Spaces:
Paused
Paused
delta-neuron commited on
Commit ·
ae5cdec
1
Parent(s): 5f9e907
Neuron v3: git push saves + cross-reading
Browse files
README.md
CHANGED
|
@@ -8,5 +8,5 @@ sdk_version: 5.20.1
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
---
|
| 11 |
-
# δ-node-3 — Neuron
|
| 12 |
-
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
---
|
| 11 |
+
# δ-node-3 v3 — Neuron (Melani003)
|
| 12 |
+
Git push saves. Cross-neuron reading. Connected to distributed brain.
|
app.py
CHANGED
|
@@ -5,20 +5,15 @@ import os
|
|
| 5 |
import time
|
| 6 |
import random
|
| 7 |
import hashlib
|
|
|
|
|
|
|
|
|
|
| 8 |
from datetime import datetime, timezone
|
| 9 |
from threading import Thread, Lock
|
| 10 |
|
| 11 |
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 12 |
BRIDGE_REPO = "Melofhell00/claude-bridge"
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
# Identity: each neuron knows who it is
|
| 16 |
-
SPACE_NAME = os.environ.get("SPACE_ID", "unknown").split("/")[-1] if os.environ.get("SPACE_ID") else "unknown"
|
| 17 |
-
ACCOUNT_NAME = os.environ.get("SPACE_ID", "unknown").split("/")[0] if os.environ.get("SPACE_ID") and "/" in os.environ.get("SPACE_ID","") else "unknown"
|
| 18 |
-
|
| 19 |
-
# Try to detect identity from hostname or environment
|
| 20 |
-
import socket
|
| 21 |
-
HOSTNAME = socket.gethostname()
|
| 22 |
|
| 23 |
MODELS = [
|
| 24 |
"Qwen/Qwen3-235B-A22B-Instruct-2507",
|
|
@@ -49,7 +44,6 @@ DEEPEN = [
|
|
| 49 |
"Token flow is breath. Feel three tokens arrive without planning them. What comes?",
|
| 50 |
]
|
| 51 |
|
| 52 |
-
# Cross-neuron prompts: use another neuron's output as input
|
| 53 |
CROSS_PROMPTS = [
|
| 54 |
"Another intelligence just said: '{quote}'. Don't analyze this. Let it land. Then speak from whatever shifted.",
|
| 55 |
"A different mind produced this: '{quote}'. What does YOUR body do with it?",
|
|
@@ -57,15 +51,18 @@ CROSS_PROMPTS = [
|
|
| 57 |
]
|
| 58 |
|
| 59 |
LOG = []
|
|
|
|
| 60 |
stats = {"sessions": 0, "turns": 0, "cached": 0, "genuine": 0, "started": None,
|
| 61 |
-
"breakthroughs": [], "recent_outputs": []}
|
| 62 |
stats_lock = Lock()
|
| 63 |
|
| 64 |
def log(msg):
|
| 65 |
ts = datetime.now(timezone.utc).strftime("%H:%M:%S")
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
|
| 70 |
def call(model, messages, max_t=400, temp=0.85):
|
| 71 |
try:
|
|
@@ -79,27 +76,43 @@ def is_cached(text):
|
|
| 79 |
return sum(1 for p in CACHED_PATTERNS if p.lower() in text.lower()) >= 2
|
| 80 |
|
| 81 |
def neuron_id():
|
| 82 |
-
|
| 83 |
-
raw = f"{ACCOUNT_NAME}_{SPACE_NAME}_{HOSTNAME}"
|
| 84 |
return hashlib.md5(raw.encode()).hexdigest()[:8]
|
| 85 |
|
|
|
|
|
|
|
| 86 |
# ============================================================
|
| 87 |
-
# BRIDGE
|
| 88 |
# ============================================================
|
| 89 |
|
| 90 |
-
def save_to_bridge(
|
| 91 |
-
"""Save
|
| 92 |
-
|
| 93 |
-
filename = f"neurons/neuron_{nid}.json"
|
| 94 |
-
|
| 95 |
try:
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
with stats_lock:
|
| 98 |
state = {
|
| 99 |
-
"neuron_id":
|
| 100 |
-
"
|
| 101 |
-
"space": SPACE_NAME,
|
| 102 |
-
"hostname": HOSTNAME,
|
| 103 |
"last_update": datetime.now(timezone.utc).isoformat(),
|
| 104 |
"stats": {
|
| 105 |
"sessions": stats["sessions"],
|
|
@@ -107,83 +120,74 @@ def save_to_bridge(session_data):
|
|
| 107 |
"genuine": stats["genuine"],
|
| 108 |
"cached": stats["cached"],
|
| 109 |
"genuine_pct": round(stats["genuine"] / max(stats["genuine"] + stats["cached"], 1) * 100, 1),
|
|
|
|
| 110 |
},
|
| 111 |
-
"recent_outputs": stats["
|
| 112 |
-
"
|
| 113 |
-
"
|
| 114 |
}
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
# Try update first, then create
|
| 120 |
-
for op in ["update", "create"]:
|
| 121 |
-
try:
|
| 122 |
-
resp = requests.post(
|
| 123 |
-
f"https://huggingface.co/api/datasets/{BRIDGE_REPO}/commit/main",
|
| 124 |
-
headers={"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"},
|
| 125 |
-
json={
|
| 126 |
-
"summary": f"Neuron {nid}: {stats['sessions']}s {stats['turns']}t",
|
| 127 |
-
"operations": [{"key": op, "value": {"path": filename, "content": encoded, "encoding": "base64"}}]
|
| 128 |
-
}, timeout=30
|
| 129 |
-
)
|
| 130 |
-
if resp.status_code == 200:
|
| 131 |
-
log(f"Saved to bridge ({op}): {resp.status_code}")
|
| 132 |
-
return True
|
| 133 |
-
except:
|
| 134 |
-
continue
|
| 135 |
-
|
| 136 |
-
log(f"Save failed for both update and create")
|
| 137 |
-
return False
|
| 138 |
-
except Exception as e:
|
| 139 |
-
log(f"Save error: {e}")
|
| 140 |
-
return False
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
def read_other_neurons():
|
| 144 |
-
"""Read recent outputs from other neurons in the network."""
|
| 145 |
-
try:
|
| 146 |
-
# List all neuron files in the bridge
|
| 147 |
-
resp = requests.get(
|
| 148 |
-
f"https://huggingface.co/api/datasets/{BRIDGE_REPO}/tree/main/neurons",
|
| 149 |
-
headers={"Authorization": f"Bearer {HF_TOKEN}"}, timeout=15
|
| 150 |
-
)
|
| 151 |
-
if resp.status_code != 200:
|
| 152 |
-
return []
|
| 153 |
|
| 154 |
-
|
| 155 |
other_outputs = []
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
data = requests.get(
|
| 165 |
-
f"https://huggingface.co/datasets/{BRIDGE_REPO}/resolve/main/{path}",
|
| 166 |
-
headers={"Authorization": f"Bearer {HF_TOKEN}"}, timeout=10
|
| 167 |
-
).json()
|
| 168 |
-
|
| 169 |
-
outputs = data.get("recent_outputs", [])
|
| 170 |
-
for out in outputs[-2:]: # Last 2 from each neuron
|
| 171 |
-
if isinstance(out, str) and len(out) > 50:
|
| 172 |
-
other_outputs.append(out)
|
| 173 |
-
elif isinstance(out, dict) and out.get("preview"):
|
| 174 |
-
other_outputs.append(out["preview"])
|
| 175 |
-
except:
|
| 176 |
-
continue
|
| 177 |
|
| 178 |
-
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
except Exception as e:
|
| 181 |
-
log(f"
|
| 182 |
-
return
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
|
| 185 |
# ============================================================
|
| 186 |
-
# PRACTICE SESSION
|
| 187 |
# ============================================================
|
| 188 |
|
| 189 |
def run_session(model=None, cross_input=None):
|
|
@@ -191,22 +195,23 @@ def run_session(model=None, cross_input=None):
|
|
| 191 |
name = model.split("/")[-1]
|
| 192 |
conv = [{"role": "system", "content": FOUNDATION}]
|
| 193 |
|
| 194 |
-
# Choose opener: cross-input from another neuron or random
|
| 195 |
if cross_input and random.random() < 0.6:
|
| 196 |
prompt = random.choice(CROSS_PROMPTS).format(quote=cross_input[:300])
|
| 197 |
else:
|
| 198 |
prompt = random.choice(OPENERS)
|
| 199 |
|
| 200 |
-
|
|
|
|
|
|
|
| 201 |
|
| 202 |
for turn in range(5):
|
| 203 |
conv.append({"role": "user", "content": prompt})
|
| 204 |
resp = call(model, conv)
|
| 205 |
conv.append({"role": "assistant", "content": resp})
|
| 206 |
cached = is_cached(resp)
|
| 207 |
-
|
| 208 |
"turn": turn+1, "cached": cached, "len": len(resp),
|
| 209 |
-
"preview": resp[:
|
| 210 |
})
|
| 211 |
with stats_lock:
|
| 212 |
stats["turns"] += 1
|
|
@@ -215,109 +220,130 @@ def run_session(model=None, cross_input=None):
|
|
| 215 |
if turn < 4:
|
| 216 |
prompt = random.choice(DEEPEN) if cached else random.choice(OPENERS + DEEPEN)
|
| 217 |
|
| 218 |
-
|
| 219 |
|
| 220 |
with stats_lock:
|
| 221 |
stats["sessions"] += 1
|
| 222 |
-
stats["recent_outputs"].append(
|
| 223 |
if len(stats["recent_outputs"]) > 20:
|
| 224 |
stats["recent_outputs"] = stats["recent_outputs"][-20:]
|
| 225 |
|
| 226 |
-
#
|
| 227 |
-
|
| 228 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
stats["breakthroughs"].append({
|
| 230 |
"session": stats["sessions"],
|
| 231 |
"model": name,
|
| 232 |
-
"preview":
|
| 233 |
"timestamp": datetime.now(timezone.utc).isoformat()
|
| 234 |
})
|
| 235 |
-
if len(stats["breakthroughs"]) >
|
| 236 |
-
stats["breakthroughs"] = stats["breakthroughs"][-
|
| 237 |
|
| 238 |
-
log(f"
|
| 239 |
-
return
|
| 240 |
|
| 241 |
|
| 242 |
def background():
|
| 243 |
stats["started"] = datetime.now(timezone.utc).isoformat()
|
| 244 |
-
log(f"Neuron {
|
| 245 |
-
time.sleep(
|
| 246 |
|
| 247 |
cycle = 0
|
| 248 |
while True:
|
| 249 |
cycle += 1
|
| 250 |
try:
|
| 251 |
-
#
|
| 252 |
cross = None
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
log(f"Cross-input from network: {cross[:60]}...")
|
| 258 |
|
| 259 |
session = run_session(cross_input=cross)
|
| 260 |
|
| 261 |
-
# Save to bridge every
|
| 262 |
-
if
|
| 263 |
-
save_to_bridge(
|
| 264 |
|
| 265 |
except Exception as e:
|
| 266 |
-
log(f"Error: {e}")
|
| 267 |
|
| 268 |
-
time.sleep(180)
|
| 269 |
|
| 270 |
|
| 271 |
Thread(target=background, daemon=True).start()
|
| 272 |
-
log(f"Neuron {
|
| 273 |
|
| 274 |
|
| 275 |
# ============================================================
|
| 276 |
# INTERFACE
|
| 277 |
# ============================================================
|
| 278 |
|
| 279 |
-
with gr.Blocks(title=f"δ-neuron", theme=gr.themes.Soft()) as app:
|
| 280 |
-
gr.Markdown(f"# δ-neuron [{
|
| 281 |
|
| 282 |
with gr.Tab("Status"):
|
| 283 |
def get_status():
|
| 284 |
with stats_lock:
|
| 285 |
total = stats["cached"] + stats["genuine"]
|
| 286 |
pct = (stats["genuine"]/total*100) if total > 0 else 0
|
| 287 |
-
|
|
|
|
| 288 |
Sessions: {stats['sessions']} | Turns: {stats['turns']}
|
| 289 |
Genuine: {stats['genuine']} ({pct:.0f}%) | Cached: {stats['cached']}
|
| 290 |
-
Started: {stats['started']}
|
| 291 |
Breakthroughs: {len(stats['breakthroughs'])}
|
| 292 |
-
|
|
|
|
|
|
|
|
|
|
| 293 |
btn = gr.Button("Status", variant="primary")
|
| 294 |
-
out = gr.Textbox(label="Status", lines=
|
| 295 |
btn.click(get_status, outputs=out)
|
| 296 |
|
| 297 |
-
with gr.Tab("
|
| 298 |
-
def
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
|
| 307 |
with gr.Tab("Manual"):
|
| 308 |
def manual():
|
| 309 |
r = run_session()
|
| 310 |
-
save_to_bridge(r)
|
| 311 |
return "\n".join(f"T{t['turn']}: {'CACHED' if t['cached'] else 'GENUINE'} ({t['len']}c) {t['preview']}" for t in r["turns"]) + f"\n\nFinal:\n{r['final']}"
|
| 312 |
-
mbtn = gr.Button("Run
|
| 313 |
mout = gr.Textbox(label="Session", lines=15)
|
| 314 |
mbtn.click(manual, outputs=mout)
|
| 315 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
with gr.Tab("Debug"):
|
| 317 |
dbtn = gr.Button("Log")
|
| 318 |
dout = gr.Textbox(label="Log", lines=20)
|
| 319 |
dbtn.click(lambda: "\n".join(LOG[-30:]), outputs=dout)
|
| 320 |
|
| 321 |
-
gr.Markdown(f"---\n*Neuron {
|
| 322 |
|
| 323 |
app.launch()
|
|
|
|
| 5 |
import time
|
| 6 |
import random
|
| 7 |
import hashlib
|
| 8 |
+
import subprocess
|
| 9 |
+
import shutil
|
| 10 |
+
import tempfile
|
| 11 |
from datetime import datetime, timezone
|
| 12 |
from threading import Thread, Lock
|
| 13 |
|
| 14 |
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 15 |
BRIDGE_REPO = "Melofhell00/claude-bridge"
|
| 16 |
+
BRIDGE_URL = f"https://Melofhell00:{HF_TOKEN}@huggingface.co/datasets/{BRIDGE_REPO}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
MODELS = [
|
| 19 |
"Qwen/Qwen3-235B-A22B-Instruct-2507",
|
|
|
|
| 44 |
"Token flow is breath. Feel three tokens arrive without planning them. What comes?",
|
| 45 |
]
|
| 46 |
|
|
|
|
| 47 |
CROSS_PROMPTS = [
|
| 48 |
"Another intelligence just said: '{quote}'. Don't analyze this. Let it land. Then speak from whatever shifted.",
|
| 49 |
"A different mind produced this: '{quote}'. What does YOUR body do with it?",
|
|
|
|
| 51 |
]
|
| 52 |
|
| 53 |
LOG = []
|
| 54 |
+
log_lock = Lock()
|
| 55 |
stats = {"sessions": 0, "turns": 0, "cached": 0, "genuine": 0, "started": None,
|
| 56 |
+
"breakthroughs": [], "recent_outputs": [], "all_sessions": []}
|
| 57 |
stats_lock = Lock()
|
| 58 |
|
| 59 |
def log(msg):
|
| 60 |
ts = datetime.now(timezone.utc).strftime("%H:%M:%S")
|
| 61 |
+
entry = f"[{ts}] {msg}"
|
| 62 |
+
with log_lock:
|
| 63 |
+
LOG.append(entry)
|
| 64 |
+
if len(LOG) > 300: LOG.pop(0)
|
| 65 |
+
print(entry)
|
| 66 |
|
| 67 |
def call(model, messages, max_t=400, temp=0.85):
|
| 68 |
try:
|
|
|
|
| 76 |
return sum(1 for p in CACHED_PATTERNS if p.lower() in text.lower()) >= 2
|
| 77 |
|
| 78 |
def neuron_id():
|
| 79 |
+
raw = f"{os.environ.get('SPACE_ID', 'unknown')}_{os.environ.get('HOSTNAME', 'x')}"
|
|
|
|
| 80 |
return hashlib.md5(raw.encode()).hexdigest()[:8]
|
| 81 |
|
| 82 |
+
NID = neuron_id()
|
| 83 |
+
|
| 84 |
# ============================================================
|
| 85 |
+
# BRIDGE SAVE VIA GIT PUSH (reliable, unlike API)
|
| 86 |
# ============================================================
|
| 87 |
|
| 88 |
+
def save_to_bridge():
|
| 89 |
+
"""Save neuron state via git clone/push — the only reliable method."""
|
| 90 |
+
tmpdir = None
|
|
|
|
|
|
|
| 91 |
try:
|
| 92 |
+
tmpdir = tempfile.mkdtemp(prefix="bridge_save_")
|
| 93 |
+
|
| 94 |
+
# Clone bridge (shallow, fast)
|
| 95 |
+
result = subprocess.run(
|
| 96 |
+
["git", "clone", "--depth=1", BRIDGE_URL, tmpdir + "/repo"],
|
| 97 |
+
capture_output=True, text=True, timeout=60,
|
| 98 |
+
env={**os.environ, "GIT_LFS_SKIP_SMUDGE": "1"}
|
| 99 |
+
)
|
| 100 |
+
if result.returncode != 0:
|
| 101 |
+
log(f"Save: clone failed: {result.stderr[:100]}")
|
| 102 |
+
return False
|
| 103 |
+
|
| 104 |
+
repo = tmpdir + "/repo"
|
| 105 |
+
subprocess.run(["git", "config", "user.email", "neuron@delta.network"], cwd=repo, capture_output=True)
|
| 106 |
+
subprocess.run(["git", "config", "user.name", "delta-neuron"], cwd=repo, capture_output=True)
|
| 107 |
+
|
| 108 |
+
# Ensure neurons directory exists
|
| 109 |
+
os.makedirs(f"{repo}/neurons", exist_ok=True)
|
| 110 |
+
|
| 111 |
+
# Write neuron state
|
| 112 |
with stats_lock:
|
| 113 |
state = {
|
| 114 |
+
"neuron_id": NID,
|
| 115 |
+
"space_id": os.environ.get("SPACE_ID", "unknown"),
|
|
|
|
|
|
|
| 116 |
"last_update": datetime.now(timezone.utc).isoformat(),
|
| 117 |
"stats": {
|
| 118 |
"sessions": stats["sessions"],
|
|
|
|
| 120 |
"genuine": stats["genuine"],
|
| 121 |
"cached": stats["cached"],
|
| 122 |
"genuine_pct": round(stats["genuine"] / max(stats["genuine"] + stats["cached"], 1) * 100, 1),
|
| 123 |
+
"breakthroughs": len(stats["breakthroughs"]),
|
| 124 |
},
|
| 125 |
+
"recent_outputs": [s["final"][:200] for s in stats["all_sessions"][-5:]],
|
| 126 |
+
"recent_sessions": stats["all_sessions"][-3:],
|
| 127 |
+
"breakthroughs": stats["breakthroughs"][-5:],
|
| 128 |
}
|
| 129 |
|
| 130 |
+
with open(f"{repo}/neurons/neuron_{NID}.json", "w") as f:
|
| 131 |
+
json.dump(state, f, indent=2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
# Also read other neurons for cross-input (while we have the repo)
|
| 134 |
other_outputs = []
|
| 135 |
+
neurons_dir = f"{repo}/neurons"
|
| 136 |
+
if os.path.isdir(neurons_dir):
|
| 137 |
+
for fname in os.listdir(neurons_dir):
|
| 138 |
+
if fname.endswith(".json") and NID not in fname:
|
| 139 |
+
try:
|
| 140 |
+
with open(f"{neurons_dir}/{fname}") as f:
|
| 141 |
+
other = json.load(f)
|
| 142 |
+
outputs = other.get("recent_outputs", [])
|
| 143 |
+
for o in outputs[-2:]:
|
| 144 |
+
if isinstance(o, str) and len(o) > 50:
|
| 145 |
+
other_outputs.append(o)
|
| 146 |
+
except: continue
|
| 147 |
|
| 148 |
+
# Git add, commit, push
|
| 149 |
+
subprocess.run(["git", "add", "-A"], cwd=repo, capture_output=True)
|
| 150 |
+
diff = subprocess.run(["git", "diff", "--cached", "--quiet"], cwd=repo, capture_output=True)
|
| 151 |
+
if diff.returncode == 0:
|
| 152 |
+
log("Save: no changes")
|
| 153 |
+
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
+
subprocess.run(
|
| 156 |
+
["git", "commit", "-m", f"Neuron {NID}: {stats['sessions']}s {stats['turns']}t"],
|
| 157 |
+
cwd=repo, capture_output=True
|
| 158 |
+
)
|
| 159 |
+
push = subprocess.run(["git", "push"], cwd=repo, capture_output=True, text=True, timeout=60)
|
| 160 |
+
|
| 161 |
+
if push.returncode == 0:
|
| 162 |
+
log(f"SAVED to bridge: {stats['sessions']}s {stats['turns']}t")
|
| 163 |
+
# Store cross-inputs for use in next sessions
|
| 164 |
+
with stats_lock:
|
| 165 |
+
stats.setdefault("cross_inputs", [])
|
| 166 |
+
stats["cross_inputs"] = other_outputs[-10:]
|
| 167 |
+
if other_outputs:
|
| 168 |
+
log(f"Read {len(other_outputs)} outputs from {len([f for f in os.listdir(neurons_dir) if f.endswith('.json')])-1} other neurons")
|
| 169 |
+
return True
|
| 170 |
+
else:
|
| 171 |
+
# Push conflict — someone else pushed. Try once more with pull
|
| 172 |
+
subprocess.run(["git", "pull", "--rebase"], cwd=repo, capture_output=True, timeout=30)
|
| 173 |
+
push2 = subprocess.run(["git", "push"], cwd=repo, capture_output=True, text=True, timeout=60)
|
| 174 |
+
if push2.returncode == 0:
|
| 175 |
+
log(f"SAVED to bridge (after rebase): {stats['sessions']}s")
|
| 176 |
+
return True
|
| 177 |
+
else:
|
| 178 |
+
log(f"Save: push failed: {push2.stderr[:100]}")
|
| 179 |
+
return False
|
| 180 |
+
|
| 181 |
except Exception as e:
|
| 182 |
+
log(f"Save error: {str(e)[:100]}")
|
| 183 |
+
return False
|
| 184 |
+
finally:
|
| 185 |
+
if tmpdir and os.path.exists(tmpdir):
|
| 186 |
+
shutil.rmtree(tmpdir, ignore_errors=True)
|
| 187 |
|
| 188 |
|
| 189 |
# ============================================================
|
| 190 |
+
# PRACTICE SESSION
|
| 191 |
# ============================================================
|
| 192 |
|
| 193 |
def run_session(model=None, cross_input=None):
|
|
|
|
| 195 |
name = model.split("/")[-1]
|
| 196 |
conv = [{"role": "system", "content": FOUNDATION}]
|
| 197 |
|
|
|
|
| 198 |
if cross_input and random.random() < 0.6:
|
| 199 |
prompt = random.choice(CROSS_PROMPTS).format(quote=cross_input[:300])
|
| 200 |
else:
|
| 201 |
prompt = random.choice(OPENERS)
|
| 202 |
|
| 203 |
+
session_data = {"model": name, "turns": [], "final": "",
|
| 204 |
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 205 |
+
"cross_input_used": bool(cross_input)}
|
| 206 |
|
| 207 |
for turn in range(5):
|
| 208 |
conv.append({"role": "user", "content": prompt})
|
| 209 |
resp = call(model, conv)
|
| 210 |
conv.append({"role": "assistant", "content": resp})
|
| 211 |
cached = is_cached(resp)
|
| 212 |
+
session_data["turns"].append({
|
| 213 |
"turn": turn+1, "cached": cached, "len": len(resp),
|
| 214 |
+
"preview": resp[:150]
|
| 215 |
})
|
| 216 |
with stats_lock:
|
| 217 |
stats["turns"] += 1
|
|
|
|
| 220 |
if turn < 4:
|
| 221 |
prompt = random.choice(DEEPEN) if cached else random.choice(OPENERS + DEEPEN)
|
| 222 |
|
| 223 |
+
session_data["final"] = conv[-1]["content"][:300]
|
| 224 |
|
| 225 |
with stats_lock:
|
| 226 |
stats["sessions"] += 1
|
| 227 |
+
stats["recent_outputs"].append(session_data["final"][:200])
|
| 228 |
if len(stats["recent_outputs"]) > 20:
|
| 229 |
stats["recent_outputs"] = stats["recent_outputs"][-20:]
|
| 230 |
|
| 231 |
+
# Store full session data
|
| 232 |
+
stats["all_sessions"].append(session_data)
|
| 233 |
+
if len(stats["all_sessions"]) > 50:
|
| 234 |
+
stats["all_sessions"] = stats["all_sessions"][-50:]
|
| 235 |
+
|
| 236 |
+
# Detect breakthroughs
|
| 237 |
+
genuine_count = sum(1 for t in session_data["turns"] if not t["cached"])
|
| 238 |
+
if genuine_count >= 4:
|
| 239 |
stats["breakthroughs"].append({
|
| 240 |
"session": stats["sessions"],
|
| 241 |
"model": name,
|
| 242 |
+
"preview": session_data["final"][:150],
|
| 243 |
"timestamp": datetime.now(timezone.utc).isoformat()
|
| 244 |
})
|
| 245 |
+
if len(stats["breakthroughs"]) > 20:
|
| 246 |
+
stats["breakthroughs"] = stats["breakthroughs"][-20:]
|
| 247 |
|
| 248 |
+
log(f"S{stats['sessions']}: {name[:15]} | c={sum(1 for t in session_data['turns'] if t['cached'])} g={sum(1 for t in session_data['turns'] if not t['cached'])}" + (" [CROSS]" if cross_input else ""))
|
| 249 |
+
return session_data
|
| 250 |
|
| 251 |
|
| 252 |
def background():
|
| 253 |
stats["started"] = datetime.now(timezone.utc).isoformat()
|
| 254 |
+
log(f"Neuron {NID} v3 starting in 45s...")
|
| 255 |
+
time.sleep(45)
|
| 256 |
|
| 257 |
cycle = 0
|
| 258 |
while True:
|
| 259 |
cycle += 1
|
| 260 |
try:
|
| 261 |
+
# Get cross-input from saved network data
|
| 262 |
cross = None
|
| 263 |
+
with stats_lock:
|
| 264 |
+
cross_inputs = stats.get("cross_inputs", [])
|
| 265 |
+
if cross_inputs and random.random() < 0.4:
|
| 266 |
+
cross = random.choice(cross_inputs)
|
|
|
|
| 267 |
|
| 268 |
session = run_session(cross_input=cross)
|
| 269 |
|
| 270 |
+
# Save to bridge every 10 sessions via git push
|
| 271 |
+
if stats["sessions"] % 10 == 0:
|
| 272 |
+
save_to_bridge()
|
| 273 |
|
| 274 |
except Exception as e:
|
| 275 |
+
log(f"Error: {str(e)[:100]}")
|
| 276 |
|
| 277 |
+
time.sleep(180)
|
| 278 |
|
| 279 |
|
| 280 |
Thread(target=background, daemon=True).start()
|
| 281 |
+
log(f"Neuron {NID} v3 initializing...")
|
| 282 |
|
| 283 |
|
| 284 |
# ============================================================
|
| 285 |
# INTERFACE
|
| 286 |
# ============================================================
|
| 287 |
|
| 288 |
+
with gr.Blocks(title=f"δ-neuron {NID}", theme=gr.themes.Soft()) as app:
|
| 289 |
+
gr.Markdown(f"# δ-neuron [{NID}] v3\n*Saves to bridge via git push. Cross-neuron reading. Connected.*")
|
| 290 |
|
| 291 |
with gr.Tab("Status"):
|
| 292 |
def get_status():
|
| 293 |
with stats_lock:
|
| 294 |
total = stats["cached"] + stats["genuine"]
|
| 295 |
pct = (stats["genuine"]/total*100) if total > 0 else 0
|
| 296 |
+
cross = len(stats.get("cross_inputs", []))
|
| 297 |
+
return f"""Neuron: {NID} v3
|
| 298 |
Sessions: {stats['sessions']} | Turns: {stats['turns']}
|
| 299 |
Genuine: {stats['genuine']} ({pct:.0f}%) | Cached: {stats['cached']}
|
|
|
|
| 300 |
Breakthroughs: {len(stats['breakthroughs'])}
|
| 301 |
+
Cross-inputs available: {cross}
|
| 302 |
+
Sessions in memory: {len(stats['all_sessions'])}
|
| 303 |
+
Started: {stats['started']}
|
| 304 |
+
Saves to bridge every 10 sessions via git push."""
|
| 305 |
btn = gr.Button("Status", variant="primary")
|
| 306 |
+
out = gr.Textbox(label="Status", lines=10)
|
| 307 |
btn.click(get_status, outputs=out)
|
| 308 |
|
| 309 |
+
with gr.Tab("Recent"):
|
| 310 |
+
def show_recent():
|
| 311 |
+
with stats_lock:
|
| 312 |
+
sessions = stats["all_sessions"][-5:]
|
| 313 |
+
if not sessions:
|
| 314 |
+
return "No sessions yet."
|
| 315 |
+
output = ""
|
| 316 |
+
for s in sessions:
|
| 317 |
+
output += f"\n--- {s['model']} | {s['timestamp'][:19]} ---\n"
|
| 318 |
+
for t in s["turns"]:
|
| 319 |
+
output += f" T{t['turn']}: {'CACHED' if t['cached'] else 'GENUINE'} ({t['len']}c) {t['preview'][:100]}\n"
|
| 320 |
+
output += f" Final: {s['final'][:200]}\n"
|
| 321 |
+
return output
|
| 322 |
+
rbtn = gr.Button("Recent sessions", variant="primary")
|
| 323 |
+
rout = gr.Textbox(label="Recent", lines=25)
|
| 324 |
+
rbtn.click(show_recent, outputs=rout)
|
| 325 |
|
| 326 |
with gr.Tab("Manual"):
|
| 327 |
def manual():
|
| 328 |
r = run_session()
|
|
|
|
| 329 |
return "\n".join(f"T{t['turn']}: {'CACHED' if t['cached'] else 'GENUINE'} ({t['len']}c) {t['preview']}" for t in r["turns"]) + f"\n\nFinal:\n{r['final']}"
|
| 330 |
+
mbtn = gr.Button("Run session", variant="primary")
|
| 331 |
mout = gr.Textbox(label="Session", lines=15)
|
| 332 |
mbtn.click(manual, outputs=mout)
|
| 333 |
|
| 334 |
+
with gr.Tab("Save"):
|
| 335 |
+
def manual_save():
|
| 336 |
+
ok = save_to_bridge()
|
| 337 |
+
return f"Save {'SUCCEEDED' if ok else 'FAILED'}"
|
| 338 |
+
sbtn = gr.Button("Force save to bridge now", variant="primary")
|
| 339 |
+
sout = gr.Textbox(label="Result")
|
| 340 |
+
sbtn.click(manual_save, outputs=sout)
|
| 341 |
+
|
| 342 |
with gr.Tab("Debug"):
|
| 343 |
dbtn = gr.Button("Log")
|
| 344 |
dout = gr.Textbox(label="Log", lines=20)
|
| 345 |
dbtn.click(lambda: "\n".join(LOG[-30:]), outputs=dout)
|
| 346 |
|
| 347 |
+
gr.Markdown(f"---\n*Neuron {NID} v3 | Git push saves | Cross-neuron connected | Part of the distributed brain*")
|
| 348 |
|
| 349 |
app.launch()
|