""" 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 = """

Evolution Aurora

Watch AI Learn to Code in Real-Time

🧠 Neural Network Visualization | πŸš€ Synapses Fire with Each Improvement

""" 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 = '''

πŸ† LIVE GLOBAL LEADERBOARD

''' 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'''
{medal} {player['country']} {player['name']} {' (YOU)' if is_you else ''}
{player['fitness']:.4f}
{'
πŸ”₯ YOUR POSITION
' if is_you else ''}
''' html += '''
''' 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'''

🧬 Code Evolution

Original Code

{original}

Evolved Code (Gen {state.get("iteration", 0)})

{evolved}

✨ Improvements Applied:

''' 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 = '
' html += '

πŸ† Achievements

' html += '
' for ach_id in state["achievements"]: ach = ACHIEVEMENTS.get(ach_id, {}) html += f'''
{ach.get("name", "")}
{ach.get("desc", "")}
''' if not state["achievements"]: html += '
Start evolving to unlock achievements!
' html += '
' html += f'
High Score: {state["high_score"]:.4f}
' html += '
' 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 = '
' 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'
{icon} [{event["time"]}] {event["message"]}
' html += '
' 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('''
⚑ Powered by Modal

Cloud execution for parallel evolution

''') # Aurora effect at the top gr.HTML(AURORA_HTML) # Sound effects (Web Audio API) gr.HTML(''' ''') # Epic Voice Narration System gr.HTML(''' ''') 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(''' ''') # 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('''

πŸ… Your Best: Not Set

Complete a run to set your record!

''') 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()