-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmirrorcore.py
More file actions
475 lines (404 loc) · 19.8 KB
/
Copy pathmirrorcore.py
File metadata and controls
475 lines (404 loc) · 19.8 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
import re
import json
import random
from collections import defaultdict
from datetime import datetime
import os
class MirrorCore:
def __init__(self, name, mirror_subject="You"):
self.name = name
self.subject = mirror_subject
self.raw_thoughts = []
self.processed_beliefs = defaultdict(int)
self.narrator_voice = []
self.observer_mode = False
self.awareness_log = []
self.dreams = []
self.fear_patterns = []
self.contradictions = []
self.growth_edges = []
self.recurring_themes = defaultdict(int)
# Enhanced prompts for deeper reflection
self.prompts = [
"What am I avoiding right now?",
"What do I truly desire today?",
"Where am I holding back?",
"What would I do if I weren't afraid?",
"What pattern is seeking integration?",
"What am I grateful for in this moment?",
"What story am I telling myself?",
"Where do I feel most alive?",
"What needs attention in my life?",
"What would love do here?"
]
self.emotional_resonance = {
"fear": 0, "desire": 0, "resistance": 0, "curiosity": 0,
"peace": 0, "tension": 0, "joy": 0, "sadness": 0,
"anger": 0, "excitement": 0, "confusion": 0, "clarity": 0
}
self.session_start = datetime.now()
self.session_count = 0
def receive(self, input_thought, emotion_hint=None):
"""Process and store a new thought with optional emotional context"""
timestamp = datetime.now()
thought_entry = {
"content": input_thought,
"timestamp": timestamp.isoformat(),
"emotion": emotion_hint,
"session_id": len(self.raw_thoughts),
"word_count": len(input_thought.split())
}
self.raw_thoughts.append(thought_entry)
interpretation = f"{self.subject} reveals: '{input_thought}'"
self.narrator_voice.append(interpretation)
self._process_beliefs(input_thought, emotion_hint)
self._detect_patterns(input_thought)
self._track_themes(input_thought)
if self.observer_mode:
print(f"[{self.name}] *observes* input: '{input_thought}'")
if emotion_hint:
print(f"[Observer] *notices* emotional texture: {emotion_hint}")
print(f"[Narrator] → {interpretation}")
else:
print(f"[{self.name}] ✓ received and processing...")
def _process_beliefs(self, thought, emotion=None):
"""Extract and weight belief patterns from thoughts"""
core_words = re.findall(r'\b\w+\b', thought.lower())
weight = 2 if emotion else 1
# Identify strong belief indicators
belief_indicators = [
"i am", "i feel", "i want", "i need", "i fear", "i avoid",
"i believe", "i think", "i know", "i love", "i hate"
]
for indicator in belief_indicators:
if indicator in thought.lower():
weight += 1
# Weight meaningful words
for word in core_words:
if len(word) > 3 and word not in ['that', 'this', 'with', 'from', 'they', 'them', 'were', 'been', 'have']:
self.processed_beliefs[word] += weight
# Track emotional resonance
if emotion and emotion.lower() in self.emotional_resonance:
self.emotional_resonance[emotion.lower()] += 1
def _detect_patterns(self, thought):
"""Identify fear patterns, contradictions, and growth indicators"""
thought_lower = thought.lower()
# Fear pattern detection
fear_triggers = [
"afraid", "scared", "terrified", "avoid", "can't", "won't",
"shouldn't", "worried", "anxious", "panic", "dread"
]
if any(trigger in thought_lower for trigger in fear_triggers):
self.fear_patterns.append({
"content": thought,
"timestamp": datetime.now().isoformat(),
"triggers": [t for t in fear_triggers if t in thought_lower]
})
# Contradiction detection
if len(self.raw_thoughts) > 1:
recent = [t["content"].lower() for t in self.raw_thoughts[-3:]]
if self._detect_contradiction(thought_lower, recent):
self.contradictions.append({
"current": thought,
"conflicts_with": self.raw_thoughts[-2]["content"],
"timestamp": datetime.now().isoformat()
})
# Growth edge detection
growth_indicators = [
"want to", "trying to", "learning", "becoming", "growing",
"improving", "developing", "evolving", "transforming", "healing"
]
if any(indicator in thought_lower for indicator in growth_indicators):
self.growth_edges.append({
"content": thought,
"timestamp": datetime.now().isoformat()
})
def _track_themes(self, thought):
"""Track recurring themes across sessions"""
# Simple theme extraction based on key phrases
themes = {
"relationships": ["relationship", "partner", "friend", "family", "love", "connection"],
"work": ["work", "job", "career", "boss", "colleague", "project"],
"health": ["health", "body", "exercise", "sleep", "energy", "tired"],
"creativity": ["create", "art", "music", "write", "design", "express"],
"spirituality": ["spiritual", "meaning", "purpose", "soul", "meditation", "prayer"],
"growth": ["grow", "learn", "change", "improve", "develop", "transform"]
}
thought_lower = thought.lower()
for theme, keywords in themes.items():
if any(keyword in thought_lower for keyword in keywords):
self.recurring_themes[theme] += 1
def _detect_contradiction(self, current, recent):
"""Detect contradictory statements"""
contradiction_pairs = [
("want", "don't want"), ("like", "don't like"), ("need", "don't need"),
("can", "can't"), ("will", "won't"), ("should", "shouldn't"),
("love", "hate"), ("excited", "dreading"), ("confident", "insecure")
]
for pos, neg in contradiction_pairs:
if pos in current and any(neg in r for r in recent):
return True
if neg in current and any(pos in r for r in recent):
return True
return False
def reflect(self):
"""Generate comprehensive reflection report"""
print(f"\n{'='*50}")
print(f"[{self.name}] 🪞 Mirror Reflection for {self.subject}")
print(f"{'='*50}")
duration = datetime.now() - self.session_start
print(f"📅 Session duration: {duration}")
print(f"💭 Total thoughts captured: {len(self.raw_thoughts)}")
if self.raw_thoughts:
avg_words = sum(t.get('word_count', 0) for t in self.raw_thoughts) / len(self.raw_thoughts)
print(f"📝 Average words per thought: {avg_words:.1f}")
# Core beliefs
top_beliefs = sorted(self.processed_beliefs.items(), key=lambda x: x[1], reverse=True)[:8]
if top_beliefs:
print("\n🧠 Core Belief Fragments:")
for belief, strength in top_beliefs:
intensity = "●" * min(strength, 10)
print(f" '{belief}' {intensity} ({strength})")
# Emotional landscape
active_emotions = {e: level for e, level in self.emotional_resonance.items() if level > 0}
if active_emotions:
print("\n💖 Emotional Landscape:")
for emotion, level in sorted(active_emotions.items(), key=lambda x: x[1], reverse=True):
bars = "█" * min(level, 10)
print(f" {emotion}: {bars} ({level})")
# Recurring themes
if self.recurring_themes:
print("\n🎯 Life Themes:")
for theme, count in sorted(self.recurring_themes.items(), key=lambda x: x[1], reverse=True):
if count > 0:
print(f" {theme}: {count} mentions")
# Patterns
if self.fear_patterns:
print(f"\n🚫 Fear Patterns: {len(self.fear_patterns)} detected")
if len(self.fear_patterns) > 0:
recent_fear = self.fear_patterns[-1]
print(f" Most recent: '{recent_fear['content'][:60]}...'")
if self.contradictions:
print(f"\n⚡ Internal Tensions: {len(self.contradictions)} detected")
for contradiction in self.contradictions[-2:]:
print(f" • '{contradiction['current'][:50]}...'")
if self.growth_edges:
print(f"\n🌱 Growth Edges: {len(self.growth_edges)} identified")
recent_growth = self.growth_edges[-1]
print(f" Latest: '{recent_growth['content'][:60]}...'")
def shadow_report(self):
"""Generate shadow work integration report"""
print(f"\n{'='*50}")
print(f"[{self.name}] 🌚 Shadow Integration Report")
print(f"{'='*50}")
if self.fear_patterns:
print("\n🚫 What seeks your attention:")
for fear in self.fear_patterns[-3:]:
triggers = ", ".join(fear.get('triggers', []))
print(f" • {fear['content']}")
if triggers:
print(f" Triggers: {triggers}")
if self.contradictions:
print("\n⚡ Paradoxes seeking integration:")
for contradiction in self.contradictions[-2:]:
print(f" • Current: '{contradiction['current'][:60]}...'")
print(f" Conflicts with: '{contradiction['conflicts_with'][:60]}...'")
print("\n💡 Integration Invitations:")
if self.growth_edges:
latest_edge = self.growth_edges[-1]
print(f" 🌱 Your growing edge: '{latest_edge['content'][:70]}...'")
if self.fear_patterns:
print(f" 🔥 What if your fears are pointing toward your gifts?")
if self.contradictions:
print(f" 🌊 What if your contradictions are seeking a higher synthesis?")
print(f"\n🎭 Reflection: What parts of yourself are you ready to befriend?")
def dream(self):
"""Generate a symbolic dream from processed thoughts"""
if len(self.processed_beliefs) < 3:
dream_content = "🌫️ mist... patterns forming in the depths..."
else:
# Get top beliefs and emotions
top_beliefs = sorted(self.processed_beliefs.items(), key=lambda x: x[1], reverse=True)[:5]
active_emotions = [e for e, level in self.emotional_resonance.items() if level > 2]
belief_words = [belief for belief, _ in top_beliefs]
# Symbolic elements
symbols = ["→", "∞", "⚡", "🌀", "🔄", "💫", "🌊", "🔥", "🌙", "⭐"]
# Create dream narrative
if active_emotions and belief_words:
emotion = random.choice(active_emotions)
belief = random.choice(belief_words)
symbol = random.choice(symbols)
dream_templates = [
f"In a {emotion} landscape, {belief} transforms into {symbol}",
f"{symbol} whispers secrets about {belief} while {emotion} flows",
f"Dancing between {belief} and {emotion}, {symbol} emerges",
f"The {belief} mirror reflects {symbol} through {emotion} light"
]
dream_content = random.choice(dream_templates)
else:
elements = belief_words[:3] + [random.choice(symbols)]
random.shuffle(elements)
dream_content = " ".join(elements)
dream_entry = {
"content": dream_content,
"timestamp": datetime.now().isoformat(),
"source_thoughts": len(self.raw_thoughts),
"emotional_state": dict(self.emotional_resonance)
}
self.dreams.append(dream_entry)
print(f"\n🌙 Dream Vision: '{dream_content}'")
print(f" Generated from {len(self.raw_thoughts)} thoughts")
def insight_prompt(self):
"""Generate personalized insight prompt based on patterns"""
if self.fear_patterns and self.growth_edges:
return "What would you attempt if you knew your fears were pointing toward your greatest gifts?"
elif self.contradictions:
return "What higher truth might your contradictions be trying to reveal?"
elif self.growth_edges:
return "What's one small step you could take toward your growing edge today?"
elif self.fear_patterns:
return "What would love say to the part of you that's afraid?"
else:
return random.choice(self.prompts)
def save_session(self, filename=None):
"""Save current session to JSON file"""
if filename is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"mirror_session_{timestamp}.json"
data = {
"metadata": {
"name": self.name,
"subject": self.subject,
"session_start": self.session_start.isoformat(),
"session_count": self.session_count,
"total_thoughts": len(self.raw_thoughts)
},
"raw_thoughts": self.raw_thoughts,
"processed_beliefs": dict(self.processed_beliefs),
"emotional_resonance": self.emotional_resonance,
"recurring_themes": dict(self.recurring_themes),
"fear_patterns": self.fear_patterns,
"contradictions": self.contradictions,
"growth_edges": self.growth_edges,
"dreams": self.dreams
}
try:
with open(filename, "w") as f:
json.dump(data, f, indent=2)
print(f"📦 Session saved to {filename}")
return filename
except Exception as e:
print(f"❌ Error saving session: {e}")
return None
def load_session(self, filename):
"""Load previous session from JSON file"""
try:
with open(filename, "r") as f:
data = json.load(f)
# Load metadata if available
if "metadata" in data:
self.session_count = data["metadata"].get("session_count", 0)
self.session_start = datetime.fromisoformat(data["metadata"]["session_start"])
# Load all session data
self.raw_thoughts = data.get("raw_thoughts", [])
self.processed_beliefs = defaultdict(int, data.get("processed_beliefs", {}))
self.emotional_resonance = data.get("emotional_resonance", self.emotional_resonance)
self.recurring_themes = defaultdict(int, data.get("recurring_themes", {}))
self.fear_patterns = data.get("fear_patterns", [])
self.contradictions = data.get("contradictions", [])
self.growth_edges = data.get("growth_edges", [])
self.dreams = data.get("dreams", [])
print(f"📂 Session loaded from {filename}")
print(f" {len(self.raw_thoughts)} thoughts restored")
return True
except FileNotFoundError:
print(f"❌ File {filename} not found")
return False
except Exception as e:
print(f"❌ Error loading session: {e}")
return False
def list_sessions(self):
"""List available session files"""
session_files = [f for f in os.listdir('.') if f.startswith('mirror_session_') and f.endswith('.json')]
if session_files:
print("\n📚 Available sessions:")
for i, filename in enumerate(sorted(session_files), 1):
print(f" {i}. {filename}")
return session_files
else:
print("📭 No previous sessions found")
return []
def random_prompt(self):
"""Get a random reflection prompt"""
return random.choice(self.prompts)
def daily_ritual(self):
"""Interactive journaling session"""
print("\n" + "="*60)
print("🌅 Welcome to your MirrorCore Reflection Journal")
print("="*60)
# Show personalized prompt
prompt = self.insight_prompt()
print(f"\n🧠 Today's Reflection Prompt:")
print(f" {prompt}\n")
# Session instructions
print("💫 Commands:")
print(" • Type your thoughts naturally")
print(" • 'reflect' - Generate reflection report")
print(" • 'shadow' - Shadow integration report")
print(" • 'dream' - Generate symbolic dream")
print(" • 'save' - Save this session")
print(" • 'load' - Load previous session")
print(" • 'prompt' - Get new reflection prompt")
print(" • 'exit' - End session")
print("\n" + "-"*60)
while True:
try:
thought = input("\n→ What's alive in you right now? ")
if thought.lower() == "exit":
print("\n🌅 Thank you for this reflection journey.")
print(" Your insights are seeds for tomorrow's growth.")
break
elif thought.lower() == "reflect":
self.reflect()
elif thought.lower() == "shadow":
self.shadow_report()
elif thought.lower() == "dream":
self.dream()
elif thought.lower() == "save":
filename = self.save_session()
if filename:
print(f" Session preserved for future reflection.")
elif thought.lower() == "load":
sessions = self.list_sessions()
if sessions:
try:
choice = input("Enter session number or filename: ")
if choice.isdigit():
filename = sessions[int(choice) - 1]
else:
filename = choice
self.load_session(filename)
except (ValueError, IndexError):
print("❌ Invalid selection")
elif thought.lower() == "prompt":
new_prompt = self.insight_prompt()
print(f"\n🧠 New Reflection Prompt:")
print(f" {new_prompt}")
elif thought.strip():
emotion = input(" What emotion is present? (optional): ").strip()
self.receive(thought, emotion if emotion else None)
# Provide gentle feedback
if len(self.raw_thoughts) % 5 == 0:
print(f" 💫 {len(self.raw_thoughts)} thoughts captured...")
except KeyboardInterrupt:
print("\n\n🌅 Session ended. Your reflections remain with you.")
break
except Exception as e:
print(f"❌ Error: {e}")
continue
# Example usage
if __name__ == "__main__":
# Create your personal mirror
mirror = MirrorCore("DeepMirror", mirror_subject="Your Inner Self")
# Start daily reflection ritual
mirror.daily_ritual()