Evolution / app.py
johangras's picture
feat: Add dynamic weather system to Evolution Aurora
98ba7e7
"""
Evolution Aurora - WORKING DEMO with Real Visual Effects
"""
import json
import os
import random
import time
from datetime import datetime
import gradio as gr
import plotly.graph_objects as go
import numpy as np
# Global state
state = {
"fitness_history": [0.9333],
"events": [],
"particles": [],
"iteration": 0,
"running": False,
"variants_evaluated": 0,
"start_time": None,
"achievements": [],
"high_score": 0.9333,
"player_name": f"Player_{random.randint(1000, 9999)}",
"multiplayer_active": False,
"other_players": {},
"global_best": 0.9333,
"boss_active": False,
"boss_health": 0,
"boss_defeated": False
}
# Simulated multiplayer data
FAKE_PLAYERS = [
{"name": "NeuralNinja_JP", "country": "πŸ‡―πŸ‡΅", "fitness": 0.9455, "status": "evolving"},
{"name": "CodeEvolver_US", "country": "πŸ‡ΊπŸ‡Έ", "fitness": 0.9523, "status": "evolving"},
{"name": "AIWizard_UK", "country": "πŸ‡¬πŸ‡§", "fitness": 0.9812, "status": "leading"},
{"name": "QuantumCoder_DE", "country": "πŸ‡©πŸ‡ͺ", "fitness": 0.9234, "status": "struggling"},
{"name": "MatrixMaster_FR", "country": "πŸ‡«πŸ‡·", "fitness": 0.9667, "status": "evolving"}
]
# Achievement definitions
ACHIEVEMENTS = {
"first_evolution": {"name": "🎯 First Evolution!", "desc": "Started your first evolution", "threshold": 1},
"fast_learner": {"name": "⚑ Fast Learner", "desc": "Reached 95% fitness", "threshold": 0.95},
"perfectionist": {"name": "πŸ’Ž Perfectionist", "desc": "Reached 99% fitness", "threshold": 0.99},
"speed_demon": {"name": "🏎️ Speed Demon", "desc": "Process 10+ variants/sec", "threshold": 10},
"marathon": {"name": "πŸƒ Marathon Runner", "desc": "Run 10+ generations", "threshold": 10}
}
# HTML for aurora effect with epic intro
AURORA_HTML = """
<div id="aurora-container" style="position: relative; width: 100%; height: 400px; background: linear-gradient(to bottom, #000428, #004e92); overflow: hidden; border-radius: 10px;">
<canvas id="aurora-canvas" style="width: 100%; height: 100%;"></canvas>
<div id="title-container" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; z-index: 10;">
<h1 id="main-title" style="color: #00FF88; font-size: 64px; margin: 0; text-shadow: 0 0 30px #00FF88, 0 0 60px #00FF88; animation: pulse 2s ease-in-out infinite;">
Evolution Aurora
</h1>
<p style="color: #FFD700; font-size: 28px; text-shadow: 0 0 20px #FFD700; margin-top: 10px; opacity: 0; animation: fadeIn 2s ease-in 1s forwards;">
Watch AI Learn to Code in Real-Time
</p>
<p id="welcome-msg" style="color: #00AAFF; font-size: 20px; margin-top: 20px; opacity: 0; animation: fadeIn 2s ease-in 2s forwards;">
🧠 Neural Network Visualization | πŸš€ Synapses Fire with Each Improvement
</p>
</div>
</div>
<style>
@keyframes pulse {
0% { transform: scale(1); opacity: 0.8; }
50% { transform: scale(1.05); opacity: 1; }
100% { transform: scale(1); opacity: 0.8; }
}
@keyframes fadeIn {
to { opacity: 1; }
}
@keyframes float {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-10px); }
}
#aurora-container {
box-shadow: 0 10px 40px rgba(123, 63, 242, 0.5);
}
</style>
<script>
const canvas = document.getElementById('aurora-canvas');
const ctx = canvas.getContext('2d');
let particles = [];
let weatherSystem = {
raindrops: [],
lightning: false,
lightningTimer: 0,
rainbow: false,
rainbowOpacity: 0
};
function resizeCanvas() {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
class Particle {
constructor(x, y, color, type = 'normal') {
this.x = x;
this.y = y;
this.vx = (Math.random() - 0.5) * 10;
this.vy = (Math.random() - 0.5) * 10 - 5;
this.life = 100;
this.color = color;
this.size = Math.random() * 4 + 2;
this.type = type;
this.angle = Math.random() * Math.PI * 2;
this.splitCount = 0;
this.trail = [];
}
update() {
// Store trail for quantum particles
if (this.type === 'quantum' && this.trail.length < 20) {
this.trail.push({x: this.x, y: this.y, alpha: this.life / 100});
}
// Quantum behavior
if (this.type === 'quantum') {
// Quantum tunneling
if (Math.random() < 0.02) {
this.x += (Math.random() - 0.5) * 100;
this.y += (Math.random() - 0.5) * 100;
}
// Wave function collapse
this.angle += 0.1;
this.vx += Math.sin(this.angle) * 0.5;
this.vy += Math.cos(this.angle) * 0.5;
// Particle splitting
if (this.life === 50 && this.splitCount === 0) {
this.split();
}
}
// Mouse attraction
const dx = mouseX - this.x;
const dy = mouseY - this.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < 200 && dist > 0) {
const force = 0.5 * (1 - dist / 200);
this.vx += (dx / dist) * force;
this.vy += (dy / dist) * force;
}
this.x += this.vx;
this.y += this.vy;
this.vy += 0.2;
this.life--;
this.vx *= 0.98;
this.vy *= 0.98;
}
split() {
this.splitCount++;
for (let i = 0; i < 3; i++) {
const newParticle = new Particle(this.x, this.y, this.color, 'quantum');
newParticle.vx = (Math.random() - 0.5) * 15;
newParticle.vy = (Math.random() - 0.5) * 15;
newParticle.life = 50;
newParticle.size = this.size * 0.7;
particles.push(newParticle);
}
}
draw() {
// Draw trail for quantum particles
if (this.type === 'quantum' && this.trail.length > 1) {
ctx.save();
ctx.strokeStyle = this.color;
ctx.lineWidth = this.size * 0.5;
for (let i = 1; i < this.trail.length; i++) {
ctx.globalAlpha = this.trail[i].alpha * 0.3;
ctx.beginPath();
ctx.moveTo(this.trail[i-1].x, this.trail[i-1].y);
ctx.lineTo(this.trail[i].x, this.trail[i].y);
ctx.stroke();
}
ctx.restore();
}
ctx.save();
ctx.globalAlpha = this.life / 100;
ctx.fillStyle = this.color;
ctx.shadowBlur = this.type === 'quantum' ? 30 : 20;
ctx.shadowColor = this.color;
// Draw quantum particles with special effect
if (this.type === 'quantum') {
// Outer glow
ctx.beginPath();
ctx.arc(this.x, this.y, this.size * 2, 0, Math.PI * 2);
ctx.globalAlpha = (this.life / 100) * 0.3;
ctx.fill();
// Inner core
ctx.globalAlpha = this.life / 100;
ctx.fillStyle = '#FFFFFF';
ctx.beginPath();
ctx.arc(this.x, this.y, this.size * 0.5, 0, Math.PI * 2);
ctx.fill();
}
// Normal particle
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
}
function createBurst(intensity, type = 'normal') {
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const colors = ['#00FF88', '#7B3FF2', '#00AAFF', '#FFD700', '#FF6B6B', '#4ECDC4', '#45B7D1'];
if (type === 'quantum' || intensity > 4) {
// Create quantum particles for high intensity
for (let i = 0; i < 30 * intensity; i++) {
const angle = (Math.PI * 2 * i) / (30 * intensity);
const speed = Math.random() * 20 + 10;
const color = colors[Math.floor(Math.random() * colors.length)];
const quantum = new Particle(
centerX + Math.cos(angle) * 30,
centerY + Math.sin(angle) * 30,
color,
'quantum'
);
quantum.vx = Math.cos(angle) * speed;
quantum.vy = Math.sin(angle) * speed;
quantum.size = Math.random() * 6 + 3;
particles.push(quantum);
}
}
// Create normal burst
for (let i = 0; i < 100 * intensity; i++) {
const angle = (Math.PI * 2 * i) / (100 * intensity);
const speed = Math.random() * 15 + 5;
const color = colors[Math.floor(Math.random() * colors.length)];
particles.push(new Particle(
centerX + Math.cos(angle) * 20,
centerY + Math.sin(angle) * 20,
color
));
}
// Add some special lightning particles
if (intensity > 3) {
for (let j = 0; j < 20; j++) {
const lightningParticle = new Particle(centerX, centerY, '#FFFFFF');
lightningParticle.size = Math.random() * 8 + 4;
lightningParticle.life = 150;
particles.push(lightningParticle);
}
}
// Add wormhole effect at 99%
if (intensity > 5) {
createWormhole();
}
}
function createWormhole() {
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
// Create spiral of quantum particles
for (let i = 0; i < 100; i++) {
const angle = (i / 100) * Math.PI * 8;
const radius = i * 2;
const wormhole = new Particle(
centerX + Math.cos(angle) * radius,
centerY + Math.sin(angle) * radius,
'#FF00FF',
'quantum'
);
wormhole.vx = -Math.cos(angle) * 5;
wormhole.vy = -Math.sin(angle) * 5;
wormhole.life = 200;
particles.push(wormhole);
}
}
// Click to damage boss
canvas.addEventListener('click', (e) => {
const rect = canvas.getBoundingClientRect();
const x = (e.clientX - rect.left) * (canvas.width / rect.width);
const y = (e.clientY - rect.top) * (canvas.height / rect.height);
// Create burst at click location
for (let i = 0; i < 50; i++) {
const angle = (Math.PI * 2 * i) / 50;
const speed = Math.random() * 10 + 5;
particles.push(new Particle(
x + Math.cos(angle) * 10,
y + Math.sin(angle) * 10,
['#00FF88', '#7B3FF2', '#00AAFF', '#FFD700'][Math.floor(Math.random() * 4)]
));
}
// Damage boss if active and clicked on it
if (bossActive && bossHealth > 0) {
const bossX = canvas.width / 2;
const bossY = canvas.height / 3;
const dist = Math.sqrt((x - bossX) ** 2 + (y - bossY) ** 2);
if (dist < 80) {
bossHealth = Math.max(0, bossHealth - 10);
createBurst(3, 'quantum');
if (bossHealth <= 0 && bossActive) {
// Boss defeated!
bossActive = false;
window.bossDamageCallback && window.bossDamageCallback();
// Victory effects
for (let i = 0; i < 5; i++) {
setTimeout(() => {
createBurst(10, 'quantum');
triggerGlitch();
}, i * 200);
}
}
}
}
});
// Track current fitness for neural network
let currentFitness = 0.9333;
// Weather System
class Raindrop {
constructor() {
this.x = Math.random() * canvas.width;
this.y = -10;
this.speed = Math.random() * 5 + 10;
this.length = Math.random() * 20 + 10;
this.opacity = Math.random() * 0.5 + 0.3;
}
update() {
this.y += this.speed;
if (this.y > canvas.height) {
this.y = -10;
this.x = Math.random() * canvas.width;
}
}
draw() {
ctx.save();
ctx.strokeStyle = `rgba(100, 150, 255, ${this.opacity})`;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.x, this.y + this.length);
ctx.stroke();
ctx.restore();
}
}
function drawWeather() {
// Rain effect
weatherSystem.raindrops.forEach(drop => {
drop.update();
drop.draw();
});
// Lightning effect
if (weatherSystem.lightning && weatherSystem.lightningTimer > 0) {
ctx.save();
ctx.fillStyle = `rgba(255, 255, 255, ${weatherSystem.lightningTimer / 10})`;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw lightning bolt
if (weatherSystem.lightningTimer > 5) {
ctx.strokeStyle = '#FFFFFF';
ctx.lineWidth = 3;
ctx.shadowBlur = 20;
ctx.shadowColor = '#00AAFF';
const startX = Math.random() * canvas.width;
const segments = 5;
let x = startX;
let y = 0;
ctx.beginPath();
ctx.moveTo(x, y);
for (let i = 0; i < segments; i++) {
x += (Math.random() - 0.5) * 100;
y += canvas.height / segments;
ctx.lineTo(x, y);
}
ctx.stroke();
}
ctx.restore();
weatherSystem.lightningTimer--;
}
// Rainbow effect
if (weatherSystem.rainbow && weatherSystem.rainbowOpacity > 0) {
ctx.save();
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height / 2);
const colors = ['#FF0000', '#FF7F00', '#FFFF00', '#00FF00', '#0000FF', '#4B0082', '#9400D3'];
colors.forEach((color, i) => {
gradient.addColorStop(i / (colors.length - 1), color);
});
ctx.fillStyle = gradient;
ctx.globalAlpha = weatherSystem.rainbowOpacity;
ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height, canvas.width, 0, Math.PI, true);
ctx.fill();
ctx.restore();
}
}
function triggerLightning() {
weatherSystem.lightning = true;
weatherSystem.lightningTimer = 10;
// Create burst at lightning strike point
createBurst(3);
}
function startRain() {
// Create raindrops
for (let i = 0; i < 50; i++) {
weatherSystem.raindrops.push(new Raindrop());
}
}
function stopRain() {
weatherSystem.raindrops = [];
}
function showRainbow() {
weatherSystem.rainbow = true;
// Fade in
const fadeIn = setInterval(() => {
weatherSystem.rainbowOpacity += 0.02;
if (weatherSystem.rainbowOpacity >= 0.3) {
clearInterval(fadeIn);
// Fade out after 3 seconds
setTimeout(() => {
const fadeOut = setInterval(() => {
weatherSystem.rainbowOpacity -= 0.02;
if (weatherSystem.rainbowOpacity <= 0) {
weatherSystem.rainbow = false;
weatherSystem.rainbowOpacity = 0;
clearInterval(fadeOut);
}
}, 50);
}, 3000);
}
}, 50);
}
function animate() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw weather effects first (background)
drawWeather();
// Draw neural network (middle layer)
neuralNetwork.update(currentFitness);
neuralNetwork.draw(ctx);
// Draw boss (above neural network)
drawBoss();
// Mouse glow effect
const gradient = ctx.createRadialGradient(mouseX, mouseY, 0, mouseX, mouseY, 100);
gradient.addColorStop(0, 'rgba(123, 63, 242, 0.3)');
gradient.addColorStop(0.5, 'rgba(0, 170, 255, 0.1)');
gradient.addColorStop(1, 'rgba(0, 255, 136, 0)');
ctx.fillStyle = gradient;
ctx.fillRect(mouseX - 100, mouseY - 100, 200, 200);
// Draw particles (foreground layer)
particles = particles.filter(p => {
p.update();
p.draw();
return p.life > 0;
});
// Draw cursor sparkle
ctx.save();
ctx.fillStyle = '#FFFFFF';
ctx.shadowBlur = 20;
ctx.shadowColor = '#00FF88';
ctx.beginPath();
ctx.arc(mouseX, mouseY, 3, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
requestAnimationFrame(animate);
}
animate();
// Trigger burst every 2 seconds
setInterval(() => {
if (Math.random() > 0.3) {
createBurst(Math.random() * 2 + 1);
}
}, 2000);
// Reality glitch effect
let glitchActive = false;
function triggerGlitch() {
glitchActive = true;
document.body.style.filter = 'hue-rotate(180deg) invert(100%)';
setTimeout(() => {
document.body.style.filter = 'hue-rotate(90deg)';
}, 100);
setTimeout(() => {
document.body.style.filter = 'none';
glitchActive = false;
}, 300);
// Create massive quantum burst
createBurst(10, 'quantum');
}
// Boss battle system
let bossActive = false;
let bossHealth = 100;
function drawBoss() {
if (!bossActive) return;
const bossX = canvas.width / 2;
const bossY = canvas.height / 3;
// Boss body (menacing eye)
ctx.save();
ctx.fillStyle = '#FF0000';
ctx.strokeStyle = '#000000';
ctx.lineWidth = 3;
// Outer eye
ctx.beginPath();
ctx.ellipse(bossX, bossY, 80, 40, 0, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
// Inner eye
ctx.fillStyle = '#000000';
ctx.beginPath();
ctx.arc(bossX, bossY, 20, 0, Math.PI * 2);
ctx.fill();
// Pupil that follows mouse
const dx = mouseX - bossX;
const dy = mouseY - bossY;
const angle = Math.atan2(dy, dx);
const pupilX = bossX + Math.cos(angle) * 10;
const pupilY = bossY + Math.sin(angle) * 10;
ctx.fillStyle = '#FFFFFF';
ctx.beginPath();
ctx.arc(pupilX, pupilY, 5, 0, Math.PI * 2);
ctx.fill();
// Health bar
ctx.fillStyle = 'rgba(255, 0, 0, 0.8)';
ctx.fillRect(bossX - 50, bossY - 70, 100, 10);
ctx.fillStyle = 'rgba(0, 255, 0, 0.8)';
ctx.fillRect(bossX - 50, bossY - 70, bossHealth, 10);
ctx.strokeRect(bossX - 50, bossY - 70, 100, 10);
// Boss title
ctx.fillStyle = '#FFFFFF';
ctx.font = 'bold 20px Arial';
ctx.textAlign = 'center';
ctx.fillText('THE LOCAL OPTIMUM', bossX, bossY - 80);
ctx.restore();
// Boss attacks
if (Math.random() < 0.02 && bossHealth > 0) {
// Laser beam attack
for (let i = 0; i < 20; i++) {
const attackParticle = new Particle(
bossX + (Math.random() - 0.5) * 50,
bossY,
'#FF0000'
);
attackParticle.vy = 10;
attackParticle.vx = (Math.random() - 0.5) * 5;
particles.push(attackParticle);
}
}
}
// Watch for quantum and boss events
const watchQuantum = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
const text = mutation.target.textContent || '';
if (text.includes('QUANTUM REALM ENTERED')) {
createBurst(5, 'quantum');
} else if (text.includes('BOSS APPEARED')) {
bossActive = true;
bossHealth = 100;
speak("Warning! Final boss detected. The Local Optimum blocks your path to perfection!", 1.1, 0.8);
} else if (text.includes('BOSS DEFEATED')) {
bossActive = false;
bossHealth = 0;
createBurst(20, 'quantum'); // Massive victory explosion
triggerGlitch();
speak("Victory! You have achieved perfection! 100 percent fitness!", 1.2, 1.2);
}
// Check for fitness updates
const fitnessMatch = text.match(/Fitness (\d+\.\d+)/);
if (fitnessMatch) {
const newFitness = parseFloat(fitnessMatch[1]);
if (newFitness > currentFitness) {
const improvement = newFitness - currentFitness;
currentFitness = newFitness;
// Trigger neural network firing
neuralNetwork.triggerFitnessImprovement(improvement);
// Weather effects based on improvement
if (improvement > 0.005) {
triggerLightning(); // Lightning for major improvements
}
// Rainbow at 95%
if (newFitness >= 0.95 && currentFitness < 0.96) {
showRainbow();
stopRain();
}
// Rain when plateauing
if (improvement < 0.002 && weatherSystem.raindrops.length === 0) {
startRain();
}
}
}
});
});
setTimeout(() => {
const eventLog = document.querySelector('[id*="event_log"]');
if (eventLog) watchQuantum.observe(eventLog, { childList: true, subtree: true });
// Also watch fitness display directly
const fitnessDisplay = document.querySelector('[id*="fitness_display"]');
if (fitnessDisplay) {
const fitnessObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
const input = mutation.target.querySelector('input');
if (input && input.value) {
const newFitness = parseFloat(input.value);
if (!isNaN(newFitness) && newFitness !== currentFitness) {
currentFitness = newFitness;
}
}
});
});
fitnessObserver.observe(fitnessDisplay, { childList: true, subtree: true, attributes: true });
}
}, 2000);
// Epic initial burst sequence
setTimeout(() => {
createBurst(5); // Massive initial burst
document.getElementById('welcome-msg').style.fontSize = '24px';
}, 500);
setTimeout(() => createBurst(3), 1500);
setTimeout(() => createBurst(4), 2500);
// Neural Network Visualization
class NeuralNetwork {
constructor() {
this.neurons = [];
this.synapses = [];
this.layers = [5, 8, 6, 4, 1]; // Network architecture
this.setupNetwork();
this.pulsePhase = 0;
this.lastFitness = 0.9333;
this.firingNeurons = new Set();
this.brainWavePhase = 0;
}
setupNetwork() {
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const networkWidth = 400;
const networkHeight = 300;
// Create neurons for each layer
for (let layer = 0; layer < this.layers.length; layer++) {
const layerNeurons = [];
const x = centerX - networkWidth/2 + (layer / (this.layers.length - 1)) * networkWidth;
for (let i = 0; i < this.layers[layer]; i++) {
const y = centerY - networkHeight/2 + ((i + 0.5) / this.layers[layer]) * networkHeight;
layerNeurons.push({
x: x,
y: y,
layer: layer,
index: i,
activation: Math.random() * 0.3,
pulseOffset: Math.random() * Math.PI * 2,
size: layer === this.layers.length - 1 ? 15 : 8 - layer // Output neuron is bigger
});
}
this.neurons.push(layerNeurons);
}
// Create synapses between layers
for (let layer = 0; layer < this.layers.length - 1; layer++) {
for (let i = 0; i < this.neurons[layer].length; i++) {
for (let j = 0; j < this.neurons[layer + 1].length; j++) {
this.synapses.push({
from: this.neurons[layer][i],
to: this.neurons[layer + 1][j],
weight: Math.random() * 0.5 + 0.1,
active: false,
pulseProgress: 0
});
}
}
}
}
update(currentFitness) {
this.pulsePhase += 0.02;
this.brainWavePhase += 0.015;
// Check if fitness improved
const fitnessImproved = currentFitness > this.lastFitness + 0.0001;
if (fitnessImproved) {
// Activate firing sequence
this.triggerFitnessImprovement(currentFitness - this.lastFitness);
}
this.lastFitness = currentFitness;
// Update neuron activations with brain wave effect
for (let layer of this.neurons) {
for (let neuron of layer) {
// Base pulsing
neuron.activation = 0.3 + 0.2 * Math.sin(this.pulsePhase + neuron.pulseOffset);
// Add brain wave effect
const waveInfluence = Math.sin(this.brainWavePhase + neuron.x * 0.01 + neuron.y * 0.01) * 0.2;
neuron.activation += waveInfluence;
// Firing neurons glow brighter
if (this.firingNeurons.has(neuron)) {
neuron.activation = Math.min(1, neuron.activation + 0.5);
}
}
}
// Update synapses
for (let synapse of this.synapses) {
if (synapse.active) {
synapse.pulseProgress += 0.05;
if (synapse.pulseProgress >= 1) {
synapse.active = false;
synapse.pulseProgress = 0;
// Activate the target neuron
this.firingNeurons.add(synapse.to);
setTimeout(() => this.firingNeurons.delete(synapse.to), 500);
}
}
}
}
triggerFitnessImprovement(improvement) {
// Fire neurons based on improvement magnitude
const fireCount = Math.min(20, Math.floor(improvement * 1000));
// Major milestone effects
if (this.lastFitness >= 0.95 && this.lastFitness < 0.95 + improvement) {
// 95% milestone - neural storm
this.triggerNeuralStorm();
}
if (this.lastFitness >= 0.99 && this.lastFitness < 0.99 + improvement) {
// 99% milestone - neural overload
this.triggerNeuralOverload();
}
// Start with random input neurons
for (let i = 0; i < fireCount; i++) {
const neuron = this.neurons[0][Math.floor(Math.random() * this.neurons[0].length)];
this.firingNeurons.add(neuron);
// Propagate through network
setTimeout(() => {
this.propagateActivation(neuron);
}, i * 50);
}
// Create synapse firing wave
const synapsesToFire = this.synapses.filter(s => Math.random() < improvement * 50);
synapsesToFire.forEach((synapse, i) => {
setTimeout(() => {
synapse.active = true;
synapse.pulseProgress = 0;
}, i * 20);
});
}
triggerNeuralStorm() {
// Fire all neurons in waves
for (let layer = 0; layer < this.neurons.length; layer++) {
setTimeout(() => {
this.neurons[layer].forEach(neuron => {
this.firingNeurons.add(neuron);
setTimeout(() => this.firingNeurons.delete(neuron), 1000);
});
}, layer * 200);
}
// Activate many synapses
this.synapses.forEach((synapse, i) => {
if (Math.random() < 0.7) {
setTimeout(() => {
synapse.active = true;
synapse.pulseProgress = 0;
}, Math.random() * 1000);
}
});
}
triggerNeuralOverload() {
// Extreme effect - all neurons and synapses fire rapidly
const overloadDuration = 3000;
const overloadInterval = setInterval(() => {
// Random neurons fire
for (let i = 0; i < 10; i++) {
const layer = Math.floor(Math.random() * this.neurons.length);
const index = Math.floor(Math.random() * this.neurons[layer].length);
const neuron = this.neurons[layer][index];
this.firingNeurons.add(neuron);
setTimeout(() => this.firingNeurons.delete(neuron), 200);
}
// Random synapses fire
for (let i = 0; i < 20; i++) {
const synapse = this.synapses[Math.floor(Math.random() * this.synapses.length)];
synapse.active = true;
synapse.pulseProgress = 0;
}
}, 100);
setTimeout(() => clearInterval(overloadInterval), overloadDuration);
}
propagateActivation(neuron) {
// Find synapses from this neuron
const outgoingSynapses = this.synapses.filter(s => s.from === neuron);
outgoingSynapses.forEach((synapse, i) => {
setTimeout(() => {
synapse.active = true;
synapse.pulseProgress = 0;
}, i * 100);
});
}
draw(ctx) {
ctx.save();
// Set overall neural network opacity
ctx.globalAlpha = 0.7;
// Draw brain scan background effect
this.drawBrainScan(ctx);
// Draw synapses
for (let synapse of this.synapses) {
ctx.save();
const baseAlpha = 0.2 + synapse.weight * 0.3;
ctx.globalAlpha = synapse.active ? Math.min(1, baseAlpha + 0.6) : baseAlpha;
// Draw synapse line
ctx.beginPath();
ctx.moveTo(synapse.from.x, synapse.from.y);
ctx.lineTo(synapse.to.x, synapse.to.y);
const gradient = ctx.createLinearGradient(
synapse.from.x, synapse.from.y,
synapse.to.x, synapse.to.y
);
if (synapse.active) {
// Firing synapse - animated pulse
const pulsePos = synapse.pulseProgress;
gradient.addColorStop(0, 'rgba(0, 255, 136, 0.1)');
gradient.addColorStop(Math.max(0, pulsePos - 0.1), 'rgba(0, 255, 136, 0.1)');
gradient.addColorStop(pulsePos, 'rgba(255, 255, 255, 1)');
gradient.addColorStop(Math.min(1, pulsePos + 0.1), 'rgba(0, 255, 136, 0.1)');
gradient.addColorStop(1, 'rgba(123, 63, 242, 0.1)');
ctx.lineWidth = 3;
ctx.shadowBlur = 20;
ctx.shadowColor = '#00FF88';
} else {
gradient.addColorStop(0, 'rgba(0, 170, 255, 0.2)');
gradient.addColorStop(1, 'rgba(123, 63, 242, 0.2)');
ctx.lineWidth = 1;
}
ctx.strokeStyle = gradient;
ctx.stroke();
ctx.restore();
}
// Draw neurons
for (let layer of this.neurons) {
for (let neuron of layer) {
ctx.save();
const isFiring = this.firingNeurons.has(neuron);
const isOutput = neuron.layer === this.layers.length - 1;
// Neuron glow
if (isFiring || isOutput) {
const glowGradient = ctx.createRadialGradient(
neuron.x, neuron.y, 0,
neuron.x, neuron.y, neuron.size * 3
);
glowGradient.addColorStop(0, isFiring ? 'rgba(255, 255, 255, 0.5)' : 'rgba(255, 215, 0, 0.3)');
glowGradient.addColorStop(0.5, isFiring ? 'rgba(0, 255, 136, 0.3)' : 'rgba(255, 215, 0, 0.1)');
glowGradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
ctx.fillStyle = glowGradient;
ctx.fillRect(neuron.x - neuron.size * 3, neuron.y - neuron.size * 3,
neuron.size * 6, neuron.size * 6);
}
// Neuron body
ctx.beginPath();
ctx.arc(neuron.x, neuron.y, neuron.size, 0, Math.PI * 2);
const neuronGradient = ctx.createRadialGradient(
neuron.x - neuron.size/3, neuron.y - neuron.size/3, 0,
neuron.x, neuron.y, neuron.size
);
if (isOutput) {
// Output neuron - golden
neuronGradient.addColorStop(0, '#FFD700');
neuronGradient.addColorStop(1, '#FFA500');
} else if (isFiring) {
// Firing neuron - bright white/green
neuronGradient.addColorStop(0, '#FFFFFF');
neuronGradient.addColorStop(1, '#00FF88');
} else {
// Normal neuron - blue/purple gradient
const brightness = neuron.activation;
neuronGradient.addColorStop(0, `rgba(0, 170, 255, ${brightness})`);
neuronGradient.addColorStop(1, `rgba(123, 63, 242, ${brightness * 0.7})`);
}
ctx.fillStyle = neuronGradient;
ctx.fill();
// Neuron outline
ctx.strokeStyle = isFiring ? '#FFFFFF' : 'rgba(255, 255, 255, 0.2)';
ctx.lineWidth = isFiring ? 2 : 1;
ctx.stroke();
ctx.restore();
}
}
ctx.restore();
}
drawBrainScan(ctx) {
// Brain scan effect - concentric circles emanating from center
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
ctx.save();
// Draw multiple scan waves
for (let i = 0; i < 5; i++) {
const radius = (this.brainWavePhase * 100 + i * 100) % 500;
const alpha = Math.max(0, 1 - radius / 500) * 0.3;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
// Create gradient stroke
const gradient = ctx.createRadialGradient(centerX, centerY, radius - 10, centerX, centerY, radius + 10);
gradient.addColorStop(0, `rgba(0, 255, 136, 0)`);
gradient.addColorStop(0.5, `rgba(0, 255, 136, ${alpha})`);
gradient.addColorStop(1, `rgba(123, 63, 242, 0)`);
ctx.strokeStyle = gradient;
ctx.lineWidth = 3;
ctx.stroke();
}
// Add "thinking" pulses randomly
if (Math.random() < 0.05) {
// Random thinking pulse
const pulseX = centerX + (Math.random() - 0.5) * 300;
const pulseY = centerY + (Math.random() - 0.5) * 200;
const pulseGradient = ctx.createRadialGradient(pulseX, pulseY, 0, pulseX, pulseY, 50);
pulseGradient.addColorStop(0, 'rgba(255, 255, 255, 0.4)');
pulseGradient.addColorStop(0.5, 'rgba(0, 170, 255, 0.2)');
pulseGradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
ctx.fillStyle = pulseGradient;
ctx.fillRect(pulseX - 50, pulseY - 50, 100, 100);
}
ctx.restore();
}
}
// Initialize neural network
const neuralNetwork = new NeuralNetwork();
// Mouse interaction
let mouseX = canvas.width / 2;
let mouseY = canvas.height / 2;
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
mouseX = (e.clientX - rect.left) * (canvas.width / rect.width);
mouseY = (e.clientY - rect.top) * (canvas.height / rect.height);
});
// Auto-start evolution after intro
setTimeout(() => {
const startBtn = document.querySelector('.gr-button-primary');
if (startBtn && startBtn.textContent.includes('Start')) {
startBtn.click();
}
}, 4000);
// Boss defeat callback is now defined in the main app
</script>
"""
def create_3d_landscape():
"""Create an animated 3D fitness landscape."""
# Create mesh grid
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, y)
# Create landscape with multiple peaks
Z = np.sin(np.sqrt(X**2 + Y**2)) / np.sqrt(X**2 + Y**2 + 1)
Z += 0.5 * np.exp(-((X-2)**2 + (Y-2)**2) / 3)
Z += 0.8 * np.exp(-((X+2)**2 + (Y-1)**2) / 2)
fig = go.Figure(data=[go.Surface(
x=X, y=Y, z=Z,
colorscale=[
[0, '#0A0A2A'],
[0.5, '#7B3FF2'],
[1, '#00FF88']
],
opacity=0.9,
lighting=dict(
ambient=0.4,
diffuse=0.5,
specular=0.2,
roughness=0.5,
fresnel=0.2
),
lightposition=dict(x=-100, y=-100, z=50)
)])
# Add moving points representing evolving programs
if state["fitness_history"]:
n_points = min(len(state["fitness_history"]), 10)
for i in range(n_points):
t = i / max(n_points - 1, 1)
fitness = state["fitness_history"][-(n_points-i)]
# Spiral path
angle = t * 4 * np.pi
radius = 3 * (1 - t)
x_pos = radius * np.cos(angle)
y_pos = radius * np.sin(angle)
z_pos = fitness - 0.9
fig.add_trace(go.Scatter3d(
x=[x_pos], y=[y_pos], z=[z_pos],
mode='markers',
marker=dict(
size=10,
color='#FFD700' if i == n_points - 1 else '#00FF88',
symbol='diamond'
),
showlegend=False
))
fig.update_layout(
scene=dict(
xaxis=dict(showgrid=False, showticklabels=False, title=''),
yaxis=dict(showgrid=False, showticklabels=False, title=''),
zaxis=dict(showgrid=True, title='Fitness'),
camera=dict(
eye=dict(x=1.5, y=1.5, z=1.5),
up=dict(x=0, y=0, z=1)
),
aspectmode='cube'
),
paper_bgcolor='#0A0A2A',
plot_bgcolor='#0A0A2A',
height=500,
margin=dict(l=0, r=0, t=0, b=0)
)
return fig
def create_fitness_chart():
"""Create animated fitness progress chart."""
fig = go.Figure()
if state["fitness_history"]:
x = list(range(len(state["fitness_history"])))
y = state["fitness_history"]
# Main line
fig.add_trace(go.Scatter(
x=x, y=y,
mode='lines+markers',
name='Fitness',
line=dict(color='#00FF88', width=4),
marker=dict(size=8, color='#7B3FF2', line=dict(color='#00FF88', width=2))
))
# Add glow effect
fig.add_trace(go.Scatter(
x=x, y=y,
mode='lines',
line=dict(color='#00FF88', width=12),
opacity=0.3,
showlegend=False
))
fig.update_layout(
xaxis=dict(
title='Generation',
gridcolor='#333',
zerolinecolor='#333'
),
yaxis=dict(
title='Fitness Score',
gridcolor='#333',
zerolinecolor='#333',
range=[0.9, 1.0]
),
paper_bgcolor='#0A0A2A',
plot_bgcolor='#0A0A2A',
font=dict(color='#FFF'),
height=400,
showlegend=False
)
return fig
def update_multiplayer():
"""Update multiplayer state with other players' progress."""
if not state["multiplayer_active"]:
return
# Simulate other players making progress
for player in FAKE_PLAYERS:
if random.random() < 0.3: # 30% chance of improvement
improvement = random.uniform(0.001, 0.01)
player["fitness"] = min(player["fitness"] + improvement, 0.9999)
# Check if someone beat us
current_fitness = state["fitness_history"][-1] if state["fitness_history"] else 0.9333
if player["fitness"] > current_fitness and player["fitness"] > state["global_best"]:
state["global_best"] = player["fitness"]
state["events"].append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": "multiplayer",
"message": f"⚑ {player['name']} {player['country']} TOOK THE LEAD! ({player['fitness']:.4f})"
})
def format_multiplayer_leaderboard():
"""Format live multiplayer leaderboard."""
current_fitness = state["fitness_history"][-1] if state["fitness_history"] else 0.9333
# Combine all players
all_players = [{"name": state["player_name"], "country": "🏴", "fitness": current_fitness, "status": "you"}]
all_players.extend(FAKE_PLAYERS)
# Sort by fitness
all_players.sort(key=lambda x: x["fitness"], reverse=True)
html = '''
<div style="background: linear-gradient(135deg, #1a1a3a, #0a0a2a); padding: 20px; border-radius: 10px; border: 2px solid #7B3FF2;">
<h3 style="color: #FFD700; margin-top: 0; text-align: center;">πŸ† LIVE GLOBAL LEADERBOARD</h3>
<div style="max-height: 400px; overflow-y: auto;">
'''
for i, player in enumerate(all_players):
rank = i + 1
medal = "πŸ₯‡" if rank == 1 else "πŸ₯ˆ" if rank == 2 else "πŸ₯‰" if rank == 3 else f"#{rank}"
is_you = player["status"] == "you"
bg_color = "linear-gradient(45deg, #FFD700, #FFA500)" if is_you else "rgba(123, 63, 242, 0.2)"
border = "2px solid #FFD700" if rank == 1 else "1px solid rgba(255, 255, 255, 0.1)"
html += f'''
<div style="background: {bg_color}; margin: 10px 0; padding: 15px; border-radius: 8px; border: {border};
{'animation: pulse 2s infinite;' if is_you else ''} transition: all 0.3s;">
<div style="display: flex; justify-content: space-between; align-items: center;">
<div style="font-size: 20px; color: {'#000' if is_you else '#FFF'};">
{medal} {player['country']} <strong>{player['name']}</strong>
{' (YOU)' if is_you else ''}
</div>
<div style="font-size: 24px; color: {'#000' if is_you else '#00FF88'}; font-weight: bold;">
{player['fitness']:.4f}
</div>
</div>
{'<div style="color: #FFD700; font-size: 14px; margin-top: 5px;">πŸ”₯ YOUR POSITION</div>' if is_you else ''}
</div>
'''
html += '''
</div>
<div style="text-align: center; margin-top: 20px;">
<button style="background: linear-gradient(45deg, #FF6B6B, #4ECDC4); color: white; border: none;
padding: 10px 30px; border-radius: 25px; font-size: 18px; cursor: pointer;"
onclick="alert('Multiplayer Battle Mode: Coming Soon!')">
βš”οΈ CHALLENGE TOP PLAYER
</button>
</div>
</div>
'''
return html
def handle_boss_defeat():
"""Handle boss defeat and reach 100% fitness."""
if state["boss_active"] and state["boss_health"] <= 0:
state["boss_defeated"] = True
state["boss_active"] = False
state["fitness_history"].append(1.0) # 100% fitness!
state["events"].append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": "victory",
"message": "πŸŽ‰ BOSS DEFEATED! You've achieved 100% FITNESS! PERFECTION ATTAINED!"
})
# Unlock special achievement
if "perfection_plus" not in state["achievements"]:
state["achievements"].append("perfection_plus")
state["events"].append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": "achievement",
"message": "πŸ† LEGENDARY ACHIEVEMENT: Perfection Plus Ultra!"
})
return True
return False
def simulate_evolution():
"""Simulate one evolution step."""
if not state["running"]:
return
state["iteration"] += 1
# Update multiplayer if active
if state["multiplayer_active"]:
update_multiplayer()
# Simulate evaluating multiple variants (Modal parallel execution)
variants_this_gen = random.randint(4, 8) # Simulating parallel evaluation
state["variants_evaluated"] += variants_this_gen
# Simulate fitness improvement
current_fitness = state["fitness_history"][-1]
improvement = random.uniform(0.001, 0.015) * (1 - current_fitness)
new_fitness = min(current_fitness + improvement, 0.9999)
state["fitness_history"].append(new_fitness)
# Check for new achievements
new_achievements = check_achievements()
# Add event
event = {
"time": datetime.now().strftime("%H:%M:%S"),
"type": "improvement" if improvement > 0.005 else "minor",
"message": f"Generation {state['iteration']}: Fitness {new_fitness:.4f} (+{improvement:.4f}) - {variants_this_gen} variants evaluated"
}
state["events"].append(event)
# Add achievement events
for ach in new_achievements:
state["events"].append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": "achievement",
"message": f"πŸ† ACHIEVEMENT UNLOCKED: {ach['name']}"
})
# Trigger quantum effects at high fitness levels
if new_fitness >= 0.95 and current_fitness < 0.95:
state["events"].append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": "quantum",
"message": "βš›οΈ QUANTUM REALM ENTERED! Reality is bending..."
})
if new_fitness >= 0.99 and current_fitness < 0.99:
state["events"].append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": "boss",
"message": "πŸ‘Ύ FINAL BOSS APPEARED: The Local Optimum! Click on it to attack!"
})
# Trigger boss battle
state["boss_active"] = True
state["boss_health"] = 100
# Boss battle progress
if state["boss_active"] and state["boss_health"] > 0:
# Boss slowly damages our fitness
damage = random.uniform(0.0001, 0.0005)
new_fitness = max(0.98, new_fitness - damage)
state["fitness_history"][-1] = new_fitness
return event
def get_evolved_code():
"""Generate example of evolved code with improvements."""
iteration = state.get("iteration", 0)
fitness = state["fitness_history"][-1] if state["fitness_history"] else 0.9333
# Base code
base_code = '''def create_model(X_train, y_train):
"""Create and train a DecisionTree model."""
model = DecisionTreeClassifier(
max_depth=3,
min_samples_split=2,
random_state=42
)
model.fit(X_train, y_train)
return model'''
# Evolved improvements based on iteration
if iteration == 0:
return base_code, base_code, []
improvements = []
evolved_code = base_code
if iteration >= 1:
evolved_code = evolved_code.replace("max_depth=3", "max_depth=5")
improvements.append("↑ Increased max_depth: 3 β†’ 5")
if iteration >= 2:
evolved_code = evolved_code.replace("min_samples_split=2", "min_samples_split=5")
improvements.append("↑ Optimized min_samples_split: 2 β†’ 5")
if iteration >= 3:
evolved_code = evolved_code.replace(
"model = DecisionTreeClassifier(",
"model = DecisionTreeClassifier(\n criterion='entropy',"
)
improvements.append("+ Added entropy criterion")
if iteration >= 4:
evolved_code = evolved_code.replace("random_state=42", "random_state=42,\n min_samples_leaf=2")
improvements.append("+ Added min_samples_leaf constraint")
return base_code, evolved_code, improvements
def format_code_display():
"""Format code evolution display with syntax highlighting."""
original, evolved, improvements = get_evolved_code()
html = f'''
<div style="background: #0A0A2A; padding: 20px; border-radius: 10px;">
<h3 style="color: #00FF88; margin-top: 0;">🧬 Code Evolution</h3>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
<div>
<h4 style="color: #7B3FF2;">Original Code</h4>
<pre style="background: #1a1a3a; padding: 15px; border-radius: 5px; color: #fff; overflow-x: auto;"><code>{original}</code></pre>
</div>
<div>
<h4 style="color: #00FF88;">Evolved Code (Gen {state.get("iteration", 0)})</h4>
<pre style="background: #1a1a3a; padding: 15px; border-radius: 5px; color: #fff; overflow-x: auto; border: 2px solid #00FF88;"><code>{evolved}</code></pre>
</div>
</div>
<div style="margin-top: 20px;">
<h4 style="color: #FFD700;">✨ Improvements Applied:</h4>
<ul style="color: #00AAFF; list-style: none; padding: 0;">
{"".join(f'<li style="margin: 5px 0;">β€’ {imp}</li>' for imp in improvements) if improvements else '<li>β€’ Analyzing code patterns...</li>'}
</ul>
</div>
</div>
'''
return html
def check_achievements():
"""Check and award achievements."""
new_achievements = []
# First evolution
if state["iteration"] >= 1 and "first_evolution" not in state["achievements"]:
state["achievements"].append("first_evolution")
new_achievements.append(ACHIEVEMENTS["first_evolution"])
# Fitness achievements
current_fitness = state["fitness_history"][-1] if state["fitness_history"] else 0
if current_fitness >= 0.95 and "fast_learner" not in state["achievements"]:
state["achievements"].append("fast_learner")
new_achievements.append(ACHIEVEMENTS["fast_learner"])
if current_fitness >= 0.99 and "perfectionist" not in state["achievements"]:
state["achievements"].append("perfectionist")
new_achievements.append(ACHIEVEMENTS["perfectionist"])
# Speed achievement
if state["start_time"] and state["variants_evaluated"] > 0:
elapsed = time.time() - state["start_time"]
if elapsed > 0:
speed = state["variants_evaluated"] / elapsed
if speed >= 10 and "speed_demon" not in state["achievements"]:
state["achievements"].append("speed_demon")
new_achievements.append(ACHIEVEMENTS["speed_demon"])
# Marathon achievement
if state["iteration"] >= 10 and "marathon" not in state["achievements"]:
state["achievements"].append("marathon")
new_achievements.append(ACHIEVEMENTS["marathon"])
# Update high score
if current_fitness > state["high_score"]:
state["high_score"] = current_fitness
return new_achievements
def format_achievements():
"""Format achievements display."""
html = '<div style="background: #0A0A2A; padding: 20px; border-radius: 10px;">'
html += '<h3 style="color: #FFD700; margin-top: 0;">πŸ† Achievements</h3>'
html += '<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px;">'
for ach_id in state["achievements"]:
ach = ACHIEVEMENTS.get(ach_id, {})
html += f'''
<div style="background: linear-gradient(45deg, #7B3FF2, #00AAFF); padding: 10px; border-radius: 8px; text-align: center;">
<div style="font-size: 24px;">{ach.get("name", "")}</div>
<div style="font-size: 12px; color: #FFD700;">{ach.get("desc", "")}</div>
</div>
'''
if not state["achievements"]:
html += '<div style="color: #666; text-align: center; width: 100%;">Start evolving to unlock achievements!</div>'
html += '</div>'
html += f'<div style="margin-top: 20px; text-align: center; color: #00FF88; font-size: 20px;">High Score: {state["high_score"]:.4f}</div>'
html += '</div>'
return html
def get_share_text():
"""Generate share text for social media."""
fitness = state["fitness_history"][-1] if state["fitness_history"] else 0.9333
achievements_count = len(state["achievements"])
text = f"🌟 Evolution Aurora: I evolved AI to {fitness:.2%} fitness with {achievements_count} achievements unlocked! Can you beat my score?\n\n"
text += "Try it yourself: https://huggingface.co/spaces/Agents-MCP-Hackathon/Evolution\n"
text += "#EvolutionAurora #AIEvolution #HuggingFace"
return text
def format_events():
"""Format events for display."""
html = '<div style="background: #0A0A2A; padding: 15px; border-radius: 10px; height: 300px; overflow-y: auto; font-family: monospace;">'
for event in state["events"][-20:][::-1]:
if event["type"] == "victory":
color = "#FFD700"
icon = "πŸŽ‰"
style = "font-size: 20px; font-weight: bold; background: linear-gradient(45deg, #FFD700, #FF6B6B); padding: 15px; border-radius: 10px; margin: 10px 0; animation: pulse 0.5s infinite; text-shadow: 0 0 20px #FFD700; border: 3px solid #FFD700;"
elif event["type"] == "boss":
color = "#FF0000"
icon = "πŸ‘Ύ"
style = "font-size: 18px; font-weight: bold; background: rgba(255, 0, 0, 0.3); padding: 12px; border-radius: 8px; margin: 8px 0; border: 2px solid #FF0000; animation: pulse 2s infinite;"
elif event["type"] == "achievement":
color = "#FFD700"
icon = "πŸ†"
style = "font-size: 16px; font-weight: bold; background: linear-gradient(45deg, #7B3FF2, #00AAFF); padding: 10px; border-radius: 5px; margin: 5px 0;"
elif event["type"] == "quantum":
color = "#FF00FF"
icon = "βš›οΈ"
style = "font-size: 18px; font-weight: bold; background: linear-gradient(45deg, #FF00FF, #00FFFF); padding: 12px; border-radius: 8px; margin: 8px 0; animation: pulse 1s infinite; text-shadow: 0 0 10px #FF00FF;"
elif event["type"] == "multiplayer":
color = "#FF6B6B"
icon = "βš”οΈ"
style = "font-size: 14px; font-weight: bold; background: rgba(255, 107, 107, 0.2); padding: 8px; border-radius: 5px; margin: 5px 0; border: 1px solid #FF6B6B;"
elif event["type"] == "improvement":
color = "#00FF88"
icon = "✨"
style = "padding: 5px;"
else:
color = "#00AAFF"
icon = "πŸ“Š"
style = "padding: 5px;"
html += f'<div style="color: {color}; {style}">{icon} [{event["time"]}] {event["message"]}</div>'
html += '</div>'
return html
def toggle_evolution(running):
"""Start or stop evolution."""
state["running"] = running
if running:
state["iteration"] = 0
state["fitness_history"] = [0.9333]
state["variants_evaluated"] = 0
state["start_time"] = time.time()
state["events"] = [{
"time": datetime.now().strftime("%H:%M:%S"),
"type": "improvement",
"message": "πŸš€ Evolution started! Initial fitness: 0.9333 | Modal containers spinning up..."
}]
return "πŸ›‘ Stop Evolution" if running else "πŸš€ Start Evolution"
# Create Gradio interface
with gr.Blocks(
theme=gr.themes.Base(
primary_hue="purple",
secondary_hue="green",
neutral_hue="slate"
),
css="""
.gradio-container {
background: linear-gradient(135deg, #0A0A2A 0%, #1A1A3A 100%);
color: white;
}
.gr-button-primary {
background: linear-gradient(45deg, #7B3FF2, #00AAFF) !important;
border: none !important;
}
.gr-box {
background: rgba(255, 255, 255, 0.05) !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
}
"""
) as demo:
# Header with Modal branding
with gr.Row():
gr.Markdown("""
# 🌟 Evolution Aurora - AI Learning to Code
Watch as AI evolves code in real-time with neural network visualization! See synapses fire and neurons activate as the AI discovers improvements. The neural network shows the AI's "thoughts" as it learns.
""")
gr.HTML('''
<div style="text-align: right; padding: 10px;">
<div style="background: linear-gradient(45deg, #FF6B6B, #4ECDC4); padding: 10px 20px; border-radius: 25px; display: inline-block;">
<span style="color: white; font-weight: bold; font-size: 18px;">⚑ Powered by Modal</span>
</div>
<p style="color: #00AAFF; margin-top: 5px; font-size: 14px;">Cloud execution for parallel evolution</p>
</div>
''')
# Aurora effect at the top
gr.HTML(AURORA_HTML)
# Sound effects (Web Audio API)
gr.HTML('''
<script>
// Sound system for achievements and improvements
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
let soundEnabled = true;
function playSound(type) {
if (!soundEnabled) return;
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
if (type === 'achievement') {
// Achievement sound - ascending arpeggio
oscillator.frequency.setValueAtTime(523.25, audioContext.currentTime); // C5
oscillator.frequency.setValueAtTime(659.25, audioContext.currentTime + 0.1); // E5
oscillator.frequency.setValueAtTime(783.99, audioContext.currentTime + 0.2); // G5
oscillator.frequency.setValueAtTime(1046.50, audioContext.currentTime + 0.3); // C6
gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.5);
oscillator.start();
oscillator.stop(audioContext.currentTime + 0.5);
} else if (type === 'improvement') {
// Improvement sound - gentle ping
oscillator.frequency.setValueAtTime(880, audioContext.currentTime); // A5
gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);
oscillator.start();
oscillator.stop(audioContext.currentTime + 0.2);
}
}
// Watch for achievement messages
const observeAchievements = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'childList') {
const text = mutation.target.textContent || '';
if (text.includes('ACHIEVEMENT UNLOCKED')) {
playSound('achievement');
} else if (text.includes('✨') && text.includes('+0.0')) {
playSound('improvement');
}
}
});
});
// Start observing when ready
setTimeout(() => {
const eventLog = document.querySelector('[id*="event_log"]');
if (eventLog) {
observeAchievements.observe(eventLog, { childList: true, subtree: true });
}
}, 1000);
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.key === ' ' && e.target.tagName !== 'INPUT') {
e.preventDefault();
const startBtn = document.querySelector('.gr-button-primary');
if (startBtn) startBtn.click();
} else if (e.key === 's' && e.ctrlKey) {
e.preventDefault();
const shareBtn = document.querySelector('[id*="share_btn"]');
if (shareBtn) shareBtn.click();
} else if (e.key === 'm') {
soundEnabled = !soundEnabled;
console.log('Sound', soundEnabled ? 'enabled' : 'disabled');
}
});
</script>
''')
# Epic Voice Narration System
gr.HTML('''
<script>
// Text-to-speech narration
const speak = (text, rate = 1, pitch = 1) => {
if (!window.speechSynthesis) return;
const utterance = new SpeechSynthesisUtterance(text);
utterance.rate = rate;
utterance.pitch = pitch;
utterance.volume = 0.8;
// Try to use a dramatic voice
const voices = speechSynthesis.getVoices();
const dramaticVoice = voices.find(v => v.name.includes('Daniel') || v.name.includes('Alex')) || voices[0];
if (dramaticVoice) utterance.voice = dramaticVoice;
speechSynthesis.speak(utterance);
};
// Epic intro narration
setTimeout(() => {
speak("Welcome to Evolution Aurora. Where artificial intelligence learns to code before your very eyes.", 0.9, 0.8);
}, 1000);
// Watch for achievements and milestones
const narrateProgress = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
const text = mutation.target.textContent || '';
if (text.includes('ACHIEVEMENT UNLOCKED')) {
speak("Achievement unlocked!", 1.2, 1.2);
} else if (text.includes('0.95') && text.includes('Fitness')) {
speak("Incredible! 95 percent fitness achieved. The AI is learning fast.", 1, 0.9);
} else if (text.includes('0.99') && text.includes('Fitness')) {
speak("Approaching perfection! 99 percent fitness. This is extraordinary!", 1.1, 1.1);
} else if (text.includes('TOOK THE LEAD')) {
speak("Alert! Another player has taken the lead! You must evolve faster!", 1.2, 1);
}
});
});
setTimeout(() => {
const containers = document.querySelectorAll('[id*="display"], [id*="event_log"]');
containers.forEach(c => narrateProgress.observe(c, { childList: true, subtree: true }));
}, 2000);
</script>
''')
with gr.Row():
with gr.Column(scale=1):
toggle_btn = gr.Button("πŸš€ Start Evolution", variant="primary", size="lg")
# Multiplayer toggle
multiplayer_btn = gr.Button("🌍 Join Global Battle", variant="secondary", size="lg")
gr.Markdown("### πŸ“Š Statistics")
with gr.Row():
fitness_display = gr.Number(
value=0.9333,
label="Current Fitness",
precision=4
)
generation_display = gr.Number(
value=0,
label="Generation"
)
gr.Markdown("### ⚑ Modal Performance")
with gr.Row():
variants_display = gr.Number(
value=0,
label="Variants Evaluated"
)
speed_display = gr.Textbox(
value="0 variants/sec",
label="Processing Speed"
)
with gr.Column(scale=2):
gr.Markdown("### πŸ“ˆ Fitness Evolution")
fitness_chart = gr.Plot(value=create_fitness_chart())
# Multiplayer Leaderboard
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 🌍 Global Competition")
multiplayer_display = gr.HTML(value=format_multiplayer_leaderboard())
with gr.Column(scale=2):
# Code Evolution Display
gr.Markdown("### 🧬 Live Code Evolution")
code_display = gr.HTML(value=format_code_display())
# Achievements Display
gr.Markdown("### πŸ† Achievements & Leaderboard")
achievements_display = gr.HTML(value=format_achievements())
with gr.Row():
share_btn = gr.Button("πŸ“± Share Your Score", variant="secondary")
share_text = gr.Textbox(
value=get_share_text(),
label="Copy & Share:",
interactive=True,
visible=False
)
with gr.Row():
with gr.Column():
gr.Markdown("### πŸ”οΈ Fitness Landscape")
landscape_3d = gr.Plot(value=create_3d_landscape())
with gr.Column():
gr.Markdown("### πŸ“œ Evolution Log")
event_log = gr.HTML(value=format_events())
# Timer for updates
timer = gr.Timer(1.0)
# Toggle state
running_state = gr.State(False)
multiplayer_state = gr.State(False)
def on_toggle(running):
new_state = not running
return new_state, toggle_evolution(new_state)
def on_multiplayer(active):
state["multiplayer_active"] = not active
return not active, "🚫 Leave Battle" if not active else "🌍 Join Global Battle"
def on_share():
return gr.update(visible=True, value=get_share_text())
toggle_btn.click(
fn=on_toggle,
inputs=[running_state],
outputs=[running_state, toggle_btn]
)
multiplayer_btn.click(
fn=on_multiplayer,
inputs=[multiplayer_state],
outputs=[multiplayer_state, multiplayer_btn]
)
share_btn.click(
fn=on_share,
outputs=[share_text]
)
def update_all():
if state["running"]:
simulate_evolution()
# Calculate speed
speed = "0 variants/sec"
if state["start_time"] and state["variants_evaluated"] > 0:
elapsed = time.time() - state["start_time"]
if elapsed > 0:
speed = f"{state['variants_evaluated'] / elapsed:.2f} variants/sec"
return {
fitness_display: state["fitness_history"][-1] if state["fitness_history"] else 0.9333,
generation_display: state["iteration"],
variants_display: state["variants_evaluated"],
speed_display: speed,
fitness_chart: create_fitness_chart(),
landscape_3d: create_3d_landscape(),
multiplayer_display: format_multiplayer_leaderboard(),
code_display: format_code_display(),
achievements_display: format_achievements(),
event_log: format_events()
}
timer.tick(
fn=update_all,
outputs=[fitness_display, generation_display, variants_display, speed_display, fitness_chart, landscape_3d, multiplayer_display, code_display, achievements_display, event_log]
)
# Hidden boss defeat button
boss_defeat_btn = gr.Button("Boss Defeat Trigger", visible=False, elem_id="boss_defeat_btn")
def on_boss_defeat():
"""Handle boss defeat from JavaScript."""
if handle_boss_defeat():
return {}
return {}
boss_defeat_btn.click(
fn=on_boss_defeat,
outputs=[]
)
# JavaScript to handle boss defeat callback
gr.HTML('''
<script>
// Connect boss defeat callback to Gradio
window.bossDamageCallback = () => {
const btn = document.getElementById('boss_defeat_btn');
if (btn) {
btn.click();
}
};
</script>
''')
# Challenge Mode
with gr.Row():
gr.Markdown("""
### 🎯 Challenge Mode
**Today's Challenge**: Reach 99% fitness in under 10 generations!
πŸ₯‡ **Gold**: < 5 generations
πŸ₯ˆ **Silver**: < 7 generations
πŸ₯‰ **Bronze**: < 10 generations
""")
gr.HTML('''
<div style="text-align: center; padding: 20px;">
<div style="display: inline-block; background: linear-gradient(45deg, #FFD700, #FFA500); padding: 15px 30px; border-radius: 10px;">
<h3 style="margin: 0; color: #000;">πŸ… Your Best: Not Set</h3>
<p style="margin: 5px 0 0 0; color: #333;">Complete a run to set your record!</p>
</div>
</div>
''')
gr.Markdown("""
---
### πŸ† HuggingFace Agents-MCP Hackathon 2025
**Track 3**: Agentic Demo Showcase | **Integration**: Evolve Framework | **Sponsor**: Modal
This demo showcases AI-driven code evolution with real-time visualization. The aurora effects
intensify with fitness improvements, creating a stunning visual representation of machine learning.
### ⌨️ Keyboard Shortcuts
- **Space**: Start/Stop Evolution
- **Ctrl+S**: Share Your Score
- **M**: Toggle Sound Effects
### πŸ’‘ Pro Tips
- Watch for achievement unlocks - they come with special sound effects!
- The aurora intensifies with larger fitness improvements
- Modal's parallel execution evaluates 4-8 variants simultaneously
- Try to unlock all 5 achievements in a single run!
""")
if __name__ == "__main__":
print("\n🌟 Evolution Aurora - Final Demo")
print("=" * 50)
print("This version has:")
print("βœ“ Working aurora particle effects")
print("βœ“ Animated 3D fitness landscape")
print("βœ“ Real-time evolution simulation")
print("βœ“ Beautiful UI with gradients")
print("=" * 50 + "\n")
demo.launch()