File size: 9,056 Bytes
ac73ca8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import gradio as gr
import numpy as np
import plotly.graph_objects as go
import sympy
import cv2
import time
import os
import sys
from collections import Counter
from PIL import Image

# Ensure logos package is importable
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
if parent_dir not in sys.path:
    sys.path.append(parent_dir)

try:
    from logos.dsp_bridge import DSPBridge
    from logos.logos_core import PRIME_MODULO
except ImportError as e:
    print(f"Error importing LOGOS components: {e}")
    DSPBridge = None
    PRIME_MODULO = 9973

# ==========================================
# PRIME VISUALIZATION (From User Snippet)
# ==========================================

def get_gpf(n):
    """Returns the Greatest Prime Factor."""
    if n <= 1: return 1
    i = 2
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
    return n

def visualize_potentiality_flow():
    """
    Tab 1: Directed Graph (Sankey) showing Digit Constraints.
    """
    labels = ["Integer Stream"] + [f"Ends in {i}" for i in range(10)] + ["Composite Sink", "Prime Potential (P_n)"]
    sources, targets, values, colors = [], [], [], []

    # Layer 1: Stream -> Digits
    for i in range(10):
        sources.append(0); targets.append(i+1); values.append(10); colors.append("#444")

    # Layer 2: Digits -> Destination
    prime_lanes = [1, 3, 7, 9]
    for i in range(10):
        sources.append(i+1)
        if i in prime_lanes:
            targets.append(12) # Prime Potential
            colors.append("#00ffea") # Cyan
        else:
            targets.append(11) # Sink
            colors.append("#ff0055") # Red
        values.append(10)

    fig = go.Figure(data=[go.Sankey(
        node=dict(pad=15, thickness=20, line=dict(color="black", width=0.5), label=labels, color=["white"]+["#333"]*10+["#ff0055", "#00ffea"]),
        link=dict(source=sources, target=targets, value=values, color=colors)
    )])
    fig.update_layout(title="Prime Potentiality Flow (Mod 10 Constraints)", template="plotly_dark", height=600)
    return fig

def visualize_prime_network(max_integer, show_links):
    """
    Tab 2: Radial Topology.
    """
    fig = go.Figure()
    positions, gpf_map, prime_counts = {}, {}, Counter()

    for n in range(1, max_integer + 1):
        angle = np.pi/2 - (2 * np.pi * (n % 10)) / 10 # Clockwise from Top
        radius = n 
        positions[n] = (radius * np.cos(angle), radius * np.sin(angle))

        if n > 1 and not sympy.isprime(n):
            gpf = get_gpf(n)
            gpf_map[n] = gpf
            prime_counts[gpf] += 1

    if show_links:
        edge_x, edge_y = [], []
        for n, base in gpf_map.items():
            if base in positions:
                x0, y0 = positions[n]
                x1, y1 = positions[base]
                edge_x.extend([x0, x1, None])
                edge_y.extend([y0, y1, None])
        fig.add_trace(go.Scatter(x=edge_x, y=edge_y, mode='lines', line=dict(color='rgba(100,100,100,0.15)', width=0.5), hoverinfo='none', name='GPF Gravity'))

    # Draw Nodes
    px, py, ps, pt = [], [], [], []
    cx, cy, ct = [], [], []

    for n in range(1, max_integer + 1):
        x, y = positions[n]
        if sympy.isprime(n) or n == 1:
            px.append(x); py.append(y)
            ps.append(5 + (np.log(prime_counts[n]+1)*6))
            pt.append(f"PRIME: {n}<br>Gravity: {prime_counts[n]}")
        else:
            cx.append(x); cy.append(y)
            ct.append(f"Composite: {n}")

    fig.add_trace(go.Scatter(x=cx, y=cy, mode='markers', marker=dict(size=3, color='#ff0055', opacity=0.5), text=ct, hoverinfo='text', name='Composites'))
    fig.add_trace(go.Scatter(x=px, y=py, mode='markers', marker=dict(size=ps, color='#00ffea', line=dict(width=1, color='white')), text=pt, hoverinfo='text', name='Primes'))

    # Spokes
    for i in range(10):
        angle = np.pi/2 - (2 * np.pi * i) / 10
        fig.add_trace(go.Scatter(x=[0, max_integer*1.1*np.cos(angle)], y=[0, max_integer*1.1*np.sin(angle)], mode='lines', line=dict(color='#222', width=1, dash='dot'), showlegend=False))

    fig.update_layout(title=f"Radial Prime-Indexed Topology", template="plotly_dark", height=800, width=800, xaxis=dict(visible=False), yaxis=dict(visible=False))
    return fig

def visualize_gpf_counts(sequence_length):
    """
    Tab 3: GPF Density (The Orange Graph).
    """
    gpf_counts = Counter()
    for n in range(4, sequence_length):
        if not sympy.isprime(n): gpf_counts[get_gpf(n)] += 1

    sorted_gpfs = sorted(gpf_counts.keys())
    counts = [gpf_counts[p] for p in sorted_gpfs]

    fig = go.Figure(data=go.Bar(x=sorted_gpfs, y=counts, marker_color='#ff7f00', name="Composite Count"))
    fig.update_layout(title="Composite Density by GPF Base", xaxis_title="Prime Base", yaxis_title="Count", template="plotly_dark", xaxis=dict(type='category'))
    return fig

# ==========================================
# LOGOS MACHINE SHOP
# ==========================================

def process_dsp(image, grid_size=8, workers=16):
    """
    Process image through LOGOS SPCW DSP Bridge.
    """
    if image is None:
        return None, "No Image Provided"
    
    if DSPBridge is None:
        return None, "LOGOS Components Not Loaded"
        
    # Save temp file
    temp_path = "temp_ingest.png"
    if isinstance(image, np.ndarray):
        img_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
        cv2.imwrite(temp_path, img_bgr)
    elif isinstance(image, str):
        temp_path = image
    else:
        # PIL Image
        try:
            image.save(temp_path)
        except Exception:
            # Maybe numpy conversion needed
            np_img = np.array(image)
            cv2.imwrite(temp_path, cv2.cvtColor(np_img, cv2.COLOR_RGB2BGR))

    # Init Bridge
    bridge = DSPBridge(num_workers=int(workers), viewport_size=(1024, 768))
    
    try:
        # Transmit (Encoding -> Decoding)
        stats = bridge.transmit(temp_path, show_window=False)
        
        # Get result
        recon = bridge.get_canvas()
        if recon is not None:
            # Convert to PIL
            output_img = Image.fromarray(recon)
        else:
            output_img = None
            
        # Format stats
        status = f"""
        ### LOGOS SPCW TRANSMISSION REPORT
        - **State**: CRYSTALLINE
        - **Mod**: {PRIME_MODULO}
        - **Waves**: {stats.total_tiles} ({stats.parallel_waves} parallel)
        - **Atoms**: {stats.atoms_sent}
        - **Throughput**: {stats.throughput_mbps:.2f} MB/s
        - **Latency**: {stats.elapsed_ms:.1f} ms
        - **SSIM**: {stats.ssim:.6f}
        """
        
        return output_img, status
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return None, f"ERROR: {str(e)}"

# ==========================================
# APP LAYOUT
# ==========================================

with gr.Blocks(theme=gr.themes.Monochrome(), title="LOGOS SPCW Protocol") as demo:
    gr.Markdown("# LOGOS: Structured Prime Composite Waveform (SPCW)")
    gr.Markdown("_\"The Machine Shop\" - Research & Development Lab_")
    
    with gr.Tabs():
        with gr.Tab("Prime Network Visualizer"):
            gr.Markdown("## Layer 1: Mathematical Blueprints")
            with gr.Row():
                with gr.Column(scale=1):
                    max_int = gr.Slider(50, 5000, value=1000, label="Max Integer", step=50)
                    show_links = gr.Checkbox(True, label="Show Gravity Links (GPF)")
                    btn_viz = gr.Button("Generate Network", variant="primary")
                with gr.Column(scale=2):
                    plot_radial = gr.Plot(label="Radial Topology")
            
            with gr.Row():
                with gr.Column():
                    plot_flow = gr.Plot(label="Potentiality Flow")
                with gr.Column():
                    plot_counts = gr.Plot(label="Composite Density")
            
            btn_viz.click(visualize_prime_network, [max_int, show_links], plot_radial)
            btn_viz.click(visualize_potentiality_flow, None, plot_flow)
            btn_viz.click(visualize_gpf_counts, [max_int], plot_counts)

        with gr.Tab("The Machine Shop (DSP Bridge)"):
            gr.Markdown("## Layer 3: SPCW Transmission Engine")
            with gr.Row():
                with gr.Column():
                    input_img = gr.Image(type="numpy", label="Input Reality (The Cake)")
                    workers = gr.Slider(1, 64, value=16, label="Parallel Workers", step=1)
                    btn_proc = gr.Button("Bake & Eat (Transmit)", variant="primary")
                with gr.Column():
                    output_img = gr.Image(type="pil", label="Reconstructed Hologram")
                    output_stats = gr.Markdown("Waiting for transmission...")
            
            btn_proc.click(process_dsp, [input_img, workers], [output_img, output_stats])

if __name__ == "__main__":
    demo.launch()