Instructions to use Invictus-AI/self-evolving-nn with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Keras
How to use Invictus-AI/self-evolving-nn with Keras:
# !pip install -U keras tensorflow huggingface_hub # Keras needs TensorFlow installed to read "hf://" paths, so the tensorflow backend is selected here; # "jax" and "torch" also work for computation once TensorFlow is installed. import os os.environ["KERAS_BACKEND"] = "tensorflow" import keras model = keras.saving.load_model("hf://Invictus-AI/self-evolving-nn") - Notebooks
- Google Colab
- Kaggle
Kashyap Khakhkhar commited on
Upload evo_gui.py with huggingface_hub
Browse files- evo_gui.py +581 -0
evo_gui.py
ADDED
|
@@ -0,0 +1,581 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Flask Web GUI for the Self-Evolving Neural Network.
|
| 4 |
+
Provides real-time monitoring of evolutionary training with:
|
| 5 |
+
- Live fitness charts (Chart.js)
|
| 6 |
+
- Start/Stop/Reset controls
|
| 7 |
+
- Genome architecture visualization
|
| 8 |
+
- Evolution history browser
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import json
|
| 14 |
+
import threading
|
| 15 |
+
import time
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
from flask import Flask, render_template_string, jsonify, request
|
| 20 |
+
|
| 21 |
+
# Import the evolution engine from our main module
|
| 22 |
+
from self_evolving_model import (
|
| 23 |
+
EvolutionEngine, DataHandler, Genome, CHECKPOINT_DIR, log
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 27 |
+
# Global Application State
|
| 28 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 29 |
+
app = Flask(__name__)
|
| 30 |
+
|
| 31 |
+
state = {
|
| 32 |
+
"running": False,
|
| 33 |
+
"generation": 0,
|
| 34 |
+
"total_generations": 0,
|
| 35 |
+
"history": [],
|
| 36 |
+
"best_genome": None,
|
| 37 |
+
"population_summary": [],
|
| 38 |
+
"best_fitness": 0.0,
|
| 39 |
+
"improvement": 0.0,
|
| 40 |
+
"status_message": "Idle. Click Start to begin evolution.",
|
| 41 |
+
"dataset_loaded": False,
|
| 42 |
+
"dataset_info": None,
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
engine: EvolutionEngine = None
|
| 46 |
+
engine_thread: threading.Thread = None
|
| 47 |
+
X_global: np.ndarray = None
|
| 48 |
+
Y_global: np.ndarray = None
|
| 49 |
+
|
| 50 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 51 |
+
# Engine Callback
|
| 52 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 53 |
+
def on_generation_complete(stats, best_genome):
|
| 54 |
+
"""Called by EvolutionEngine after each generation."""
|
| 55 |
+
state["generation"] = stats["generation"] + 1
|
| 56 |
+
state["history"].append(stats)
|
| 57 |
+
state["best_fitness"] = stats["best_fitness"]
|
| 58 |
+
if best_genome:
|
| 59 |
+
state["best_genome"] = best_genome.to_dict()
|
| 60 |
+
state["population_summary"] = [
|
| 61 |
+
g.to_dict() for g in (engine.population if engine else [])
|
| 62 |
+
]
|
| 63 |
+
if len(state["history"]) > 1 and state["history"][0]["best_fitness"] > 0:
|
| 64 |
+
state["improvement"] = (
|
| 65 |
+
(state["history"][-1]["best_fitness"] - state["history"][0]["best_fitness"])
|
| 66 |
+
/ state["history"][0]["best_fitness"] * 100
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def run_evolution_with_data(pop_size, generations, mutation_rate, train_epochs, n_samples):
|
| 71 |
+
"""Background thread: loads dataset (if needed) then runs evolution."""
|
| 72 |
+
global engine, X_global, Y_global
|
| 73 |
+
try:
|
| 74 |
+
state["running"] = True
|
| 75 |
+
state["total_generations"] = generations
|
| 76 |
+
|
| 77 |
+
# Load dataset in background if not pre-loaded
|
| 78 |
+
if X_global is None:
|
| 79 |
+
state["status_message"] = "Loading FABLE.5 dataset..."
|
| 80 |
+
try:
|
| 81 |
+
X_global, Y_global = DataHandler.load_fable_dataset(n_samples=n_samples)
|
| 82 |
+
state["dataset_loaded"] = True
|
| 83 |
+
state["dataset_info"] = f"{X_global.shape[0]} samples, {X_global.shape[1]} features"
|
| 84 |
+
except Exception as e:
|
| 85 |
+
state["status_message"] = f"Dataset load failed: {e}. Using synthetic data."
|
| 86 |
+
log(f"Dataset load failed: {e}. Falling back to synthetic.", "warn")
|
| 87 |
+
X_global, Y_global = None, None
|
| 88 |
+
|
| 89 |
+
state["status_message"] = f"Evolution in progress: 0/{generations} generations"
|
| 90 |
+
|
| 91 |
+
engine = EvolutionEngine(
|
| 92 |
+
pop_size=pop_size,
|
| 93 |
+
generations=generations,
|
| 94 |
+
mutation_rate=mutation_rate,
|
| 95 |
+
train_epochs=train_epochs,
|
| 96 |
+
)
|
| 97 |
+
engine.on_generation_complete = on_generation_complete
|
| 98 |
+
engine.run(X=X_global, Y=Y_global, reset=True)
|
| 99 |
+
|
| 100 |
+
state["status_message"] = (
|
| 101 |
+
f"Evolution complete! Best fitness: {state['best_fitness']:.2f} "
|
| 102 |
+
f"(+{state['improvement']:.1f}%)"
|
| 103 |
+
)
|
| 104 |
+
except Exception as e:
|
| 105 |
+
state["status_message"] = f"Error: {str(e)}"
|
| 106 |
+
log(f"Evolution error: {e}", "error")
|
| 107 |
+
finally:
|
| 108 |
+
state["running"] = False
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 112 |
+
# HTML Template (Single-page app with embedded CSS/JS)
|
| 113 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 114 |
+
HTML_TEMPLATE = r"""<!DOCTYPE html>
|
| 115 |
+
<html lang="en">
|
| 116 |
+
<head>
|
| 117 |
+
<meta charset="UTF-8">
|
| 118 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 119 |
+
<title>𧬠Self-Evolving Neural Network</title>
|
| 120 |
+
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
|
| 121 |
+
<style>
|
| 122 |
+
:root {
|
| 123 |
+
--bg: #0d1117; --surface: #161b22; --border: #30363d;
|
| 124 |
+
--text: #e6edf3; --text-dim: #8b949e; --accent: #58a6ff;
|
| 125 |
+
--green: #3fb950; --red: #f85149; --yellow: #d29922;
|
| 126 |
+
--cyan: #39d353; --purple: #bc8cff;
|
| 127 |
+
}
|
| 128 |
+
* { margin:0; padding:0; box-sizing:border-box; }
|
| 129 |
+
body {
|
| 130 |
+
font-family: 'SF Mono', 'Fira Code', 'Cascadia Code', monospace;
|
| 131 |
+
background: var(--bg); color: var(--text);
|
| 132 |
+
min-height: 100vh; padding: 20px;
|
| 133 |
+
}
|
| 134 |
+
.header {
|
| 135 |
+
text-align: center; padding: 20px 0 10px;
|
| 136 |
+
border-bottom: 1px solid var(--border); margin-bottom: 20px;
|
| 137 |
+
}
|
| 138 |
+
.header h1 { font-size: 1.8em; color: var(--cyan); }
|
| 139 |
+
.header p { color: var(--text-dim); font-size: 0.85em; margin-top: 5px; }
|
| 140 |
+
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; max-width: 1400px; margin: 0 auto; }
|
| 141 |
+
.card {
|
| 142 |
+
background: var(--surface); border: 1px solid var(--border);
|
| 143 |
+
border-radius: 8px; padding: 16px; position: relative;
|
| 144 |
+
}
|
| 145 |
+
.card h2 { font-size: 1em; color: var(--accent); margin-bottom: 12px; border-bottom: 1px solid var(--border); padding-bottom: 8px; }
|
| 146 |
+
.card.full { grid-column: 1 / -1; }
|
| 147 |
+
.stat-row { display: flex; justify-content: space-between; padding: 6px 0; border-bottom: 1px solid var(--border); }
|
| 148 |
+
.stat-label { color: var(--text-dim); font-size: 0.85em; }
|
| 149 |
+
.stat-value { font-weight: bold; font-size: 0.95em; }
|
| 150 |
+
.stat-value.green { color: var(--green); }
|
| 151 |
+
.stat-value.red { color: var(--red); }
|
| 152 |
+
.stat-value.yellow { color: var(--yellow); }
|
| 153 |
+
.stat-value.cyan { color: var(--cyan); }
|
| 154 |
+
.stat-value.accent { color: var(--accent); }
|
| 155 |
+
.controls { display: flex; gap: 10px; margin: 12px 0; flex-wrap: wrap; }
|
| 156 |
+
.btn {
|
| 157 |
+
padding: 10px 20px; border: 1px solid var(--border); border-radius: 6px;
|
| 158 |
+
font-family: inherit; font-size: 0.85em; cursor: pointer;
|
| 159 |
+
transition: all 0.2s; font-weight: 600;
|
| 160 |
+
}
|
| 161 |
+
.btn:hover { transform: translateY(-1px); box-shadow: 0 2px 8px rgba(0,0,0,0.3); }
|
| 162 |
+
.btn-start { background: var(--green); color: #000; }
|
| 163 |
+
.btn-start:hover { background: #2ea043; }
|
| 164 |
+
.btn-stop { background: var(--red); color: #fff; }
|
| 165 |
+
.btn-stop:hover { background: #da3633; }
|
| 166 |
+
.btn:disabled { opacity: 0.4; cursor: not-allowed; transform: none; }
|
| 167 |
+
.params { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin: 10px 0; }
|
| 168 |
+
.params label { font-size: 0.8em; color: var(--text-dim); }
|
| 169 |
+
.params input {
|
| 170 |
+
background: var(--bg); border: 1px solid var(--border); border-radius: 4px;
|
| 171 |
+
color: var(--text); padding: 6px 8px; font-family: inherit; font-size: 0.85em; width: 100%;
|
| 172 |
+
}
|
| 173 |
+
.params input:focus { outline: none; border-color: var(--accent); }
|
| 174 |
+
.status-bar {
|
| 175 |
+
background: var(--bg); border: 1px solid var(--border); border-radius: 6px;
|
| 176 |
+
padding: 10px 14px; margin: 10px 0; font-size: 0.85em;
|
| 177 |
+
display: flex; align-items: center; gap: 8px;
|
| 178 |
+
}
|
| 179 |
+
.status-dot { width: 8px; height: 8px; border-radius: 50%; }
|
| 180 |
+
.status-dot.running { background: var(--green); animation: pulse 1s infinite; }
|
| 181 |
+
.status-dot.idle { background: var(--text-dim); }
|
| 182 |
+
.status-dot.error { background: var(--red); }
|
| 183 |
+
@keyframes pulse { 0%,100% { opacity:1; } 50% { opacity:0.4; } }
|
| 184 |
+
.progress-bar {
|
| 185 |
+
width: 100%; height: 6px; background: var(--border); border-radius: 3px; margin: 8px 0; overflow: hidden;
|
| 186 |
+
}
|
| 187 |
+
.progress-fill {
|
| 188 |
+
height: 100%; background: var(--cyan); border-radius: 3px;
|
| 189 |
+
transition: width 0.5s ease;
|
| 190 |
+
}
|
| 191 |
+
.genome-card {
|
| 192 |
+
background: var(--bg); border: 1px solid var(--border); border-radius: 6px;
|
| 193 |
+
padding: 10px; margin: 6px 0; font-size: 0.8em;
|
| 194 |
+
}
|
| 195 |
+
.genome-card .id { color: var(--purple); font-weight: bold; }
|
| 196 |
+
.genome-card .fitness { color: var(--green); }
|
| 197 |
+
.genome-layers {
|
| 198 |
+
display: flex; gap: 4px; margin: 6px 0; flex-wrap: wrap; align-items: center;
|
| 199 |
+
}
|
| 200 |
+
.layer-chip {
|
| 201 |
+
background: var(--surface); border: 1px solid var(--border); border-radius: 4px;
|
| 202 |
+
padding: 3px 8px; font-size: 0.75em; color: var(--text-dim);
|
| 203 |
+
}
|
| 204 |
+
.layer-chip.active { border-color: var(--accent); color: var(--accent); }
|
| 205 |
+
.arrow { color: var(--text-dim); font-size: 0.8em; }
|
| 206 |
+
.chart-container { position: relative; height: 280px; }
|
| 207 |
+
#log-area {
|
| 208 |
+
background: var(--bg); border: 1px solid var(--border); border-radius: 6px;
|
| 209 |
+
padding: 10px; max-height: 200px; overflow-y: auto; font-size: 0.75em;
|
| 210 |
+
color: var(--text-dim); line-height: 1.6;
|
| 211 |
+
}
|
| 212 |
+
@media (max-width: 800px) { .grid { grid-template-columns: 1fr; } }
|
| 213 |
+
</style>
|
| 214 |
+
</head>
|
| 215 |
+
<body>
|
| 216 |
+
|
| 217 |
+
<div class="header">
|
| 218 |
+
<h1>𧬠Self-Evolving Neural Network</h1>
|
| 219 |
+
<p>Architecture evolves through mutation, crossover & natural selection β trained on FABLE.5 traces</p>
|
| 220 |
+
</div>
|
| 221 |
+
|
| 222 |
+
<div class="grid">
|
| 223 |
+
|
| 224 |
+
<!-- Status & Controls -->
|
| 225 |
+
<div class="card">
|
| 226 |
+
<h2>β‘ Controls</h2>
|
| 227 |
+
<div class="status-bar">
|
| 228 |
+
<div class="status-dot" id="statusDot"></div>
|
| 229 |
+
<span id="statusText">Idle</span>
|
| 230 |
+
</div>
|
| 231 |
+
<div class="progress-bar">
|
| 232 |
+
<div class="progress-fill" id="progressFill" style="width:0%"></div>
|
| 233 |
+
</div>
|
| 234 |
+
<div class="controls">
|
| 235 |
+
<button class="btn btn-start" id="btnStart" onclick="startEvolution()">βΆ Start Evolution</button>
|
| 236 |
+
<button class="btn btn-stop" id="btnStop" onclick="stopEvolution()" disabled>β Stop</button>
|
| 237 |
+
</div>
|
| 238 |
+
<div class="params">
|
| 239 |
+
<div><label>Population Size</label><input type="number" id="popSize" value="6" min="2" max="50"></div>
|
| 240 |
+
<div><label>Generations</label><input type="number" id="generations" value="15" min="1" max="500"></div>
|
| 241 |
+
<div><label>Train Epochs</label><input type="number" id="trainEpochs" value="10" min="1" max="100"></div>
|
| 242 |
+
<div><label>Mutation Rate</label><input type="number" id="mutationRate" value="0.3" min="0" max="1" step="0.05"></div>
|
| 243 |
+
<div><label>Dataset Samples</label><input type="number" id="nSamples" value="5000" min="100" max="200000"></div>
|
| 244 |
+
</div>
|
| 245 |
+
</div>
|
| 246 |
+
|
| 247 |
+
<!-- Statistics -->
|
| 248 |
+
<div class="card">
|
| 249 |
+
<h2>π Statistics</h2>
|
| 250 |
+
<div class="stat-row"><span class="stat-label">Generation</span><span class="stat-value accent" id="statGen">0 / 0</span></div>
|
| 251 |
+
<div class="stat-row"><span class="stat-label">Best Fitness</span><span class="stat-value green" id="statBestFit">β</span></div>
|
| 252 |
+
<div class="stat-row"><span class="stat-label">Avg Fitness</span><span class="stat-value yellow" id="statAvgFit">β</span></div>
|
| 253 |
+
<div class="stat-row"><span class="stat-label">Improvement</span><span class="stat-value cyan" id="statImprovement">β</span></div>
|
| 254 |
+
<div class="stat-row"><span class="stat-label">Population</span><span class="stat-value" id="statPop">β</span></div>
|
| 255 |
+
<div class="stat-row"><span class="stat-label">Best Genome ID</span><span class="stat-value purple" id="statBestId" style="color:var(--purple)">β</span></div>
|
| 256 |
+
<div class="stat-row"><span class="stat-label">Dataset</span><span class="stat-value accent" id="statDataset">Not loaded</span></div>
|
| 257 |
+
</div>
|
| 258 |
+
|
| 259 |
+
<!-- Fitness Chart -->
|
| 260 |
+
<div class="card full">
|
| 261 |
+
<h2>π Fitness Over Generations</h2>
|
| 262 |
+
<div class="chart-container">
|
| 263 |
+
<canvas id="fitnessChart"></canvas>
|
| 264 |
+
</div>
|
| 265 |
+
</div>
|
| 266 |
+
|
| 267 |
+
<!-- Best Genome -->
|
| 268 |
+
<div class="card">
|
| 269 |
+
<h2>π Best Genome</h2>
|
| 270 |
+
<div id="bestGenomeInfo">
|
| 271 |
+
<div class="genome-card">
|
| 272 |
+
<span style="color:var(--text-dim)">No evolution started yet</span>
|
| 273 |
+
</div>
|
| 274 |
+
</div>
|
| 275 |
+
</div>
|
| 276 |
+
|
| 277 |
+
<!-- Population -->
|
| 278 |
+
<div class="card">
|
| 279 |
+
<h2>𧬠Population</h2>
|
| 280 |
+
<div id="populationInfo" style="max-height: 300px; overflow-y: auto;">
|
| 281 |
+
<div style="color:var(--text-dim); font-size:0.85em;">Population will appear here during evolution...</div>
|
| 282 |
+
</div>
|
| 283 |
+
</div>
|
| 284 |
+
|
| 285 |
+
<!-- Log -->
|
| 286 |
+
<div class="card full">
|
| 287 |
+
<h2>π Evolution Log</h2>
|
| 288 |
+
<div id="log-area">Waiting for evolution to start...</div>
|
| 289 |
+
</div>
|
| 290 |
+
|
| 291 |
+
</div>
|
| 292 |
+
|
| 293 |
+
<script>
|
| 294 |
+
// ββ Chart Setup ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 295 |
+
const ctx = document.getElementById('fitnessChart').getContext('2d');
|
| 296 |
+
const fitnessChart = new Chart(ctx, {
|
| 297 |
+
type: 'line',
|
| 298 |
+
data: {
|
| 299 |
+
labels: [],
|
| 300 |
+
datasets: [
|
| 301 |
+
{
|
| 302 |
+
label: 'Best Fitness',
|
| 303 |
+
data: [],
|
| 304 |
+
borderColor: '#3fb950',
|
| 305 |
+
backgroundColor: 'rgba(63,185,80,0.1)',
|
| 306 |
+
fill: true, tension: 0.3, pointRadius: 4, borderWidth: 2,
|
| 307 |
+
},
|
| 308 |
+
{
|
| 309 |
+
label: 'Avg Fitness',
|
| 310 |
+
data: [],
|
| 311 |
+
borderColor: '#d29922',
|
| 312 |
+
backgroundColor: 'rgba(210,153,34,0.05)',
|
| 313 |
+
fill: false, tension: 0.3, pointRadius: 3, borderWidth: 1.5,
|
| 314 |
+
borderDash: [5, 3],
|
| 315 |
+
},
|
| 316 |
+
],
|
| 317 |
+
},
|
| 318 |
+
options: {
|
| 319 |
+
responsive: true, maintainAspectRatio: false,
|
| 320 |
+
plugins: {
|
| 321 |
+
legend: { labels: { color: '#8b949e', font: { family: 'monospace' } } },
|
| 322 |
+
},
|
| 323 |
+
scales: {
|
| 324 |
+
x: { ticks: { color: '#8b949e' }, grid: { color: '#21262d' } },
|
| 325 |
+
y: { ticks: { color: '#8b949e' }, grid: { color: '#21262d' }, beginAtZero: false },
|
| 326 |
+
},
|
| 327 |
+
},
|
| 328 |
+
});
|
| 329 |
+
|
| 330 |
+
// ββ Polling ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 331 |
+
let pollInterval = null;
|
| 332 |
+
|
| 333 |
+
function pollStatus() {
|
| 334 |
+
fetch('/api/status')
|
| 335 |
+
.then(r => r.json())
|
| 336 |
+
.then(data => {
|
| 337 |
+
// Status
|
| 338 |
+
const dot = document.getElementById('statusDot');
|
| 339 |
+
const txt = document.getElementById('statusText');
|
| 340 |
+
if (data.running) {
|
| 341 |
+
dot.className = 'status-dot running';
|
| 342 |
+
document.getElementById('btnStart').disabled = true;
|
| 343 |
+
document.getElementById('btnStop').disabled = false;
|
| 344 |
+
} else {
|
| 345 |
+
dot.className = data.status_message.includes('Error') ? 'status-dot error' : 'status-dot idle';
|
| 346 |
+
document.getElementById('btnStart').disabled = false;
|
| 347 |
+
document.getElementById('btnStop').disabled = true;
|
| 348 |
+
}
|
| 349 |
+
txt.textContent = data.status_message;
|
| 350 |
+
|
| 351 |
+
// Progress
|
| 352 |
+
const pct = data.total_generations > 0
|
| 353 |
+
? (data.generation / data.total_generations * 100) : 0;
|
| 354 |
+
document.getElementById('progressFill').style.width = pct + '%';
|
| 355 |
+
|
| 356 |
+
// Stats
|
| 357 |
+
document.getElementById('statGen').textContent = `${data.generation} / ${data.total_generations}`;
|
| 358 |
+
document.getElementById('statBestFit').textContent = data.best_fitness > 0 ? data.best_fitness.toFixed(4) : 'β';
|
| 359 |
+
document.getElementById('statImprovement').textContent = data.improvement !== 0 ? `${data.improvement > 0 ? '+' : ''}${data.improvement.toFixed(1)}%` : 'β';
|
| 360 |
+
document.getElementById('statPop').textContent = data.population_summary ? data.population_summary.length + ' genomes' : 'β';
|
| 361 |
+
document.getElementById('statBestId').textContent = data.best_genome ? data.best_genome.id : 'β';
|
| 362 |
+
|
| 363 |
+
// Average fitness from last history entry
|
| 364 |
+
if (data.history && data.history.length > 0) {
|
| 365 |
+
const last = data.history[data.history.length - 1];
|
| 366 |
+
document.getElementById('statAvgFit').textContent = last.avg_fitness.toFixed(4);
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
// Dataset
|
| 370 |
+
if (data.dataset_loaded) {
|
| 371 |
+
document.getElementById('statDataset').textContent = data.dataset_info || 'Loaded';
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
// Chart update
|
| 375 |
+
if (data.history && data.history.length > 0) {
|
| 376 |
+
fitnessChart.data.labels = data.history.map((h, i) => `Gen ${i + 1}`);
|
| 377 |
+
fitnessChart.data.datasets[0].data = data.history.map(h => h.best_fitness);
|
| 378 |
+
fitnessChart.data.datasets[1].data = data.history.map(h => h.avg_fitness);
|
| 379 |
+
fitnessChart.update('none');
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
// Best genome
|
| 383 |
+
if (data.best_genome) {
|
| 384 |
+
const g = data.best_genome;
|
| 385 |
+
const cfg = g.config;
|
| 386 |
+
let layersHtml = '';
|
| 387 |
+
cfg.layers.forEach((l, i) => {
|
| 388 |
+
layersHtml += `<span class="layer-chip active">${l.units} ${l.activation.slice(0,4)}</span>`;
|
| 389 |
+
if (i < cfg.layers.length - 1) layersHtml += '<span class="arrow">β</span>';
|
| 390 |
+
});
|
| 391 |
+
document.getElementById('bestGenomeInfo').innerHTML = `
|
| 392 |
+
<div class="genome-card">
|
| 393 |
+
<span class="id">${g.id}</span> β <span class="fitness">Fitness: ${g.fitness.toFixed(4)}</span><br>
|
| 394 |
+
<span style="color:var(--text-dim);font-size:0.8em">
|
| 395 |
+
Layers: ${cfg.num_layers} | LR: ${cfg.learning_rate} | Opt: ${cfg.optimizer} | Born: Gen ${g.generation_born}
|
| 396 |
+
</span>
|
| 397 |
+
<div class="genome-layers">${layersHtml}</div>
|
| 398 |
+
<div style="color:var(--accent);font-size:0.8em;margin-top:4px">
|
| 399 |
+
β‘ Gated: top-3 features [${cfg.top3_features ? cfg.top3_features.join(', ') : '0, 1, 2'}] β layer 1 | rest join layers 2+
|
| 400 |
+
</div>
|
| 401 |
+
</div>`;
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
// Population
|
| 405 |
+
if (data.population_summary && data.population_summary.length > 0) {
|
| 406 |
+
const sorted = [...data.population_summary].sort((a, b) => b.fitness - a.fitness);
|
| 407 |
+
let popHtml = '';
|
| 408 |
+
sorted.forEach((g, i) => {
|
| 409 |
+
const cfg = g.config;
|
| 410 |
+
const layersStr = cfg.layers.map(l => `${l.units}(${l.activation.slice(0,3)})`).join(', ');
|
| 411 |
+
const medal = i === 0 ? 'π₯' : i === 1 ? 'π₯' : i === 2 ? 'π₯' : ' ';
|
| 412 |
+
popHtml += `<div class="genome-card" style="${i < 3 ? 'border-color:var(--accent)' : ''}">
|
| 413 |
+
${medal} <span class="id">${g.id}</span> β <span class="fitness">${g.fitness.toFixed(4)}</span>
|
| 414 |
+
<span style="color:var(--text-dim);font-size:0.75em"> | ${cfg.num_layers}L [{${layersStr}}] ${cfg.optimizer} lr=${cfg.learning_rate}</span>
|
| 415 |
+
</div>`;
|
| 416 |
+
});
|
| 417 |
+
document.getElementById('populationInfo').innerHTML = popHtml;
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
// Log
|
| 421 |
+
if (data.history && data.history.length > 0) {
|
| 422 |
+
const logDiv = document.getElementById('log-area');
|
| 423 |
+
const last = data.history[data.history.length - 1];
|
| 424 |
+
const entry = `[Gen ${last.generation + 1}] Best: ${last.best_fitness.toFixed(4)} | Avg: ${last.avg_fitness.toFixed(4)} | Std: ${last.std_fitness.toFixed(4)}\n`;
|
| 425 |
+
if (!logDiv.textContent.includes(entry.trim())) {
|
| 426 |
+
logDiv.textContent += entry;
|
| 427 |
+
logDiv.scrollTop = logDiv.scrollHeight;
|
| 428 |
+
}
|
| 429 |
+
}
|
| 430 |
+
})
|
| 431 |
+
.catch(err => console.error('Poll error:', err));
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
function startEvolution() {
|
| 435 |
+
const params = {
|
| 436 |
+
pop_size: parseInt(document.getElementById('popSize').value),
|
| 437 |
+
generations: parseInt(document.getElementById('generations').value),
|
| 438 |
+
train_epochs: parseInt(document.getElementById('trainEpochs').value),
|
| 439 |
+
mutation_rate: parseFloat(document.getElementById('mutationRate').value),
|
| 440 |
+
n_samples: parseInt(document.getElementById('nSamples').value),
|
| 441 |
+
};
|
| 442 |
+
|
| 443 |
+
// Clear previous state
|
| 444 |
+
fitnessChart.data.labels = [];
|
| 445 |
+
fitnessChart.data.datasets[0].data = [];
|
| 446 |
+
fitnessChart.data.datasets[1].data = [];
|
| 447 |
+
fitnessChart.update();
|
| 448 |
+
document.getElementById('log-area').textContent = 'Starting evolution...\n';
|
| 449 |
+
|
| 450 |
+
fetch('/api/start', {
|
| 451 |
+
method: 'POST',
|
| 452 |
+
headers: { 'Content-Type': 'application/json' },
|
| 453 |
+
body: JSON.stringify(params),
|
| 454 |
+
})
|
| 455 |
+
.then(r => r.json())
|
| 456 |
+
.then(data => {
|
| 457 |
+
console.log('Start:', data);
|
| 458 |
+
if (!pollInterval) pollInterval = setInterval(pollStatus, 1500);
|
| 459 |
+
})
|
| 460 |
+
.catch(err => console.error('Start error:', err));
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
function stopEvolution() {
|
| 464 |
+
fetch('/api/stop', { method: 'POST' })
|
| 465 |
+
.then(r => r.json())
|
| 466 |
+
.then(data => console.log('Stop:', data));
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
// Auto-poll on load
|
| 470 |
+
pollInterval = setInterval(pollStatus, 2000);
|
| 471 |
+
pollStatus();
|
| 472 |
+
</script>
|
| 473 |
+
</body>
|
| 474 |
+
</html>"""
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 478 |
+
# Flask Routes
|
| 479 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 480 |
+
@app.route("/")
|
| 481 |
+
def index():
|
| 482 |
+
return render_template_string(HTML_TEMPLATE)
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
@app.route("/api/status")
|
| 486 |
+
def api_status():
|
| 487 |
+
return jsonify(state)
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
@app.route("/api/start", methods=["POST"])
|
| 491 |
+
def api_start():
|
| 492 |
+
global engine_thread, X_global, Y_global
|
| 493 |
+
|
| 494 |
+
if state["running"]:
|
| 495 |
+
return jsonify({"error": "Evolution already running"}), 400
|
| 496 |
+
|
| 497 |
+
params = request.get_json() or {}
|
| 498 |
+
|
| 499 |
+
pop_size = params.get("pop_size", 6)
|
| 500 |
+
generations = params.get("generations", 15)
|
| 501 |
+
train_epochs = params.get("train_epochs", 10)
|
| 502 |
+
mutation_rate = params.get("mutation_rate", 0.3)
|
| 503 |
+
n_samples = params.get("n_samples", 5000)
|
| 504 |
+
|
| 505 |
+
# Reset state
|
| 506 |
+
state["history"] = []
|
| 507 |
+
state["generation"] = 0
|
| 508 |
+
state["best_genome"] = None
|
| 509 |
+
state["population_summary"] = []
|
| 510 |
+
state["best_fitness"] = 0.0
|
| 511 |
+
state["improvement"] = 0.0
|
| 512 |
+
|
| 513 |
+
# Start evolution in background thread
|
| 514 |
+
# Dataset loading happens inside the thread to avoid blocking Flask
|
| 515 |
+
engine_thread = threading.Thread(
|
| 516 |
+
target=run_evolution_with_data,
|
| 517 |
+
args=(pop_size, generations, mutation_rate, train_epochs, n_samples),
|
| 518 |
+
daemon=True,
|
| 519 |
+
)
|
| 520 |
+
engine_thread.start()
|
| 521 |
+
|
| 522 |
+
return jsonify({"status": "started", "generations": generations})
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
@app.route("/api/stop", methods=["POST"])
|
| 526 |
+
def api_stop():
|
| 527 |
+
global engine
|
| 528 |
+
if engine and state["running"]:
|
| 529 |
+
engine.stop_event.set()
|
| 530 |
+
state["status_message"] = "Stopping... (finishing current genome)"
|
| 531 |
+
return jsonify({"status": "stopping"})
|
| 532 |
+
return jsonify({"status": "not_running"})
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 536 |
+
# Launch
|
| 537 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 538 |
+
def launch_gui(
|
| 539 |
+
pop_size: int = 6,
|
| 540 |
+
generations: int = 15,
|
| 541 |
+
mutation_rate: float = 0.3,
|
| 542 |
+
train_epochs: int = 10,
|
| 543 |
+
X: np.ndarray = None,
|
| 544 |
+
Y: np.ndarray = None,
|
| 545 |
+
port: int = 5000,
|
| 546 |
+
):
|
| 547 |
+
"""Launch the Flask GUI server."""
|
| 548 |
+
global X_global, Y_global
|
| 549 |
+
|
| 550 |
+
X_global = X
|
| 551 |
+
Y_global = Y
|
| 552 |
+
|
| 553 |
+
if X_global is not None:
|
| 554 |
+
state["dataset_loaded"] = True
|
| 555 |
+
state["dataset_info"] = f"{X_global.shape[0]} samples, {X_global.shape[1]} features"
|
| 556 |
+
log(f"Dataset pre-loaded: {state['dataset_info']}", "success")
|
| 557 |
+
|
| 558 |
+
banner = f"""
|
| 559 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 560 |
+
β 𧬠Self-Evolving Neural Network β Web GUI β
|
| 561 |
+
β Open http://localhost:{port} in your browser β
|
| 562 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"""
|
| 563 |
+
print(banner)
|
| 564 |
+
|
| 565 |
+
app.run(host="0.0.0.0", port=port, debug=False, use_reloader=False)
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
if __name__ == "__main__":
|
| 569 |
+
import argparse
|
| 570 |
+
parser = argparse.ArgumentParser()
|
| 571 |
+
parser.add_argument("--port", type=int, default=5000)
|
| 572 |
+
parser.add_argument("--n-samples", type=int, default=5000)
|
| 573 |
+
args = parser.parse_args()
|
| 574 |
+
|
| 575 |
+
X_data, Y_data = None, None
|
| 576 |
+
try:
|
| 577 |
+
X_data, Y_data = DataHandler.load_fable_dataset(n_samples=args.n_samples)
|
| 578 |
+
except Exception as e:
|
| 579 |
+
log(f"Could not load dataset: {e}. Will use synthetic data.", "warn")
|
| 580 |
+
|
| 581 |
+
launch_gui(X=X_data, Y=Y_data, port=args.port)
|