Raiff1982 commited on
Commit
bffcfbc
·
verified ·
1 Parent(s): eaf1a8d

Update src/utils/cocoon_manager.py

Browse files
Files changed (1) hide show
  1. src/utils/cocoon_manager.py +139 -136
src/utils/cocoon_manager.py CHANGED
@@ -1,137 +1,140 @@
1
- from datetime import datetime
2
- import os
3
- import json
4
- import logging
5
- from typing import List, Dict, Any, Optional
6
-
7
- logger = logging.getLogger(__name__)
8
-
9
- class CocoonManager:
10
- """Manages Codette's cocoon data storage and retrieval"""
11
-
12
- def __init__(self, base_dir: str = "./cocoons"):
13
- self.base_dir = base_dir
14
- self.cocoon_data = []
15
- self.quantum_state = {"coherence": 0.5}
16
- self._ensure_cocoon_dir()
17
-
18
- def _ensure_cocoon_dir(self):
19
- """Ensure cocoon directory exists"""
20
- os.makedirs(self.base_dir, exist_ok=True)
21
-
22
- def load_cocoons(self) -> None:
23
- """Load all cocoon data from files"""
24
- try:
25
- # Ensure directory exists
26
- os.makedirs(self.base_dir, exist_ok=True)
27
-
28
- cocoon_files = [
29
- f for f in os.listdir(self.base_dir)
30
- if f.endswith('.cocoon')
31
- ]
32
- logger.info(f"Found {len(cocoon_files)} cocoon files in {self.base_dir}")
33
-
34
- loaded_data = []
35
- for fname in cocoon_files:
36
- try:
37
- full_path = os.path.join(self.base_dir, fname)
38
- with open(full_path, 'r') as f:
39
- cocoon = json.load(f)
40
- if self._validate_cocoon(cocoon):
41
- loaded_data.append(cocoon)
42
- # Update quantum state if present and most recent
43
- current_quantum_state = cocoon.get('data', {}).get('quantum_state')
44
- if current_quantum_state:
45
- # Convert list quantum state to dict if needed
46
- if isinstance(current_quantum_state, list):
47
- current_quantum_state = {
48
- "coherence": sum(current_quantum_state) / len(current_quantum_state)
49
- if current_quantum_state else 0.5
50
- }
51
- # Update if we don't have state yet or if this cocoon is more recent
52
- if (not isinstance(self.quantum_state, dict) or
53
- not self.quantum_state.get('coherence') or
54
- not loaded_data[:-1] or
55
- cocoon['timestamp'] > loaded_data[-2]['timestamp']):
56
- self.quantum_state = current_quantum_state.copy() if isinstance(current_quantum_state, dict) else {"coherence": 0.5}
57
- except Exception as e:
58
- logger.error(f"Error loading cocoon {fname}: {e}")
59
- continue
60
-
61
- # Sort by timestamp and handle empty timestamps
62
- self.cocoon_data = sorted(
63
- [c for c in loaded_data if isinstance(c, dict) and self._validate_cocoon(c)],
64
- key=lambda x: x.get('timestamp', '0'),
65
- reverse=True
66
- )
67
- logger.info(f"Successfully loaded {len(self.cocoon_data)} valid cocoons")
68
-
69
- logger.info(
70
- f"Loaded {len(self.cocoon_data)} cocoons "
71
- f"with quantum coherence {self.quantum_state.get('coherence', 0.5)}"
72
- )
73
-
74
- except Exception as e:
75
- logger.error(f"Error loading cocoons: {e}")
76
- self.cocoon_data = []
77
- # Ensure we have a valid quantum state
78
- if not isinstance(self.quantum_state, dict) or 'coherence' not in self.quantum_state:
79
- self.quantum_state = {"coherence": 0.5}
80
-
81
- def _validate_cocoon(self, cocoon: Dict[str, Any]) -> bool:
82
- """Validate cocoon data structure"""
83
- required_fields = ['timestamp', 'data']
84
- return all(field in cocoon for field in required_fields)
85
-
86
- def save_cocoon(
87
- self,
88
- data: Dict[str, Any],
89
- cocoon_type: str = "codette"
90
- ) -> bool:
91
- """Save new cocoon data to file"""
92
- try:
93
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
94
- filename = f"{cocoon_type}_cocoon_{timestamp}.cocoon"
95
- filepath = os.path.join(self.base_dir, filename)
96
-
97
- # If data has its own quantum state, update our state
98
- if "quantum_state" in data:
99
- self.quantum_state = data["quantum_state"]
100
-
101
- cocoon = {
102
- "timestamp": timestamp,
103
- "data": {
104
- **data,
105
- "quantum_state": self.quantum_state.copy()
106
- }
107
- }
108
-
109
- with open(filepath, 'w') as f:
110
- json.dump(cocoon, f, indent=2)
111
-
112
- self.cocoon_data.insert(0, cocoon)
113
- logger.info(f"Saved cocoon: {filename}")
114
- return True
115
-
116
- except Exception as e:
117
- logger.error(f"Error saving cocoon: {e}")
118
- return False
119
-
120
- def get_latest_quantum_state(self) -> Dict[str, float]:
121
- """Get the most recent quantum state"""
122
- return self.quantum_state.copy()
123
-
124
- def get_latest_cocoons(self, limit: int = 5) -> List[Dict[str, Any]]:
125
- """Get the most recent cocoons"""
126
- return self.cocoon_data[:limit]
127
-
128
- def update_quantum_state(self, new_state: Dict[str, float]) -> None:
129
- """Update the current quantum state and save it"""
130
- self.quantum_state.update(new_state)
131
- logger.info(f"Updated quantum state: {self.quantum_state}")
132
-
133
- # Save the new state in a cocoon
134
- self.save_cocoon({
135
- "type": "quantum_update",
136
- "quantum_state": self.quantum_state.copy()
 
 
 
137
  })
 
1
+ from datetime import datetime
2
+ import os
3
+ import json
4
+ import logging
5
+ from typing import List, Dict, Any, Optional
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ class CocoonManager:
10
+ """Manages Codette's cocoon data storage and retrieval"""
11
+
12
+ def __init__(self, base_dir: str = "./cocoons"):
13
+ self.base_dir = base_dir
14
+ self.cocoon_data = []
15
+ self.quantum_state = {"coherence": 0.5}
16
+ self._ensure_cocoon_dir()
17
+
18
+ def _ensure_cocoon_dir(self):
19
+ """Ensure cocoon directory exists"""
20
+ os.makedirs(self.base_dir, exist_ok=True)
21
+
22
+ def load_cocoons(self) -> None:
23
+ """Load all cocoon data from files"""
24
+ try:
25
+ # Ensure directory exists
26
+ os.makedirs(self.base_dir, exist_ok=True)
27
+
28
+ cocoon_files = [
29
+ f for f in os.listdir(self.base_dir)
30
+ if f.endswith('.cocoon')
31
+ ]
32
+ logger.info(f"Found {len(cocoon_files)} cocoon files in {self.base_dir}")
33
+
34
+ loaded_data = []
35
+ for fname in cocoon_files:
36
+ try:
37
+ full_path = os.path.join(self.base_dir, fname)
38
+ with open(full_path, 'r') as f:
39
+ cocoon = json.load(f)
40
+ if self._validate_cocoon(cocoon):
41
+ loaded_data.append(cocoon)
42
+ # Update quantum state if present and most recent
43
+ current_quantum_state = cocoon.get('data', {}).get('quantum_state')
44
+ if current_quantum_state:
45
+ # Convert list quantum state to dict if needed
46
+ if isinstance(current_quantum_state, list):
47
+ current_quantum_state = {
48
+ "coherence": sum(current_quantum_state) / len(current_quantum_state)
49
+ if current_quantum_state else 0.5
50
+ }
51
+ # Update if we don't have state yet or if this cocoon is more recent
52
+ if (not isinstance(self.quantum_state, dict) or
53
+ not self.quantum_state.get('coherence') or
54
+ not loaded_data[:-1] or
55
+ cocoon['timestamp'] > loaded_data[-2]['timestamp']):
56
+ self.quantum_state = current_quantum_state.copy() if isinstance(current_quantum_state, dict) else {"coherence": 0.5}
57
+ except Exception as e:
58
+ logger.error(f"Error loading cocoon {fname}: {e}")
59
+ continue
60
+
61
+ # Sort by timestamp and handle empty timestamps
62
+ self.cocoon_data = sorted(
63
+ [c for c in loaded_data if isinstance(c, dict) and self._validate_cocoon(c)],
64
+ key=lambda x: x.get('timestamp', '0'),
65
+ reverse=True
66
+ )
67
+ logger.info(f"Successfully loaded {len(self.cocoon_data)} valid cocoons")
68
+
69
+ logger.info(
70
+ f"Loaded {len(self.cocoon_data)} cocoons "
71
+ f"with quantum coherence {self.quantum_state.get('coherence', 0.5)}"
72
+ )
73
+
74
+ except Exception as e:
75
+ logger.error(f"Error loading cocoons: {e}")
76
+ self.cocoon_data = []
77
+ # Ensure we have a valid quantum state
78
+ if not isinstance(self.quantum_state, dict) or 'coherence' not in self.quantum_state:
79
+ self.quantum_state = {"coherence": 0.5}
80
+
81
+ def _validate_cocoon(self, cocoon: Dict[str, Any]) -> bool:
82
+ """Validate cocoon data structure"""
83
+ required_fields = ['timestamp', 'data']
84
+ return all(field in cocoon for field in required_fields)
85
+
86
+ def save_cocoon(
87
+ self,
88
+ data: Dict[str, Any],
89
+ cocoon_type: str = "codette"
90
+ ) -> bool:
91
+ """Save new cocoon data to file"""
92
+ try:
93
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
94
+ filename = f"{cocoon_type}_cocoon_{timestamp}.cocoon"
95
+ filepath = os.path.join(self.base_dir, filename)
96
+
97
+ # If data has its own quantum state, update our state
98
+ if "quantum_state" in data:
99
+ self.quantum_state = data["quantum_state"]
100
+
101
+ cocoon = {
102
+ "timestamp": timestamp,
103
+ "data": {
104
+ **data,
105
+ "quantum_state": self.quantum_state.copy()
106
+ }
107
+ }
108
+
109
+ with open(filepath, 'w') as f:
110
+ json.dump(cocoon, f, indent=2)
111
+
112
+ self.cocoon_data.insert(0, cocoon)
113
+ logger.info(f"Saved cocoon: {filename}")
114
+ return True
115
+
116
+ except Exception as e:
117
+ logger.error(f"Error saving cocoon: {e}")
118
+ return False
119
+
120
+ def get_latest_quantum_state(self) -> Dict[str, float]:
121
+ """Get the most recent quantum state"""
122
+ # Ensure quantum_state is always a proper dict
123
+ if not isinstance(self.quantum_state, dict):
124
+ self.quantum_state = {"coherence": 0.5}
125
+ return self.quantum_state.copy()
126
+
127
+ def get_latest_cocoons(self, limit: int = 5) -> List[Dict[str, Any]]:
128
+ """Get the most recent cocoons"""
129
+ return self.cocoon_data[:limit]
130
+
131
+ def update_quantum_state(self, new_state: Dict[str, float]) -> None:
132
+ """Update the current quantum state and save it"""
133
+ self.quantum_state.update(new_state)
134
+ logger.info(f"Updated quantum state: {self.quantum_state}")
135
+
136
+ # Save the new state in a cocoon
137
+ self.save_cocoon({
138
+ "type": "quantum_update",
139
+ "quantum_state": self.quantum_state.copy()
140
  })