File size: 8,701 Bytes
d76b5df
 
f9d91e8
 
7d38f33
ac73ca8
 
7d38f33
ac73ca8
7d38f33
ac73ca8
04f7887
 
ac73ca8
7d38f33
6d3aa82
 
7d38f33
 
6d3aa82
7d38f33
 
 
 
 
 
 
 
 
27905ae
7d38f33
 
6d3aa82
7d38f33
 
 
4a8c46f
66b508d
7d38f33
66b508d
7d38f33
 
37a07d6
7d38f33
 
 
 
37a07d6
7d38f33
 
 
 
 
 
 
 
 
 
66b508d
 
 
7d38f33
 
6d3aa82
7d38f33
 
27905ae
7d38f33
4a8c46f
7d38f33
 
 
 
 
aeb7110
7d38f33
 
 
 
 
 
 
f3ae05d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d38f33
f3ae05d
 
 
 
7d38f33
 
f3ae05d
7d38f33
 
 
 
 
f3ae05d
 
 
7d38f33
 
 
f3ae05d
 
 
7d38f33
 
 
 
 
f3ae05d
 
 
7d38f33
 
 
 
 
 
 
 
 
 
 
76c263c
7d38f33
 
 
d77237a
7d38f33
 
 
 
 
 
ad814f5
7d38f33
 
 
 
 
 
 
ad814f5
7d38f33
 
 
ac73ca8
7d38f33
ac73ca8
7d38f33
 
f3ae05d
7d38f33
 
 
f3ae05d
7d38f33
 
 
 
 
 
 
 
 
 
f3ae05d
7d38f33
 
 
 
 
 
f3ae05d
7d38f33
4a8c46f
7d38f33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e213a1
1c69af1
7d38f33
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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())