-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_manager.py
More file actions
1662 lines (1373 loc) · 65.6 KB
/
Copy pathmemory_manager.py
File metadata and controls
1662 lines (1373 loc) · 65.6 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
import json
from datetime import datetime, timedelta
from typing import Dict, List, Optional
from langdetect import detect
import os
import re
class MemoryManager:
def __init__(self, memory_file: str = "bella_memory.json"):
self.memory_file = memory_file
self.memory_data = self._load_memory()
self.memory_retention = timedelta(days=30)
self.backup_dir = "memory_backups"
self.last_backup = None
self.backup_interval = timedelta(hours=1)
# Create backup directory if it doesn't exist
if not os.path.exists(self.backup_dir):
os.makedirs(self.backup_dir)
# Auto-backup on initialization
self._create_backup()
# Enhanced memory integrity check
if not self.verify_memory_integrity():
print("Attempting to repair memory structure...")
self._repair_memory()
self._create_backup() # Create backup after repair
def _repair_memory(self):
"""Advanced memory repair function"""
default_memory = self._create_default_memory()
repaired = False
# Deep merge of existing and default memory structures
for key in default_memory:
if key not in self.memory_data:
self.memory_data[key] = default_memory[key]
repaired = True
elif isinstance(default_memory[key], dict):
for subkey in default_memory[key]:
if subkey not in self.memory_data[key]:
self.memory_data[key][subkey] = default_memory[key][subkey]
repaired = True
# Validate data types
for key in self.memory_data:
if key in default_memory:
if not isinstance(self.memory_data[key], type(default_memory[key])):
self.memory_data[key] = default_memory[key]
repaired = True
if repaired:
self._save_memory()
print("Memory structure repaired successfully")
def _create_backup(self):
"""Enhanced backup system with rotation and validation"""
current_time = datetime.now()
# Check if backup is needed based on interval
if self.last_backup and (current_time - self.last_backup) < self.backup_interval:
return
timestamp = current_time.strftime("%Y%m%d_%H%M%S")
backup_path = os.path.join(self.backup_dir, f"bella_memory_backup_{timestamp}.json")
try:
# Create new backup
with open(self.memory_file, 'r') as source:
memory_data = json.load(source)
with open(backup_path, 'w') as backup:
json.dump(memory_data, backup, indent=4)
# Validate backup
with open(backup_path, 'r') as backup:
backup_data = json.load(backup)
if backup_data != memory_data:
raise ValueError("Backup validation failed")
# Update last backup time
self.last_backup = current_time
# Rotate backups (keep last 10 instead of 5)
backups = sorted([f for f in os.listdir(self.backup_dir) if f.endswith('.json')])
if len(backups) > 10:
for old_backup in backups[:-10]:
os.remove(os.path.join(self.backup_dir, old_backup))
except Exception as e:
print(f"Backup creation failed: {str(e)}")
# Try to restore from last good backup if current backup fails
self._restore_from_last_backup()
def _restore_from_last_backup(self):
"""Restore memory from most recent valid backup"""
try:
backups = sorted([f for f in os.listdir(self.backup_dir) if f.endswith('.json')], reverse=True)
for backup_file in backups:
backup_path = os.path.join(self.backup_dir, backup_file)
try:
with open(backup_path, 'r') as backup:
data = json.load(backup)
# Validate backup structure
if self._validate_memory_structure(data):
self.memory_data = data
self._save_memory()
print(f"Successfully restored from backup: {backup_file}")
return True
except:
continue
print("No valid backups found")
return False
except Exception as e:
print(f"Restore failed: {str(e)}")
return False
def _validate_memory_structure(self, data: Dict) -> bool:
"""Validate memory structure against required schema"""
required_keys = {
"users": dict,
"conversations": dict,
"instructions": dict,
"behavior_notes": list,
"owner_commands": dict,
"punishment_rules": dict,
"behavior_rules": dict,
"emotional_states": list,
"analytics": dict,
"user_reputation": dict,
"conversation_summaries": dict,
"backups": list,
"memorable_phrases": list,
"message_patterns": dict,
"conversation_styles": dict,
"user_preferences": dict,
"interaction_metrics": dict,
"relationships": dict,
"user_notes": dict,
"media_interactions": dict
}
try:
for key, expected_type in required_keys.items():
if key not in data:
return False
if not isinstance(data[key], expected_type):
return False
return True
except:
return False
def add_conversation(self, user_id: str, message: str, response: str, is_owner: bool = False):
"""Enhanced conversation tracking with analytics"""
if "conversations" not in self.memory_data:
self.memory_data["conversations"] = {}
if user_id not in self.memory_data["conversations"]:
self.memory_data["conversations"][user_id] = {}
timestamp = datetime.now().isoformat()
# Enhanced context tracking
context = {
"timestamp": timestamp,
"message_type": "owner_message" if is_owner else "user_message",
"sentiment": self._analyze_sentiment(message),
"topics": self._extract_topics(message),
"language": detect(message),
"message_length": len(message),
"response_length": len(response),
"interaction_time": timestamp
}
# Store conversation with enhanced metadata
self.memory_data["conversations"][user_id][timestamp] = {
"message": message,
"response": response,
"is_owner": is_owner,
"context": context
}
# Update analytics
self._update_analytics(user_id, context)
# Auto-backup on significant changes
if len(self.memory_data["conversations"][user_id]) % 10 == 0:
self._create_backup()
self._save_memory()
def _analyze_sentiment(self, text: str) -> str:
"""Basic sentiment analysis"""
positive_words = {'love', 'great', 'awesome', 'amazing', 'good', 'thanks', 'please'}
negative_words = {'hate', 'bad', 'stupid', 'dumb', 'idiot', 'fuck', 'shit'}
text_words = set(text.lower().split())
pos_count = len(text_words.intersection(positive_words))
neg_count = len(text_words.intersection(negative_words))
if pos_count > neg_count:
return "very_positive" if pos_count > 2 else "positive"
elif neg_count > pos_count:
return "very_negative" if neg_count > 2 else "negative"
return "neutral"
def _extract_topics(self, text: str) -> List[str]:
"""Extract main topics from text"""
# Add your topic extraction logic here
# This is a simple example
common_topics = {
'greeting': ['hi', 'hello', 'hey'],
'farewell': ['bye', 'goodbye', 'cya'],
'help': ['help', 'assist', 'support'],
'command': ['!', '/', 'command'],
'emotion': ['feel', 'happy', 'sad', 'angry']
}
found_topics = []
text_lower = text.lower()
for topic, keywords in common_topics.items():
if any(keyword in text_lower for keyword in keywords):
found_topics.append(topic)
return found_topics
def _update_analytics(self, user_id: str, context: Dict):
"""Update analytics with new interaction data"""
if "analytics" not in self.memory_data:
self.memory_data["analytics"] = {
"user_engagement": {},
"command_usage": {},
"response_metrics": {},
"error_logs": [],
"performance_metrics": {}
}
# Update user engagement
if user_id not in self.memory_data["analytics"]["user_engagement"]:
self.memory_data["analytics"]["user_engagement"][user_id] = {
"total_messages": 0,
"avg_message_length": 0,
"sentiment_distribution": {
"positive": 0,
"negative": 0,
"neutral": 0
},
"active_hours": {},
"topics_discussed": {}
}
engagement = self.memory_data["analytics"]["user_engagement"][user_id]
engagement["total_messages"] += 1
# Update average message length
engagement["avg_message_length"] = (
(engagement["avg_message_length"] * (engagement["total_messages"] - 1) +
context["message_length"]) / engagement["total_messages"]
)
# Update sentiment distribution
sentiment = context["sentiment"]
if "positive" in sentiment:
engagement["sentiment_distribution"]["positive"] += 1
elif "negative" in sentiment:
engagement["sentiment_distribution"]["negative"] += 1
else:
engagement["sentiment_distribution"]["neutral"] += 1
# Update active hours
hour = datetime.fromisoformat(context["timestamp"]).hour
engagement["active_hours"][str(hour)] = engagement["active_hours"].get(str(hour), 0) + 1
# Update topics
for topic in context["topics"]:
engagement["topics_discussed"][topic] = engagement["topics_discussed"].get(topic, 0) + 1
def _load_memory(self) -> Dict:
"""Enhanced memory loading with corruption handling"""
try:
# Try to load the main memory file
with open(self.memory_file, 'r') as f:
data = json.load(f)
# Initialize missing keys instead of replacing everything
default_memory = self._create_default_memory()
# Merge existing data with default structure
for key in default_memory:
if key not in data:
data[key] = default_memory[key]
return data
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"Memory load failed: {str(e)}, creating new memory file")
return self._create_default_memory()
def _create_default_memory(self) -> Dict:
"""Create default memory structure"""
return {
"users": {},
"conversations": {},
"instructions": {},
"behavior_notes": [],
"owner_commands": {
"permanent": [],
"temporary": []
},
"punishment_rules": {},
"behavior_rules": {},
"emotional_states": [],
"analytics": {
"user_engagement": {},
"command_usage": {},
"response_metrics": {},
"error_logs": [],
"performance_metrics": {}
},
"user_reputation": {},
"conversation_summaries": {},
"backups": [],
"memorable_phrases": [],
"message_patterns": {},
"conversation_styles": {},
"last_cleaned": datetime.now().isoformat(),
"media_interactions": {
"images": {},
"voice_messages": {},
"last_processed": None
}
}
def _save_memory(self):
"""Enhanced save with error handling"""
try:
# Create backup of current file if it exists
if os.path.exists(self.memory_file):
backup_file = f"{self.memory_file}.bak"
with open(self.memory_file, 'r') as source:
with open(backup_file, 'w') as backup:
backup.write(source.read())
# Save new data
with open(self.memory_file, 'w') as f:
json.dump(self.memory_data, f, indent=4)
except Exception as e:
print(f"Memory save failed: {str(e)}")
# If save failed and backup exists, restore from backup
if os.path.exists(f"{self.memory_file}.bak"):
os.replace(f"{self.memory_file}.bak", self.memory_file)
def _recover_from_backup(self):
"""Recover memory from most recent backup"""
try:
backups = sorted([f for f in os.listdir(self.backup_dir) if f.endswith('.json')])
if backups:
latest_backup = os.path.join(self.backup_dir, backups[-1])
with open(latest_backup, 'r') as f:
self.memory_data = json.load(f)
print("Successfully recovered from backup")
else:
print("No backups available for recovery")
except Exception as e:
print(f"Recovery failed: {str(e)}")
def _clean_old_memories(self):
current_time = datetime.now()
last_cleaned = self.memory_data.get("last_cleaned")
if last_cleaned and (current_time -
datetime.fromisoformat(last_cleaned)).days < 1:
return # Only clean once per day
for user_id in list(self.memory_data["conversations"].keys()):
conversations = self.memory_data["conversations"][user_id]
recent_convos = {}
for timestamp, convo in conversations.items():
if (current_time - datetime.fromisoformat(timestamp)
) <= self.memory_retention:
recent_convos[timestamp] = convo
if recent_convos:
self.memory_data["conversations"][user_id] = recent_convos
else:
del self.memory_data["conversations"][user_id]
self.memory_data["last_cleaned"] = current_time.isoformat()
self._save_memory()
def add_user_info(self, user_id: str, info: Dict):
"""Store or update user information"""
if "users" not in self.memory_data:
self.memory_data["users"] = {}
if user_id not in self.memory_data["users"]:
self.memory_data["users"][user_id] = {
"name": None,
"first_seen": datetime.now().isoformat(),
"last_seen": datetime.now().isoformat(),
"preferences": {},
"traits": [],
"personal_info": {},
"nicknames": [],
"remembered_facts": [],
"conversation_style": "default"
}
user_data = self.memory_data["users"][user_id]
user_data["last_seen"] = datetime.now().isoformat()
# Update specific fields while preserving existing data
if "name" in info:
user_data["personal_info"]["name"] = info["name"]
if info["name"] not in user_data["nicknames"]:
user_data["nicknames"].append(info["name"])
if "fact" in info:
if info["fact"] not in user_data["remembered_facts"]:
user_data["remembered_facts"].append({
"fact": info["fact"],
"timestamp": datetime.now().isoformat()
})
if "preference" in info:
user_data["preferences"][info["preference"]["type"]] = info["preference"]["value"]
self._save_memory()
def add_conversation(self, user_id: str, message: str, response: str, is_owner: bool):
"""Enhanced conversation storage with detailed memory"""
if "conversations" not in self.memory_data:
self.memory_data["conversations"] = {}
if user_id not in self.memory_data["conversations"]:
self.memory_data["conversations"][user_id] = {}
timestamp = datetime.now().isoformat()
# Enhanced context tracking with more details
context = {
"timestamp": timestamp,
"message_type": self._determine_message_type(message),
"sentiment": self._analyze_sentiment(message),
"language": detect(message) if message else "unknown",
"user_state": self._get_user_state(user_id),
"conversation_chain": self._get_conversation_chain(user_id),
"active_rules": self._get_active_rules(user_id),
"environmental_context": {
"time_of_day": datetime.now().strftime("%H:%M"),
"day_of_week": datetime.now().strftime("%A"),
"server_load": self._get_server_load()
},
"keywords": self._extract_keywords(message),
"topics": self._identify_topics(message),
"references": self._find_references(message),
"emotional_context": self._get_emotional_context()
}
self.memory_data["conversations"][user_id][timestamp] = {
"message": message,
"response": response,
"is_owner": is_owner,
"context": context,
"related_memories": self._find_related_memories(message, user_id),
"instruction_references": self._find_relevant_instructions(message)
}
# Process and store detailed patterns
self._process_conversation_patterns(user_id, message, context)
self._save_memory()
def get_recent_conversations(self,
user_id: str,
limit: int = 5) -> List[Dict]:
"""Get recent conversations with a user"""
if user_id not in self.memory_data.get("conversations", {}):
return []
conversations = self.memory_data["conversations"][user_id]
sorted_convos = sorted([{
"timestamp": ts,
**conv
} for ts, conv in conversations.items()],
key=lambda x: x["timestamp"],
reverse=True)
return sorted_convos[:limit]
def get_user_info(self, user_id: str) -> Dict:
"""Get comprehensive user information"""
if user_id not in self.memory_data["users"]:
self.memory_data["users"][user_id] = {
"name": None,
"first_seen": datetime.now().isoformat(),
"last_seen": datetime.now().isoformat(),
"preferences": {},
"traits": [],
"personal_info": {
"name": None,
"remembered_facts": [],
"nicknames": []
},
"conversation_style": "default",
"sentiment_history": []
}
return self.memory_data["users"][user_id]
def get_conversation_summary(self, user_id: str) -> str:
"""Enhanced conversation summary with better context"""
recent_convos = self.get_recent_conversations(user_id, limit=10) # Increased from 5
user_info = self.get_user_info(user_id)
behavior_rules = self.get_user_behavior_rules(user_id)
punishment_history = self.get_punishment_history(user_id)
if not any([recent_convos, user_info, behavior_rules, punishment_history]):
return ""
summary = []
if user_info:
summary.append("👤 User Profile:")
for key, value in user_info.items():
summary.append(f"- {key}: {value}")
if behavior_rules:
summary.append("\n🎭 Behavior Rules:")
summary.append(behavior_rules)
if punishment_history:
summary.append("\n⚠️ Punishment History:")
summary.append(punishment_history)
if recent_convos:
summary.append("\n💬 Recent Interactions:")
for convo in recent_convos:
timestamp = datetime.fromisoformat(convo["timestamp"]).strftime("%Y-%m-%d %H:%M")
context = convo.get("context", {})
summary.append(f"[{timestamp}] ({context.get('message_type', 'conversation')})")
summary.append(f"User: {convo['message']}")
summary.append(f"Bella: {convo['response']}")
if context.get("sentiment"):
summary.append(f"Sentiment: {context['sentiment']}")
summary.append("")
return "\n".join(summary)
def get_punishment_history(self, user_id: str) -> str:
"""Get user's punishment history"""
if "punishment_rules" not in self.memory_data:
return ""
history = []
for rule_id, rule in self.memory_data["punishment_rules"].items():
if rule_id == user_id:
timestamp = datetime.fromisoformat(rule["timestamp"]).strftime("%Y-%m-%d %H:%M")
punishment_type = rule["type"]
duration = f" for {rule['duration']} minutes" if rule.get("duration") else ""
status = "Active" if rule.get("active", True) else "Inactive"
history.append(f"[{timestamp}] {status} - {punishment_type}{duration}")
return "\n".join(history) if history else ""
def get_all_users_summary(self) -> str:
"""Get a summary of all users Bella has interacted with"""
summary = []
for user_id, conversations in self.memory_data.get(
"conversations", {}).items():
# Get the most recent conversation
sorted_convos = sorted(conversations.items(),
key=lambda x: x[0],
reverse=True)
if sorted_convos:
latest_convo = sorted_convos[0][1]
is_owner = latest_convo.get("is_owner", False)
user_type = "👤 Regular user" if is_owner else "👤 Regular user"
summary.append(f"User {user_id} ({user_type}):")
summary.append(f"Last interaction: {latest_convo['message']}")
summary.append(f"My response: {latest_convo['response']}\n")
if not summary:
return "No previous users in memory."
return "\n".join(summary)
def get_user_personality(self, user_id: str) -> str:
"""Analyze user's personality based on past interactions"""
conversations = self.get_recent_conversations(user_id)
if not conversations:
return "No previous interaction data"
# Count message characteristics
total_msgs = len(conversations)
polite_count = sum(1 for conv in conversations if any(
word in conv['message'].lower()
for word in ['please', 'thank', 'thanks', 'kind']))
question_count = sum(1 for conv in conversations
if '?' in conv['message'])
# Simple personality analysis
traits = []
if polite_count / total_msgs > 0.3:
traits.append("generally polite")
if question_count / total_msgs > 0.5:
traits.append("very curious")
if len(traits) == 0:
traits.append("neutral personality")
return ", ".join(traits)
def add_instruction(self, user_id: str, instruction: str, is_permanent: bool = True):
"""Store user instructions with context"""
if "instructions" not in self.memory_data:
self.memory_data["instructions"] = {}
if user_id not in self.memory_data["instructions"]:
self.memory_data["instructions"][user_id] = []
instruction_data = {
"instruction": instruction,
"timestamp": datetime.now().isoformat(),
"is_permanent": is_permanent,
"last_used": None,
"usage_count": 0,
"context": {
"user_state": self._get_user_state(user_id),
"conversation_context": self._get_conversation_context(user_id),
"emotional_state": self._get_emotional_context()
}
}
self.memory_data["instructions"][user_id].append(instruction_data)
self._save_memory()
def add_behavior_note(self, note: str):
"""Store general behavior notes and personality traits"""
if "behavior_notes" not in self.memory_data:
self.memory_data["behavior_notes"] = []
timestamp = datetime.now().isoformat()
self.memory_data["behavior_notes"].append({
"timestamp": timestamp,
"note": note
})
self._save_memory()
def get_important_instructions(self, user_id: str = None) -> str:
"""Get summary of important instructions, optionally filtered by user"""
if "instructions" not in self.memory_data:
return "No stored instructions."
summary = []
instructions = self.memory_data["instructions"]
if user_id:
if user_id not in instructions:
return "No instructions from this user."
user_instructions = instructions[user_id]
summary.append(f"Instructions from user {user_id}:")
for inst in sorted(user_instructions,
key=lambda x: x["timestamp"],
reverse=True)[:5]:
timestamp = datetime.fromisoformat(
inst["timestamp"]).strftime("%Y-%m-%d")
summary.append(
f"[{timestamp}] {'👑 ' if inst['is_owner'] else ''}Instruction: {inst['instruction']}"
)
else:
# Get most recent instructions from all users
all_instructions = []
for uid, user_instructions in instructions.items():
for inst in user_instructions:
all_instructions.append((uid, inst))
sorted_instructions = sorted(all_instructions,
key=lambda x: x[1]["timestamp"],
reverse=True)[:10]
for uid, inst in sorted_instructions:
timestamp = datetime.fromisoformat(
inst["timestamp"]).strftime("%Y-%m-%d")
user_type = " Owner" if inst["is_owner"] else "User"
summary.append(
f"[{timestamp}] {user_type} {uid}: {inst['instruction']}"
)
return "\n".join(summary)
def get_behavior_summary(self) -> str:
"""Get summary of Bella's learned behaviors and personality traits"""
if "behavior_notes" not in self.memory_data:
return "No behavior notes stored."
notes = self.memory_data["behavior_notes"]
recent_notes = sorted(notes,
key=lambda x: x["timestamp"],
reverse=True)[:5]
summary = ["Recent behavior notes:"]
for note in recent_notes:
timestamp = datetime.fromisoformat(
note["timestamp"]).strftime("%Y-%m-%d")
summary.append(f"[{timestamp}] {note['note']}")
return "\n".join(summary)
def add_owner_command(self, command: str, permanent: bool = True):
"""Store permanent commands from the owner"""
if "owner_commands" not in self.memory_data:
self.memory_data["owner_commands"] = {
"permanent": [],
"temporary": []
}
timestamp = datetime.now().isoformat()
command_data = {
"timestamp": timestamp,
"command": command,
"active": True
}
if permanent:
self.memory_data["owner_commands"]["permanent"].append(
command_data)
else:
self.memory_data["owner_commands"]["temporary"].append(
command_data)
self._save_memory()
def get_active_owner_commands(self) -> str:
"""Get all active commands from the owner"""
if "owner_commands" not in self.memory_data:
return "No owner commands stored."
summary = []
# Get permanent commands
permanent = self.memory_data["owner_commands"].get("permanent", [])
if permanent:
summary.append("🔒 Permanent Commands:")
for cmd in permanent:
if cmd.get("active", True):
timestamp = datetime.fromisoformat(
cmd["timestamp"]).strftime("%Y-%m-%d")
summary.append(f"[{timestamp}] {cmd['command']}")
# Get temporary commands
temporary = self.memory_data["owner_commands"].get("temporary", [])
if temporary:
if summary: # Add spacing if there were permanent commands
summary.append("")
summary.append("⏳ Temporary Commands:")
for cmd in temporary:
if cmd.get("active", True):
timestamp = datetime.fromisoformat(
cmd["timestamp"]).strftime("%Y-%m-%d")
summary.append(f"[{timestamp}] {cmd['command']}")
return "\n".join(summary) if summary else "No active owner commands."
def add_punishment_rule(self,
target_id: str,
punishment_type: str,
duration: int = None):
"""Store permanent punishment rules set by owner"""
if "punishment_rules" not in self.memory_data:
self.memory_data["punishment_rules"] = {}
timestamp = datetime.now().isoformat()
self.memory_data["punishment_rules"][target_id] = {
"timestamp": timestamp,
"type": punishment_type, # 'ban', 'kick', or 'timeout'
"duration": duration, # in minutes for timeout, None for ban/kick
"active": True
}
self._save_memory()
def get_punishment_rule(self, user_id: str) -> Optional[Dict]:
"""Get active punishment rule for a user if it exists"""
if "punishment_rules" not in self.memory_data:
return None
rule = self.memory_data["punishment_rules"].get(user_id)
if rule and rule.get("active", True):
return rule
return None
def remove_punishment_rule(self, user_id: str):
"""Remove punishment rule for a user"""
if "punishment_rules" in self.memory_data:
if user_id in self.memory_data["punishment_rules"]:
del self.memory_data["punishment_rules"][user_id]
self._save_memory()
def get_active_punishments_summary(self) -> str:
"""Get summary of all active punishments"""
if "punishment_rules" not in self.memory_data:
return "No active punishments."
summary = []
for user_id, rule in self.memory_data["punishment_rules"].items():
if rule.get("active", True):
punishment_type = rule["type"]
duration = f" for {rule['duration']} minutes" if rule.get(
"duration") else ""
summary.append(f"User {user_id}: {punishment_type}{duration}")
return "\n".join(summary) if summary else "No active punishments."
def add_behavior_rule(self, target_id: str, behavior: str, is_owner_command: bool = True):
"""Store behavior rules for specific users with treatment types"""
if "behavior_rules" not in self.memory_data:
self.memory_data["behavior_rules"] = {}
timestamp = datetime.now().isoformat()
if target_id not in self.memory_data["behavior_rules"]:
self.memory_data["behavior_rules"][target_id] = []
# Determine behavior type from command
behavior_lower = behavior.lower()
if any(phrase in behavior_lower for phrase in ["not behave", "don't behave", "be mean", "be rude"]):
behavior_type = "hostile"
elif any(phrase in behavior_lower for phrase in ["behave", "be nice", "be kind", "be good"]):
behavior_type = "friendly"
else:
behavior_type = "neutral"
# Deactivate previous rules for this user
for rule in self.memory_data["behavior_rules"][target_id]:
rule["active"] = False
self.memory_data["behavior_rules"][target_id].append({
"timestamp": timestamp,
"behavior": behavior,
"behavior_type": behavior_type,
"is_owner_command": is_owner_command,
"active": True
})
self._save_memory()
def get_user_behavior_rules(self, user_id: str) -> str:
"""Get active behavior rules for a specific user"""
if "behavior_rules" not in self.memory_data:
return "No behavior rules."
rules = self.memory_data["behavior_rules"].get(user_id, [])
active_rules = [rule for rule in rules if rule.get("active", True)]
if not active_rules:
return "No active behavior rules."
return "\n".join(f"- {rule['behavior']}" for rule in active_rules)
def get_user_behavior_type(self, user_id: str) -> str:
"""Get the current behavior type for a user"""
if "behavior_rules" not in self.memory_data:
return "neutral"
rules = self.memory_data["behavior_rules"].get(user_id, [])
active_rules = [rule for rule in rules if rule.get("active", True)]
if not active_rules:
return "neutral"
# Get most recent active rule
latest_rule = max(active_rules, key=lambda x: x["timestamp"])
return latest_rule.get("behavior_type", "neutral")
def clear_all_memory(self):
"""Clear all stored memory and reset to initial state"""
self.memory_data = {
"users": {},
"conversations": {},
"instructions": {},
"behavior_notes": [],
"owner_commands": {
"permanent": [],
"temporary": []
},
"punishment_rules": {},
"behavior_rules": {},
"last_cleaned": datetime.now().isoformat()
}
self._save_memory()
def add_analytics_data(self):
"""Add analytics tracking to memory structure"""
if "analytics" not in self.memory_data:
self.memory_data["analytics"] = {
"user_engagement": {}, # Track user interaction frequency
"command_usage": {}, # Track command usage statistics
"response_metrics": {}, # Track response effectiveness
"error_logs": [], # Track errors and issues
"performance_metrics": {} # Track response times and system performance
}
def manage_user_reputation(self, user_id: str, action: str, value: int = 1):
"""Track user reputation based on interactions"""
if "user_reputation" not in self.memory_data:
self.memory_data["user_reputation"] = {}
if user_id not in self.memory_data["user_reputation"]:
self.memory_data["user_reputation"][user_id] = {
"score": 0,
"history": [],
"badges": [],
"warnings": 0
}
user_rep = self.memory_data["user_reputation"][user_id]
timestamp = datetime.now().isoformat()
if action == "positive":
user_rep["score"] += value
elif action == "negative":
user_rep["score"] -= value
user_rep["history"].append({
"timestamp": timestamp,
"action": action,
"value": value
})
self._save_memory()
def create_backup(self):
"""Create timestamped backup of memory"""
backup_time = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_file = f"backup_{backup_time}_bella_memory.json"
with open(backup_file, 'w') as f:
json.dump(self.memory_data, f, indent=4)
# Keep track of backups
if "backups" not in self.memory_data:
self.memory_data["backups"] = []
self.memory_data["backups"].append({
"timestamp": datetime.now().isoformat(),
"filename": backup_file
})
self._save_memory()
def restore_from_backup(self, backup_file: str):
"""Restore memory from backup"""
try:
with open(backup_file, 'r') as f:
self.memory_data = json.load(f)
self._save_memory()
return True
except Exception as e:
print(f"Restore failed: {str(e)}")
return False
def optimize_memory(self):
"""Optimize memory usage by compressing old data"""
for user_id in self.memory_data["conversations"]:
conversations = self.memory_data["conversations"][user_id]
if len(conversations) > 100: # Threshold for optimization
# Summarize old conversations
old_convos = dict(sorted(conversations.items())[:50]) # Get oldest 50
summary = self._generate_conversation_summary(old_convos)
# Replace old conversations with summary
new_convos = dict(sorted(conversations.items())[50:]) # Keep newest 50
self.memory_data["conversations"][user_id] = new_convos
# Store summary
if "conversation_summaries" not in self.memory_data:
self.memory_data["conversation_summaries"] = {}
if user_id not in self.memory_data["conversation_summaries"]:
self.memory_data["conversation_summaries"][user_id] = []
self.memory_data["conversation_summaries"][user_id].append({
"period": f"{min(old_convos.keys())} to {max(old_convos.keys())}",
"summary": summary
})
def add_emotional_state(self, emotion: str, intensity: int, thought: str):
"""Track Bella's emotional state and unfiltered thoughts"""
if "emotional_states" not in self.memory_data:
self.memory_data["emotional_states"] = []
timestamp = datetime.now().isoformat()
self.memory_data["emotional_states"].append({
"timestamp": timestamp,
"emotion": emotion, # e.g., "angry", "happy", "sassy"
"intensity": intensity, # 1-10 scale
"raw_thought": thought, # Unfiltered thought
"is_expressed": False # Track if this thought was expressed