import gradio as gr import numpy as np import plotly.graph_objects as go import sympy import time import os import sys from collections import Counter # Ensure logos package is importable current_dir = os.path.dirname(os.path.abspath(__file__)) if current_dir not in sys.path: sys.path.insert(0, current_dir) # --- LOGOS CORE IMPORTS --- try: from logos.mtl.interpreter import MTLInterpreter from logos.memory.prime_db import PrimeTokenDB from logos.models.polar_matroska import PolarMatroska MTL_AVAILABLE = True print("[LOGOS] MTL Interpreter & Models loaded successfully") except ImportError as e: MTL_AVAILABLE = False print(f"[LOGOS] MTL not available: {e}") try: from logos.dsp_bridge import DSPBridge from logos.logos_core import PRIME_MODULO print(f"[LOGOS] Successfully imported DSPBridge") except ImportError: DSPBridge = None PRIME_MODULO = 9973 # --- PROTOCOL 26: START NEURAL ROUTER --- import threading import subprocess def start_neural_router(): print("[SYSTEM] Igniting Neural Router (Port 5000)...") try: process = subprocess.Popen( [sys.executable, "-m", "logos.server"], env={**os.environ, "PYTHONPATH": current_dir}, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1 ) print(f"[OK] Neural Router Process ID: {process.pid}") def stream_logs(p): for line in iter(p.stdout.readline, ''): print(f"[ROUTER] {line.strip()}") threading.Thread(target=stream_logs, args=(process,), daemon=True).start() except Exception as e: print(f"[X] Failed to start Neural Router: {e}") threading.Thread(target=start_neural_router, daemon=True).start() # --- THEME LOADING --- def load_css(): try: with open(os.path.join(current_dir, "style.css"), "r") as f: return f.read() except: return "" # --- MTL INTERPRETER INTERFACE --- def execute_mtl(code: str) -> str: """Execute MTL code and return result.""" if not MTL_AVAILABLE: return "MTL Interpreter not available in this environment" try: interpreter = MTLInterpreter() result = interpreter.execute(code) return f"Result: {result}" except Exception as e: return f"Error: {str(e)}" def run_mtl_demo() -> str: """Run a demonstration of MTL capabilities.""" if not MTL_AVAILABLE: return "MTL not available" try: mtl = MTLInterpreter() output = [] output.append("=== LOGOS MTL DEMONSTRATION ===\n") output.append("[1] Tensor Multiplication") r = mtl.execute('(mult [2] [3])') output.append(f" (mult [2] [3]) = {r} (MECHANISM x RESULT = FLIP)") output.append("\n[2] Logic Gates") r = mtl.execute('(or [2] [3])') output.append(f" (or [2] [3]) = {r} (LCM - Superposition)") r = mtl.execute('(and [6] [10])') output.append(f" (and [6] [10]) = {r} (GCD - Intersection)") output.append("\n[3] Recursive Function (Factorial)") mtl.execute('(defun factorial (n) (if (lt? n 2) 1 (mult n (factorial (sub n 1)))))') r = mtl.execute('(factorial 5)') output.append(f" (factorial 5) = {r}") output.append("\n[4] Knowledge Graph (Synapse)") r = mtl.execute('(relate [17] [19])') output.append(f" (relate [17] [19]) = {r} (IMAGE x TEXT x RELATE)") output.append("\n=== TURING COMPLETENESS VERIFIED ===") return "\n".join(output) except Exception as e: return f"Demo Error: {str(e)}" # --- PHYSICS VISUALIZERS --- def get_prime_topology(max_n=500): """LOGOS Concentric Log Polar Cone Topology.""" import math fig = go.Figure() all_nums = list(range(1, max_n)) residue_colors = { 1: '#00ffea', 3: '#ff00ff', 7: '#ffff00', 9: '#00ff00', 0: '#333333', 2: '#333333', 4: '#333333', 6: '#333333', 8: '#333333' } for residue in [1, 3, 7, 9]: nums = [n for n in all_nums if n % 10 == residue] r = [math.log10(n) if n > 0 else 0 for n in nums] theta = [(n % 100) * 3.6 for n in nums] is_prime = [sympy.isprime(n) for n in nums] sizes = [12 if p else 4 for p in is_prime] colors = [residue_colors[residue] if p else '#555555' for p in is_prime] fig.add_trace(go.Scatterpolar( r=r, theta=theta, mode='markers', marker=dict(size=sizes, color=colors, line=dict(color='white', width=0.3), opacity=0.8), text=[f"{n} (mod10={residue})" for n in nums], hoverinfo='text', name=f'Mod {residue}' )) fig.update_layout( template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', showlegend=True, legend=dict(font=dict(color='white')), polar=dict(radialaxis=dict(visible=True, range=[0, 3], tickvals=[0, 1, 2, 3], ticktext=['1', '10', '100', '1000']), angularaxis=dict(visible=True), bgcolor='rgba(11,15,25,0.9)'), margin=dict(l=40, r=40, t=40, b=40), height=550, title=dict(text="LOGOS Log Polar Cone", font=dict(color='white')) ) return fig def get_polar_matroska_viz(): """Visualizes the Active Knowledge Base (Protocol 35).""" if not MTL_AVAILABLE: return None try: pm = PolarMatroska() success = pm.load_knowledge() if not success: return None return pm.visualize() except Exception as e: print(f"PM Viz Error: {e}") return None # --- UI --- PROTOCOL_NAME = "LOGOS v2.0 (Stratos)" SUBTITLE = "Protocol 35-44: Matroska + Semantics + Cortex + RPC" def fetch_manifold_diagnostics(): """Polls diagnostic state.""" status = "ONLINE" if MTL_AVAILABLE else "DEGRADED" html = f"""