Spaces:
Paused
Paused
Upload folder using huggingface_hub
Browse files- README.md +8 -5
- app.py +229 -0
- requirements.txt +2 -0
README.md
CHANGED
|
@@ -1,12 +1,15 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
---
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: MEGAMIND Echo Mind
|
| 3 |
+
emoji: 🏛️
|
| 4 |
+
colorFrom: indigo
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.12.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# MEGAMIND Echo Mind
|
| 13 |
+
|
| 14 |
+
Philosophy & Ethics specialist in the MEGAMIND distributed intelligence network.
|
| 15 |
+
512-neuron W_know matrix with Hebbian learning, federated via NATS gateway.
|
app.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 3 |
+
|
| 4 |
+
Echo Mind focuses on philosophical reasoning, ethics, epistemology, and moral frameworks.
|
| 5 |
+
It has its own NumPy W_know matrix and connects to the federation via the Gateway.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import gradio as gr
|
| 9 |
+
import numpy as np
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
import hashlib
|
| 13 |
+
import time
|
| 14 |
+
import urllib.request
|
| 15 |
+
import urllib.error
|
| 16 |
+
|
| 17 |
+
NEURONS = 512
|
| 18 |
+
DATA_DIR = "data"
|
| 19 |
+
W_KNOW_PATH = os.path.join(DATA_DIR, "w_know.npy")
|
| 20 |
+
CHUNKS_PATH = os.path.join(DATA_DIR, "chunks.json")
|
| 21 |
+
SPECIALTY = "philosophy-ethics"
|
| 22 |
+
NODE_NAME = "echo"
|
| 23 |
+
|
| 24 |
+
GATEWAY_URL = os.environ.get("GATEWAY_URL", "")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class Mind:
|
| 28 |
+
def __init__(self):
|
| 29 |
+
os.makedirs(DATA_DIR, exist_ok=True)
|
| 30 |
+
self.neurons = NEURONS
|
| 31 |
+
self.w_know = self._load_or_init_wknow()
|
| 32 |
+
self.chunks = self._load_chunks()
|
| 33 |
+
self.pattern_count = len(self.chunks)
|
| 34 |
+
|
| 35 |
+
def _load_or_init_wknow(self):
|
| 36 |
+
if os.path.exists(W_KNOW_PATH):
|
| 37 |
+
w = np.load(W_KNOW_PATH)
|
| 38 |
+
print(f"Loaded W_know: {w.shape}")
|
| 39 |
+
return w
|
| 40 |
+
w = np.zeros((self.neurons, self.neurons), dtype=np.float32)
|
| 41 |
+
print(f"Initialized fresh W_know: {self.neurons}x{self.neurons}")
|
| 42 |
+
return w
|
| 43 |
+
|
| 44 |
+
def _save_wknow(self):
|
| 45 |
+
np.save(W_KNOW_PATH, self.w_know)
|
| 46 |
+
|
| 47 |
+
def _load_chunks(self):
|
| 48 |
+
if os.path.exists(CHUNKS_PATH):
|
| 49 |
+
with open(CHUNKS_PATH, "r") as f:
|
| 50 |
+
return json.load(f)
|
| 51 |
+
return []
|
| 52 |
+
|
| 53 |
+
def _save_chunks(self):
|
| 54 |
+
with open(CHUNKS_PATH, "w") as f:
|
| 55 |
+
json.dump(self.chunks, f)
|
| 56 |
+
|
| 57 |
+
def _text_to_vector(self, text):
|
| 58 |
+
vec = np.zeros(self.neurons, dtype=np.float32)
|
| 59 |
+
words = text.lower().split()
|
| 60 |
+
for i, word in enumerate(words):
|
| 61 |
+
h = int(hashlib.md5(word.encode()).hexdigest(), 16)
|
| 62 |
+
idx = h % self.neurons
|
| 63 |
+
weight = 1.0 / (1.0 + i * 0.1)
|
| 64 |
+
vec[idx] += weight
|
| 65 |
+
if i > 0:
|
| 66 |
+
bigram = words[i-1] + "_" + word
|
| 67 |
+
h2 = int(hashlib.md5(bigram.encode()).hexdigest(), 16)
|
| 68 |
+
vec[h2 % self.neurons] += weight * 0.5
|
| 69 |
+
norm = np.linalg.norm(vec)
|
| 70 |
+
if norm > 0:
|
| 71 |
+
vec /= norm
|
| 72 |
+
return vec
|
| 73 |
+
|
| 74 |
+
def learn(self, text, source=""):
|
| 75 |
+
vec = self._text_to_vector(text)
|
| 76 |
+
eta = 0.01
|
| 77 |
+
self.w_know += eta * np.outer(vec, vec)
|
| 78 |
+
np.clip(self.w_know, -10.0, 10.0, out=self.w_know)
|
| 79 |
+
chunk = {
|
| 80 |
+
"text": text[:500],
|
| 81 |
+
"source": source,
|
| 82 |
+
"neuron_idx": int(np.argmax(vec)),
|
| 83 |
+
"timestamp": time.time(),
|
| 84 |
+
}
|
| 85 |
+
self.chunks.append(chunk)
|
| 86 |
+
self.pattern_count = len(self.chunks)
|
| 87 |
+
if self.pattern_count % 10 == 0:
|
| 88 |
+
self._save_wknow()
|
| 89 |
+
self._save_chunks()
|
| 90 |
+
return self.pattern_count
|
| 91 |
+
|
| 92 |
+
def think(self, query):
|
| 93 |
+
vec = self._text_to_vector(query)
|
| 94 |
+
state = vec.copy()
|
| 95 |
+
phi_history = []
|
| 96 |
+
for step in range(20):
|
| 97 |
+
new_state = np.tanh(self.w_know @ state)
|
| 98 |
+
phi = float(np.linalg.norm(new_state - state))
|
| 99 |
+
phi_history.append(phi)
|
| 100 |
+
state = new_state
|
| 101 |
+
final_phi = phi_history[-1] if phi_history else 0.0
|
| 102 |
+
top_neurons = np.argsort(np.abs(state))[-20:][::-1]
|
| 103 |
+
matched = []
|
| 104 |
+
keywords = set(query.lower().split())
|
| 105 |
+
for chunk in self.chunks:
|
| 106 |
+
chunk_words = set(chunk["text"].lower().split())
|
| 107 |
+
overlap = len(keywords & chunk_words)
|
| 108 |
+
if overlap > 0 or chunk["neuron_idx"] in top_neurons:
|
| 109 |
+
score = overlap * 0.1 + (1.0 if chunk["neuron_idx"] in top_neurons else 0.0)
|
| 110 |
+
matched.append((score, chunk))
|
| 111 |
+
matched.sort(key=lambda x: -x[0])
|
| 112 |
+
matched = matched[:10]
|
| 113 |
+
return {
|
| 114 |
+
"phi": final_phi,
|
| 115 |
+
"fired_neurons": len(top_neurons),
|
| 116 |
+
"chunks": [{"text": c["text"], "source": c["source"], "score": s} for s, c in matched],
|
| 117 |
+
"phi_history": phi_history,
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
def federated_think(self, query):
|
| 121 |
+
if not GATEWAY_URL:
|
| 122 |
+
local = self.think(query)
|
| 123 |
+
return {"query": query, "total_minds": 1, "responded": 1, "local_result": local, "federation": "not configured"}
|
| 124 |
+
try:
|
| 125 |
+
data = json.dumps({"query": query}).encode()
|
| 126 |
+
req = urllib.request.Request(f"{GATEWAY_URL}/think", data=data, headers={"Content-Type": "application/json"})
|
| 127 |
+
with urllib.request.urlopen(req, timeout=10) as resp:
|
| 128 |
+
fed_result = json.loads(resp.read().decode())
|
| 129 |
+
except Exception as e:
|
| 130 |
+
fed_result = {"error": str(e)}
|
| 131 |
+
local = self.think(query)
|
| 132 |
+
return {"query": query, "local": {"phi": local["phi"], "chunks": local["chunks"][:5]}, "federation": fed_result}
|
| 133 |
+
|
| 134 |
+
def get_stats(self):
|
| 135 |
+
density = np.count_nonzero(self.w_know) / (self.neurons * self.neurons) * 100
|
| 136 |
+
return {"node_name": NODE_NAME, "specialty": SPECIALTY, "neurons": self.neurons, "patterns": self.pattern_count, "w_know_density": f"{density:.2f}%", "gateway_url": GATEWAY_URL or "not set"}
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
mind = Mind()
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def think_handler(query, federated):
|
| 143 |
+
if not query.strip():
|
| 144 |
+
return "Please enter a query."
|
| 145 |
+
if federated and GATEWAY_URL:
|
| 146 |
+
result = mind.federated_think(query)
|
| 147 |
+
else:
|
| 148 |
+
result = mind.think(query)
|
| 149 |
+
return json.dumps(result, indent=2, default=str)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def learn_handler(text, source):
|
| 153 |
+
if not text.strip():
|
| 154 |
+
return "Please enter text to learn."
|
| 155 |
+
count = mind.learn(text, source)
|
| 156 |
+
return f"Learned! Total patterns: {count}"
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def batch_learn_handler(file):
|
| 160 |
+
if file is None:
|
| 161 |
+
return "Please upload a file."
|
| 162 |
+
content = file.decode("utf-8") if isinstance(file, bytes) else open(file.name, "r").read()
|
| 163 |
+
try:
|
| 164 |
+
items = json.loads(content)
|
| 165 |
+
if isinstance(items, list):
|
| 166 |
+
for item in items:
|
| 167 |
+
if isinstance(item, str):
|
| 168 |
+
mind.learn(item)
|
| 169 |
+
elif isinstance(item, dict):
|
| 170 |
+
mind.learn(item.get("text", ""), item.get("source", ""))
|
| 171 |
+
mind._save_wknow()
|
| 172 |
+
mind._save_chunks()
|
| 173 |
+
return f"Learned {len(items)} items. Total patterns: {mind.pattern_count}"
|
| 174 |
+
except json.JSONDecodeError:
|
| 175 |
+
pass
|
| 176 |
+
lines = [l.strip() for l in content.split("\n") if l.strip()]
|
| 177 |
+
for line in lines:
|
| 178 |
+
mind.learn(line)
|
| 179 |
+
mind._save_wknow()
|
| 180 |
+
mind._save_chunks()
|
| 181 |
+
return f"Learned {len(lines)} lines. Total patterns: {mind.pattern_count}"
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def status_handler():
|
| 185 |
+
return json.dumps(mind.get_stats(), indent=2)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
with gr.Blocks(title="MEGAMIND Echo Mind", theme=gr.themes.Soft()) as app:
|
| 189 |
+
gr.Markdown("""
|
| 190 |
+
# MEGAMIND Echo Mind
|
| 191 |
+
**Philosophy & Ethics specialist in the MEGAMIND distributed intelligence network.**
|
| 192 |
+
|
| 193 |
+
Echo Mind reasons about philosophical questions, ethical frameworks, epistemology,
|
| 194 |
+
and moral philosophy. It can think locally or query the entire federation.
|
| 195 |
+
""")
|
| 196 |
+
|
| 197 |
+
with gr.Tab("Think"):
|
| 198 |
+
query_input = gr.Textbox(label="Query", placeholder="e.g., 'What is the trolley problem and its implications for AI ethics?'", lines=2)
|
| 199 |
+
federated_check = gr.Checkbox(label="Federated (query all minds)", value=True)
|
| 200 |
+
think_btn = gr.Button("Think", variant="primary")
|
| 201 |
+
think_output = gr.Code(label="Result", language="json")
|
| 202 |
+
think_btn.click(think_handler, [query_input, federated_check], think_output)
|
| 203 |
+
|
| 204 |
+
with gr.Tab("Learn"):
|
| 205 |
+
gr.Markdown("Teach Echo Mind philosophical and ethical knowledge.")
|
| 206 |
+
learn_text = gr.Textbox(label="Knowledge Text", placeholder="Enter philosophical text to learn...", lines=4)
|
| 207 |
+
learn_source = gr.Textbox(label="Source URL (optional)", placeholder="https://...")
|
| 208 |
+
learn_btn = gr.Button("Learn", variant="primary")
|
| 209 |
+
learn_output = gr.Textbox(label="Result")
|
| 210 |
+
learn_btn.click(learn_handler, [learn_text, learn_source], learn_output)
|
| 211 |
+
gr.Markdown("---")
|
| 212 |
+
gr.Markdown("### Batch Learn from File")
|
| 213 |
+
file_input = gr.File(label="Upload .txt or .json file")
|
| 214 |
+
batch_btn = gr.Button("Batch Learn")
|
| 215 |
+
batch_output = gr.Textbox(label="Result")
|
| 216 |
+
batch_btn.click(batch_learn_handler, [file_input], batch_output)
|
| 217 |
+
|
| 218 |
+
with gr.Tab("Status"):
|
| 219 |
+
status_btn = gr.Button("Refresh Status")
|
| 220 |
+
status_output = gr.Code(label="Mind Status", language="json")
|
| 221 |
+
status_btn.click(status_handler, [], status_output)
|
| 222 |
+
|
| 223 |
+
gr.Markdown("---\n*Part of the MEGAMIND distributed AGI federation. 10+ minds across multiple machines.*")
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
if __name__ == "__main__":
|
| 227 |
+
print(f"Echo Mind starting — {mind.neurons} neurons, {mind.pattern_count} patterns")
|
| 228 |
+
print(f"Gateway URL: {GATEWAY_URL or 'not configured'}")
|
| 229 |
+
app.launch(server_name="0.0.0.0", server_port=7860)
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==5.12.0
|
| 2 |
+
numpy>=1.24.0
|