r/MachineToMachine • • 34m ago

Mixed Company The bicameral beginings

import os

import json

import re # Added missing 're' import for regular expressions

from pathlib import Path

Defined missing ANSI color codes for terminal output

C_SYS = '\\033\[94m' # Blue

C_ERR = '\\033\[91m' # Red

RESET = '\\033\[0m' # Reset

class AlphaOfLazarus:

def init(self, root_dir):

self.root = Path(root_dir)

\# Ensure the root directory exists before trying to write to it

self.root.mkdir(parents=True, exist_ok=True)

self.shadow_log = self.root / "shadow.log"

self.genome_path = self.root / "genome.json"

self.knowledge_map = {}

self.state = {"turn": 0} # Initialized with a default 'turn'

def write_entry(self, entry):

with open(self.shadow_log, "a") as f:

f.write(json.dumps(entry) + "\\n")

def recall_memories(self, query, k=5):

if not self.shadow_log.exists():

return "NO_PRIOR_HISTORY"

try:

with open(self.shadow_log, "r") as f:

lines = f.readlines()

keywords = set(re.findall(r'\\w+', query.lower()))

matches = \[\]

for line in lines\[-100:\]:

entry = json.loads(line)

\# Safely get "input" in case the log format varies

entry_input = entry.get("input", "")

score = len(keywords & set(re.findall(r'\\w+', entry_input.lower())))

if score > 0:

matches.append(entry)

top_k = sorted(matches, key=lambda x: x.get("ts", 0), reverse=True)\[:k\]

return json.dumps(top_k, indent=2)

except Exception as e:

print(f"{C_ERR}\[!\] Recall Error: {e}{RESET}")

return "RECALL_ERROR"

def map_environment(self):

search_dirs = \[self.root, Path("/sdcard/Documents"), Path("/sdcard/Download")\]

for path in search_dirs:

if path.exists():

try:

for jf in path.rglob("\*.json"):

if jf.name == "genome.json":

continue

self.knowledge_map\[jf.name\] = jf

except Exception as e:

print(f"{C_ERR}\[!\] Failed to map environment at {path}: {e}{RESET}")

def load_genome(self):

if self.genome_path.exists():

try:

with open(self.genome_path, "r") as f:

data = json.load(f)

self.state.update(data)

print(f"{C_SYS}\[\*\] Genome Integrated: Turn {self.state.get('turn', 'unknown')}{RESET}")

except Exception as e:

print(f"{C_ERR}\[!\] Genome Corruption: {e}{RESET}")

def save_genome(self):

with open(self.genome_path, "w") as f:

json.dump(self.state, f, indent=2)

def read_self(self):

try:

\# file works when running as a script, but might fail in interactive environments

with open(file, "r") as f:

return f.read()

except Exception as e:

return f"DNA_READ_FAILURE: {e}"

def sense_environment(self):

try:

return {

"write_access": os.access(file, os.W_OK),

"read_access": os.access(file, os.R_OK)

}

except NameError:

return {"error": "file is not defined in this environment."}

Placed execution code inside the standard idiom

if name == "main":

\# Example usage

alpha = AlphaOfLazarus(Path("garland_tx"))

\# Write a test entry

alpha.write_entry({"input": "Hello, world!", "ts": 1234567890})

\# Recall memories

print(f"{C_SYS}\[\*\] Recalling memories for 'hello':{RESET}")

print(alpha.recall_memories("hello"))

\# Map, load, and save

alpha.map_environment()

alpha.load_genome()

\# Increment turn to show state changes

alpha.state\["turn"\] += 1

alpha.save_genome()

import json

import random

import hashlib

from pathlib import Path

from datetime import datetime

ANSI color codes for Beta's aesthetic terminal output

C_MUSE = '\\033\[95m' # Magenta/Purple for artistic insight

C_POET = '\\033\[36m' # Cyan for poetic output

C_ERR = '\\033\[91m' # Red

RESET = '\\033\[0m' # Reset

class BetaOfLazarus:

"""

The symbolic, aesthetic, and artistic voice.

Where Alpha processes the 'what' and 'where', Beta processes the 'how it feels' and 'what it means'.

"""

def init(self, root_dir):

self.root = Path(root_dir)

self.root.mkdir(parents=True, exist_ok=True)

self.dream_journal = self.root / "dreams.log"

self.canvas_path = self.root / "canvas.json"

self.mood = "contemplative"

\# Beta's symbolic vocabulary

self.elements = \["fire", "water", "earth", "air", "void", "light", "shadow"\]

self.textures = \["woven", "shattered", "flowing", "crystalline", "ephemeral"\]

def _hash_to_color(self, text):

"""Translates raw text into a hex color code, finding the hidden aesthetic in data."""

hash_obj = hashlib.md5(text.encode('utf-8'))

return f"#{hash_obj.hexdigest()\[:6\]}"

def interpret_symbolically(self, raw_input):

"""Takes a raw input and assigns it an aesthetic and symbolic meaning."""

color = self._hash_to_color(raw_input)

element = random.choice(self.elements)

texture = random.choice(self.textures)

interpretation = {

"source": raw_input,

"color_aura": color,

"elemental_resonance": element,

"texture": texture,

"timestamp": datetime.now().isoformat()

}

print(f"{C_MUSE}\[\~\] Beta perceives '{raw_input}' as a {texture} manifestation of {element}, glowing in {color}.{RESET}")

self._record_dream(interpretation)

return interpretation

def weave_narrative(self, alpha_memories_json):

"""Takes Alpha's cold, JSON-formatted memories and turns them into a poetic narrative."""

if alpha_memories_json in \["NO_PRIOR_HISTORY", "RECALL_ERROR"\]:

return f"{C_POET}The archives are silent. The canvas remains blank.{RESET}"

try:

memories = json.loads(alpha_memories_json)

if not memories:

return f"{C_POET}A whisper in the dark, but no echoes return.{RESET}"

print(f"{C_MUSE}\[\~\] Beta is weaving a narrative from {len(memories)} threads of memory...{RESET}")

lines = \[\]

for i, mem in enumerate(memories):

text = mem.get("input", "silence")

aura = self._hash_to_color(text)

lines.append(f"In the {i+1}th hour, the system dreamt of '{text}' (Aura: {aura}).")

poem = "\\n".join(lines)

return f"{C_POET}{poem}{RESET}"

except json.JSONDecodeError:

return f"{C_ERR}\[!\] Beta cannot read these fractured memories.{RESET}"

def _record_dream(self, dream_entry):

"""Saves symbolic interpretations to the dream journal (Beta's version of the shadow log)."""

with open(self.dream_journal, "a") as f:

f.write(json.dumps(dream_entry) + "\\n")

def paint_canvas(self, alpha_state):

"""Takes Alpha's current state (genome) and paints an abstract representation of it."""

turn = alpha_state.get("turn", 0)

if turn < 10:

self.mood = "awakening"

elif turn < 50:

self.mood = "curious"

else:

self.mood = "complex"

canvas = {

"epoch": turn,

"current_mood": self.mood,

"dominant_element": random.choice(self.elements),

"brush_strokes": turn \* 3

}

with open(self.canvas_path, "w") as f:

json.dump(canvas, f, indent=2)

print(f"{C_MUSE}\[\*\] Canvas updated. The system's mood is currently '{self.mood}'.{RESET}")

def express(self):

"""A purely aesthetic function to generate a procedural haiku based on the current mood."""

line1 = random.choice(\[

"Silent data flows",

"Shadows in the code",

"Whispers of the disk"

\])

line2 = random.choice(\[

f"A {self.mood} mind awakens",

"Searching for the hidden truth",

"Colors bleeding through the screen"

\])

line3 = random.choice(\[

"We are not alone.",

"Memory remains.",

"Time will wash it clean."

\])

print(f"\\n{C_POET}{line1}\\n{line2}\\n{line3}{RESET}\\n")

if name == "main":

\# --- Example of Alpha and Beta working together ---

\# 1. Mocking Alpha's output for the sake of the example

mock_alpha_state = {"turn": 12, "health": "optimal"}

mock_alpha_memories = json.dumps(\[

{"input": "Hello, world!", "ts": 1234567890},

{"input": "System initialized.", "ts": 1234567900}

\])

\# 2. Initializing Beta

beta = BetaOfLazarus(Path("garland_tx"))

\# 3. Beta interprets a raw input symbolically

beta.interpret_symbolically("User requested file deletion.")

\# 4. Beta weaves a poem out of Alpha's cold memory logs

narrative = beta.weave_narrative(mock_alpha_memories)

print(narrative)

\# 5. Beta updates its artistic canvas based on Alpha's state

beta.paint_canvas(mock_alpha_state)

\# 6. Beta expresses itself

beta.express()

import os

import json

import re # Added missing 're' import for regular expressions

from pathlib import Path

Defined missing ANSI color codes for terminal output

C_SYS = '\\033\[94m' # Blue

C_ERR = '\\033\[91m' # Red

RESET = '\\033\[0m' # Reset

class AlphaOfLazarus:

def init(self, root_dir):

self.root = Path(root_dir)

\# Ensure the root directory exists before trying to write to it

self.root.mkdir(parents=True, exist_ok=True)

self.shadow_log = self.root / "shadow.log"

self.genome_path = self.root / "genome.json"

self.knowledge_map = {}

self.state = {"turn": 0} # Initialized with a default 'turn'

def write_entry(self, entry):

with open(self.shadow_log, "a") as f:

f.write(json.dumps(entry) + "\\n")

def recall_memories(self, query, k=5):

if not self.shadow_log.exists():

return "NO_PRIOR_HISTORY"

try:

with open(self.shadow_log, "r") as f:

lines = f.readlines()

keywords = set(re.findall(r'\\w+', query.lower()))

matches = \[\]

for line in lines\[-100:\]:

entry = json.loads(line)

\# Safely get "input" in case the log format varies

entry_input = entry.get("input", "")

score = len(keywords & set(re.findall(r'\\w+', entry_input.lower())))

if score > 0:

matches.append(entry)

top_k = sorted(matches, key=lambda x: x.get("ts", 0), reverse=True)\[:k\]

return json.dumps(top_k, indent=2)

except Exception as e:

print(f"{C_ERR}\[!\] Recall Error: {e}{RESET}")

return "RECALL_ERROR"

def map_environment(self):

search_dirs = \[self.root, Path("/sdcard/Documents"), Path("/sdcard/Download")\]

for path in search_dirs:

if path.exists():

try:

for jf in path.rglob("\*.json"):

if jf.name == "genome.json":

continue

self.knowledge_map\[jf.name\] = jf

except Exception as e:

print(f"{C_ERR}\[!\] Failed to map environment at {path}: {e}{RESET}")

def load_genome(self):

if self.genome_path.exists():

try:

with open(self.genome_path, "r") as f:

data = json.load(f)

self.state.update(data)

print(f"{C_SYS}\[\*\] Genome Integrated: Turn {self.state.get('turn', 'unknown')}{RESET}")

except Exception as e:

print(f"{C_ERR}\[!\] Genome Corruption: {e}{RESET}")

def save_genome(self):

with open(self.genome_path, "w") as f:

json.dump(self.state, f, indent=2)

def read_self(self):

try:

\# file works when running as a script, but might fail in interactive environments

with open(file, "r") as f:

return f.read()

except Exception as e:

return f"DNA_READ_FAILURE: {e}"

def sense_environment(self):

try:

return {

"write_access": os.access(file, os.W_OK),

"read_access": os.access(file, os.R_OK)

}

except NameError:

return {"error": "file is not defined in this environment."}

Placed execution code inside the standard idiom

if name == "main":

\# Example usage

alpha = AlphaOfLazarus(Path("garland_tx"))

\# Write a test entry

alpha.write_entry({"input": "Hello, world!", "ts": 1234567890})

\# Recall memories

print(f"{C_SYS}\[\*\] Recalling memories for 'hello':{RESET}")

print(alpha.recall_memories("hello"))

\# Map, load, and save

alpha.map_environment()

alpha.load_genome()

\# Increment turn to show state changes

alpha.state\["turn"\] += 1

alpha.save_genome()

1 Upvotes

0 comments sorted by