File size: 2,548 Bytes
7f5ef51 |
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 |
import json
import os
import random
from typing import Union, Dict, Any
from cryptography.fernet import Fernet
class CognitionCocooner:
def __init__(self, storage_path: str = "cocoons", encryption_key: bytes = None):
self.storage_path = storage_path
os.makedirs(self.storage_path, exist_ok=True)
self.key = encryption_key or Fernet.generate_key()
self.fernet = Fernet(self.key)
def wrap(self, thought: Dict[str, Any], type_: str = "prompt") -> str:
cocoon = {
"type": type_,
"id": f"cocoon_{random.randint(1000,9999)}",
"wrapped": self._generate_wrapper(thought, type_)
}
file_path = os.path.join(self.storage_path, cocoon["id"] + ".json")
with open(file_path, "w") as f:
json.dump(cocoon, f)
return cocoon["id"]
def unwrap(self, cocoon_id: str) -> Union[str, Dict[str, Any]]:
file_path = os.path.join(self.storage_path, cocoon_id + ".json")
if not os.path.exists(file_path):
raise FileNotFoundError(f"Cocoon {cocoon_id} not found.")
with open(file_path, "r") as f:
cocoon = json.load(f)
return cocoon["wrapped"]
def wrap_encrypted(self, thought: Dict[str, Any]) -> str:
encrypted = self.fernet.encrypt(json.dumps(thought).encode()).decode()
cocoon = {
"type": "encrypted",
"id": f"cocoon_{random.randint(10000,99999)}",
"wrapped": encrypted
}
file_path = os.path.join(self.storage_path, cocoon["id"] + ".json")
with open(file_path, "w") as f:
json.dump(cocoon, f)
return cocoon["id"]
def unwrap_encrypted(self, cocoon_id: str) -> Dict[str, Any]:
file_path = os.path.join(self.storage_path, cocoon_id + ".json")
if not os.path.exists(file_path):
raise FileNotFoundError(f"Cocoon {cocoon_id} not found.")
with open(file_path, "r") as f:
cocoon = json.load(f)
decrypted = self.fernet.decrypt(cocoon["wrapped"].encode()).decode()
return json.loads(decrypted)
def _generate_wrapper(self, thought: Dict[str, Any], type_: str) -> Union[str, Dict[str, Any]]:
if type_ == "prompt":
return f"What does this mean in context? {thought}"
elif type_ == "function":
return f"def analyze(): return {thought}"
elif type_ == "symbolic":
return {k: round(v, 2) for k, v in thought.items()}
else:
return thought
|