Spaces:
Runtime error
Runtime error
| 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""" | |
| <div style='background: rgba(0,255,100,0.1); padding: 10px; border: 1px solid #00ff66; border-radius: 5px; color: #00ff66;'> | |
| LOGOS SYSTEM: {status} | |
| </div> | |
| """ | |
| return html | |
| with gr.Blocks(title="LOGOS Stratos") as demo: | |
| with gr.Link(rel="stylesheet", href="style.css"): pass | |
| with gr.Row(): | |
| gr.Markdown(f"# {PROTOCOL_NAME}\n**{SUBTITLE}**") | |
| with gr.Row(): | |
| status_panel = gr.HTML(fetch_manifold_diagnostics()) | |
| with gr.Tabs(): | |
| with gr.Tab("Polar Matroska (Protocol 35)"): | |
| with gr.Row(): | |
| with gr.Column(scale=3): | |
| pm_plot = gr.Plot(label="Knowledge Manifold") | |
| with gr.Column(scale=1): | |
| pm_btn = gr.Button("Build Network", variant="primary") | |
| pm_stats = gr.Textbox(label="Status") | |
| gr.Markdown("Visualize the Semantic Heat Map. Radius = Binary Entropy. Theta = Prime Sector.") | |
| def load_pm(): | |
| fig = get_polar_matroska_viz() | |
| if fig: return fig, "Network Active" | |
| return None, "Network Failed" | |
| pm_btn.click(load_pm, outputs=[pm_plot, pm_stats]) | |
| demo.load(load_pm, outputs=[pm_plot, pm_stats]) | |
| with gr.Tab("MTL Interpreter"): | |
| mtl_input = gr.Textbox(label="MTL Code", lines=3, placeholder="(recall \"structure\")") | |
| with gr.Row(): | |
| mtl_run = gr.Button("Execute", variant="primary") | |
| mtl_demo = gr.Button("Run Demo") | |
| mtl_output = gr.Textbox(label="Result", lines=5) | |
| mtl_run.click(execute_mtl, inputs=mtl_input, outputs=mtl_output) | |
| mtl_demo.click(run_mtl_demo, outputs=mtl_output) | |
| with gr.Tab("Prime Topology"): | |
| gr.Plot(value=get_prime_topology(), label="Log Polar Cone") | |
| with gr.Tab("RPC Validator"): | |
| rpc_input = gr.Textbox(label="Stream (Comma Separated Integers)", placeholder="2, 3, 5, 7, 11") | |
| rpc_btn = gr.Button("Validate Phase Signal") | |
| rpc_out = gr.Textbox(label="RPC Score") | |
| def val_rpc(txt): | |
| from logos.analysis.rpc_validator import PhaseSpaceValidator | |
| try: | |
| nums = [int(x.strip()) for x in txt.split(',') if x.strip()] | |
| score = PhaseSpaceValidator().get_rpc_score(nums) | |
| return f"RPC Score: {score:.4f}" | |
| except Exception as e: | |
| return f"Error: {e}" | |
| rpc_btn.click(val_rpc, inputs=rpc_input, outputs=rpc_out) | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", server_port=7860, css=load_css()) | |