ANXLOG commited on
Commit
f9d91e8
·
verified ·
1 Parent(s): 976575e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +222 -76
app.py CHANGED
@@ -1,63 +1,200 @@
1
  import gradio as gr
2
  import numpy as np
 
 
3
  import cv2
4
  import time
5
- import sys
6
- import os
7
 
8
- # --- SSIM CALCULATION (Signal Fidelity) ---
9
- def calculate_ssim(img1, img2):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  """
11
- Calculates Structural Similarity Index (SSIM).
12
- 1.0 = Perfect Copy. <0.8 = Noticeable Degradation.
 
 
13
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  C1 = (0.01 * 255)**2
15
  C2 = (0.03 * 255)**2
16
-
17
  img1 = img1.astype(np.float64)
18
  img2 = img2.astype(np.float64)
19
-
20
  kernel = cv2.getGaussianKernel(11, 1.5)
21
  window = np.outer(kernel, kernel.transpose())
22
-
23
  mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5]
24
  mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]
25
-
26
  mu1_sq = mu1**2
27
  mu2_sq = mu2**2
28
  mu1_mu2 = mu1 * mu2
29
-
30
  sigma1_sq = cv2.filter2D(img1**2, -1, window)[5:-5, 5:-5] - mu1_sq
31
  sigma2_sq = cv2.filter2D(img2**2, -1, window)[5:-5, 5:-5] - mu2_sq
32
  sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2
33
-
34
  ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
35
  return ssim_map.mean()
36
 
37
- # --- THE LOGOS ENGINE (In-Memory Implementation) ---
38
- def run_logos_pipeline(image, heat_tolerance, noise_level, use_checksum):
39
  """
40
- Simulates the Full DSP Pipeline:
41
- Source -> Noise -> Bake (Encode) -> Transmit -> Eat (Decode) -> SSIM Check
42
  """
43
  if image is None: return None, None, "No Signal"
44
 
45
- # 1. PRE-PROCESS & NOISE INJECTION
46
  if len(image.shape) == 3:
47
  gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
48
  else:
49
  gray = image
50
-
51
  h, w = gray.shape
52
 
53
- # Add Gaussian Noise (Simulate Interference)
54
  if noise_level > 0:
55
- noise = np.random.normal(0, noise_level * 25, gray.shape).astype(np.int16)
56
  noisy_signal = np.clip(gray + noise, 0, 255).astype(np.uint8)
57
  else:
58
  noisy_signal = gray.copy()
59
 
60
- # 2. BAKE (Encoding) - Adaptive Quadtree
61
  start_time = time.time()
62
  atoms = []
63
 
@@ -65,16 +202,10 @@ def run_logos_pipeline(image, heat_tolerance, noise_level, use_checksum):
65
  region = noisy_signal[y:y+h, x:x+w]
66
  if region.size == 0: return
67
 
68
- # Heat Calculation (Variance)
69
  heat = np.std(region)
70
 
71
- # Harmonic Checksum Logic (Simulated)
72
- # If enabled, we use Prime Resonance to 'smooth' high-frequency noise
73
- if use_checksum and heat < (heat_tolerance * 150):
74
- # Force Persistence if "Harmonically Stable" even if noisy
75
- heat = 0
76
-
77
- # Decision: Split or Persist
78
  if heat > (heat_tolerance * 100) and w > 4:
79
  hw, hh = w // 2, h // 2
80
  recursive_bake(x, y, hw, hh)
@@ -82,72 +213,87 @@ def run_logos_pipeline(image, heat_tolerance, noise_level, use_checksum):
82
  recursive_bake(x, y+hh, hw, h-hh)
83
  recursive_bake(x+hw, y+hh, w-hw, h-hh)
84
  else:
85
- # ENCODE ATOM (Persistence State)
86
  avg_val = int(np.mean(region))
87
  atoms.append((x, y, w, h, avg_val))
88
 
89
  recursive_bake(0, 0, w, h)
90
- encode_time = time.time() - start_time
91
 
92
- # 3. EAT (Reconstruction)
93
  reconstructed = np.zeros_like(gray)
94
  heatmap_vis = np.zeros((h, w, 3), dtype=np.uint8)
95
 
96
  for (x, y, cw, ch, val) in atoms:
97
  reconstructed[y:y+ch, x:x+cw] = val
98
-
99
- # Visualize Heat Map (Red=Small/Hot, Cyan=Large/Cool)
100
- is_hot = cw < 8
101
  color = (255, 0, 85) if is_hot else (0, 255, 234)
102
  cv2.rectangle(heatmap_vis, (x, y), (x+cw, y+ch), color, 1)
103
 
104
- # 4. ANALYTICS (DSP Stats)
105
- ssim_score = calculate_ssim(gray, reconstructed)
106
- compression_ratio = 100 * (1 - (len(atoms) * 512) / (w * h)) # approx atom size
107
 
108
  stats = (
109
- f"--- DSP TELEMETRY ---\n"
110
- f"Stream Latency: {encode_time*1000:.1f} ms\n"
111
- f"Atom Count: {len(atoms)}\n"
112
- f"Compression: {compression_ratio:.1f}%\n"
113
- f"Signal Fidelity (SSIM): {ssim_score:.4f} / 1.0\n"
114
- f"Status: {'CRITICAL' if ssim_score < 0.8 else 'STABLE'}"
 
115
  )
116
 
117
- # Visual Output: Left=Reconstructed, Right=Heatmap Overlay
118
- final_output = cv2.cvtColor(reconstructed, cv2.COLOR_GRAY2RGB)
119
-
120
- return final_output, heatmap_vis, stats
121
 
122
- # --- THE INTERFACE ---
123
- with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
124
- gr.Markdown("# LOGOS: DSP Fidelity & Harmonic Checksum Lab")
125
- gr.Markdown("Test the **SPCW Phase Determinism** against signal noise. Verify SSIM and Transmission Speed.")
126
-
127
- with gr.Row():
128
- with gr.Column(scale=1):
129
- inp_img = gr.Image(label="Input Signal (Source)", type="numpy", height=300)
130
-
131
- with gr.Group():
132
- gr.Markdown("### DSP Parameters")
133
- tol_slider = gr.Slider(0.01, 1.0, value=0.1, label="Heat Tolerance (Persistence)")
134
- noise_slider = gr.Slider(0.0, 5.0, value=0.0, label="Signal Noise (Interference)")
135
- check_toggle = gr.Checkbox(label="Enable Harmonic Checksum (Prime Correction)", value=False)
136
-
137
- btn_run = gr.Button("TRANSMIT STREAM", variant="primary")
138
- stats_box = gr.Textbox(label="Telemetry", lines=6)
 
 
139
 
140
- with gr.Column(scale=2):
141
- with gr.Tab("Reconstructed Reality"):
142
- out_img = gr.Image(label="Decoded Signal", type="numpy")
143
- with gr.Tab("Heatmap (Phase Delta)"):
144
- heat_img = gr.Image(label="Variable Chunking Visualization", type="numpy")
145
-
146
- btn_run.click(
147
- run_logos_pipeline,
148
- inputs=[inp_img, tol_slider, noise_slider, check_toggle],
149
- outputs=[out_img, heat_img, stats_box]
150
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
  if __name__ == "__main__":
 
153
  demo.launch(ssr_mode=False)
 
1
  import gradio as gr
2
  import numpy as np
3
+ import plotly.graph_objects as go
4
+ import sympy
5
  import cv2
6
  import time
7
+ from collections import Counter
 
8
 
9
+ # ==========================================
10
+ # PART 1: MATHEMATICAL PRIMITIVES (THEORY)
11
+ # ==========================================
12
+
13
+ def get_gpf(n):
14
+ """Returns the Greatest Prime Factor of n."""
15
+ if n <= 1: return 1
16
+ i = 2
17
+ gpf = 1
18
+ while i * i <= n:
19
+ if n % i:
20
+ i += 1
21
+ else:
22
+ n //= i
23
+ gpf = i
24
+ if n > 1:
25
+ gpf = n
26
+ return gpf
27
+
28
+ def visualize_prime_network(max_integer, show_links):
29
  """
30
+ Visualizes the Radial Prime Topology.
31
+ - Nodes: Integers.
32
+ - Layout: Radial Mod 10 (Clockwise from Top).
33
+ - Connections: Composites tethered to their GPF Base.
34
  """
35
+ fig = go.Figure()
36
+
37
+ positions = {}
38
+ gpf_map = {}
39
+ prime_children_count = Counter()
40
+
41
+ # 1. Calculate Positions (Mod 10 Dial)
42
+ for n in range(1, max_integer + 1):
43
+ # 0 at Top (pi/2), Clockwise rotation
44
+ angle = np.pi/2 - (2 * np.pi * (n % 10)) / 10
45
+ radius = n
46
+ x = radius * np.cos(angle)
47
+ y = radius * np.sin(angle)
48
+ positions[n] = (x, y)
49
+
50
+ if n > 1:
51
+ if not sympy.isprime(n):
52
+ gpf = get_gpf(n)
53
+ gpf_map[n] = gpf
54
+ prime_children_count[gpf] += 1
55
+
56
+ # 2. Draw Connectivity (The Tessellation)
57
+ if show_links:
58
+ edge_x, edge_y = [], []
59
+ for n, base in gpf_map.items():
60
+ if base in positions:
61
+ x0, y0 = positions[n]
62
+ x1, y1 = positions[base]
63
+ edge_x.extend([x0, x1, None])
64
+ edge_y.extend([y0, y1, None])
65
+
66
+ fig.add_trace(go.Scatter(
67
+ x=edge_x, y=edge_y,
68
+ mode='lines',
69
+ line=dict(color='rgba(100, 100, 100, 0.15)', width=0.5),
70
+ hoverinfo='none',
71
+ name='GPF Gravity'
72
+ ))
73
+
74
+ # 3. Draw Nodes
75
+ prime_x, prime_y, prime_size, prime_text = [], [], [], []
76
+ comp_x, comp_y, comp_text = [], [], []
77
+
78
+ for n in range(1, max_integer + 1):
79
+ x, y = positions[n]
80
+ if sympy.isprime(n) or n == 1:
81
+ prime_x.append(x)
82
+ prime_y.append(y)
83
+ weight = prime_children_count[n]
84
+ # Logarithmic sizing based on "Gravity" (number of composites anchored)
85
+ size = 5 + (np.log(weight + 1) * 6)
86
+ prime_size.append(size)
87
+ prime_text.append(f"<b>PRIME: {n}</b><br>Gravity: {weight}")
88
+ else:
89
+ comp_x.append(x)
90
+ comp_y.append(y)
91
+ comp_text.append(f"Composite: {n}<br>Base: {gpf_map.get(n)}")
92
+
93
+ fig.add_trace(go.Scatter(
94
+ x=comp_x, y=comp_y,
95
+ mode='markers',
96
+ marker=dict(size=3, color='#ff0055', opacity=0.5), # Red dust
97
+ text=comp_text, hoverinfo='text', name='Composites'
98
+ ))
99
+
100
+ fig.add_trace(go.Scatter(
101
+ x=prime_x, y=prime_y,
102
+ mode='markers',
103
+ marker=dict(size=prime_size, color='#00ffea', line=dict(width=1, color='white')), # Cyan anchors
104
+ text=prime_text, hoverinfo='text', name='Primes'
105
+ ))
106
+
107
+ # 4. Draw Radial Spokes
108
+ for i in range(10):
109
+ angle = np.pi/2 - (2 * np.pi * i) / 10
110
+ fig.add_trace(go.Scatter(
111
+ x=[0, max_integer * 1.1 * np.cos(angle)],
112
+ y=[0, max_integer * 1.1 * np.sin(angle)],
113
+ mode='lines',
114
+ line=dict(color='#333', width=1, dash='dot'),
115
+ showlegend=False
116
+ ))
117
+
118
+ fig.update_layout(
119
+ title=f"Radial Prime-Indexed Topology (Max: {max_integer})",
120
+ template="plotly_dark",
121
+ xaxis=dict(showgrid=False, zeroline=False, visible=False),
122
+ yaxis=dict(showgrid=False, zeroline=False, visible=False),
123
+ width=800, height=800,
124
+ showlegend=True
125
+ )
126
+ return fig
127
+
128
+ def visualize_gpf_counts(sequence_length):
129
+ """Visualizes the 'Heat' generated by each Prime Base."""
130
+ gpf_counts = Counter()
131
+ for n in range(4, sequence_length):
132
+ if not sympy.isprime(n):
133
+ gpf = get_gpf(n)
134
+ gpf_counts[gpf] += 1
135
+
136
+ sorted_gpfs = sorted(gpf_counts.keys())
137
+ counts = [gpf_counts[p] for p in sorted_gpfs]
138
+
139
+ fig = go.Figure(data=go.Bar(
140
+ x=sorted_gpfs, y=counts,
141
+ marker_color='#ff7f00', # LOGOS Orange
142
+ name="Composite Count"
143
+ ))
144
+
145
+ fig.update_layout(
146
+ title="Composite Density by Greatest Prime Factor (GPF)",
147
+ xaxis_title="Prime Base (P)",
148
+ yaxis_title="Composites Anchored",
149
+ template="plotly_dark",
150
+ xaxis=dict(type='category')
151
+ )
152
+ return fig
153
+
154
+ # ==========================================
155
+ # PART 2: DSP ENGINE (PRACTICE)
156
+ # ==========================================
157
+
158
+ def calculate_ssim(img1, img2):
159
+ """Calculates Structural Similarity Index (1.0 = Perfect)."""
160
  C1 = (0.01 * 255)**2
161
  C2 = (0.03 * 255)**2
 
162
  img1 = img1.astype(np.float64)
163
  img2 = img2.astype(np.float64)
 
164
  kernel = cv2.getGaussianKernel(11, 1.5)
165
  window = np.outer(kernel, kernel.transpose())
 
166
  mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5]
167
  mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]
 
168
  mu1_sq = mu1**2
169
  mu2_sq = mu2**2
170
  mu1_mu2 = mu1 * mu2
 
171
  sigma1_sq = cv2.filter2D(img1**2, -1, window)[5:-5, 5:-5] - mu1_sq
172
  sigma2_sq = cv2.filter2D(img2**2, -1, window)[5:-5, 5:-5] - mu2_sq
173
  sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2
 
174
  ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
175
  return ssim_map.mean()
176
 
177
+ def run_logos_pipeline(image, heat_tolerance, noise_level):
 
178
  """
179
+ Runs the Real DSP Pipeline: Source -> Noise -> SPCW Encode -> Decode -> SSIM
 
180
  """
181
  if image is None: return None, None, "No Signal"
182
 
183
+ # 1. Pre-process
184
  if len(image.shape) == 3:
185
  gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
186
  else:
187
  gray = image
 
188
  h, w = gray.shape
189
 
190
+ # 2. Noise Injection (Simulate Transmission Interference)
191
  if noise_level > 0:
192
+ noise = np.random.normal(0, noise_level * 20, gray.shape).astype(np.int16)
193
  noisy_signal = np.clip(gray + noise, 0, 255).astype(np.uint8)
194
  else:
195
  noisy_signal = gray.copy()
196
 
197
+ # 3. THE BAKER (Adaptive Quadtree Decomposition)
198
  start_time = time.time()
199
  atoms = []
200
 
 
202
  region = noisy_signal[y:y+h, x:x+w]
203
  if region.size == 0: return
204
 
205
+ # Heat = Variance of the signal
206
  heat = np.std(region)
207
 
208
+ # Split Decision (The SPCW Phase Logic)
 
 
 
 
 
 
209
  if heat > (heat_tolerance * 100) and w > 4:
210
  hw, hh = w // 2, h // 2
211
  recursive_bake(x, y, hw, hh)
 
213
  recursive_bake(x, y+hh, hw, h-hh)
214
  recursive_bake(x+hw, y+hh, w-hw, h-hh)
215
  else:
216
+ # Persistence State (00)
217
  avg_val = int(np.mean(region))
218
  atoms.append((x, y, w, h, avg_val))
219
 
220
  recursive_bake(0, 0, w, h)
221
+ latency = (time.time() - start_time) * 1000 # ms
222
 
223
+ # 4. THE PLAYER (Reconstruction)
224
  reconstructed = np.zeros_like(gray)
225
  heatmap_vis = np.zeros((h, w, 3), dtype=np.uint8)
226
 
227
  for (x, y, cw, ch, val) in atoms:
228
  reconstructed[y:y+ch, x:x+cw] = val
229
+ # Visualization: Small=Hot(Red), Large=Cold(Cyan)
230
+ is_hot = cw < 16
 
231
  color = (255, 0, 85) if is_hot else (0, 255, 234)
232
  cv2.rectangle(heatmap_vis, (x, y), (x+cw, y+ch), color, 1)
233
 
234
+ # 5. Telemetry
235
+ ssim = calculate_ssim(gray, reconstructed)
236
+ comp_ratio = 100 * (1 - (len(atoms) * 5) / (w * h)) # approx
237
 
238
  stats = (
239
+ f"DSP TELEMETRY\n"
240
+ f"-------------\n"
241
+ f"Latency: {latency:.1f} ms\n"
242
+ f"Atoms: {len(atoms)}\n"
243
+ f"Compression: ~{comp_ratio:.1f}%\n"
244
+ f"SSIM (Fidelity): {ssim:.4f}\n"
245
+ f"Noise Floor: {noise_level}"
246
  )
247
 
248
+ return cv2.cvtColor(reconstructed, cv2.COLOR_GRAY2RGB), heatmap_vis, stats
 
 
 
249
 
250
+ # ==========================================
251
+ # PART 3: THE INTERFACE
252
+ # ==========================================
253
+
254
+ def build_demo():
255
+ with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
256
+ gr.Markdown("# LOGOS: Systems Architecture Suite")
257
+ gr.Markdown("Validating **Post-Binary Logic**, **Prime Topology**, and **DSP Signal Integrity**.")
258
+
259
+ with gr.Tabs():
260
+ # TAB 1: THE THEORY (Visuals)
261
+ with gr.Tab("1. Radial Prime Topology"):
262
+ gr.Markdown("The **Natural Tessellation** of the number line. Composites are anchored to their Greatest Prime Factor (GPF).")
263
+ with gr.Row():
264
+ rad_len = gr.Slider(100, 2000, value=500, label="Integer Range")
265
+ link_toggle = gr.Checkbox(value=True, label="Show Connectivity (Gravity)")
266
+ net_plot = gr.Plot(label="Radial View")
267
+ btn_net = gr.Button("Build Network")
268
+ btn_net.click(visualize_prime_network, inputs=[rad_len, link_toggle], outputs=net_plot)
269
 
270
+ # TAB 2: DENSITY ANALYSIS
271
+ with gr.Tab("2. GPF Density"):
272
+ gr.Markdown("Analyzing the 'Heat' generated by each Prime Base.")
273
+ gpf_len = gr.Slider(100, 10000, value=2500, label="Stream Depth")
274
+ gpf_plot = gr.Plot(label="GPF Distribution")
275
+ btn_gpf = gr.Button("Calculate Density")
276
+ btn_gpf.click(visualize_gpf_counts, inputs=[gpf_len], outputs=gpf_plot)
277
+
278
+ # TAB 3: THE LAB (Real Engine)
279
+ with gr.Tab("3. DSP Fidelity Lab"):
280
+ gr.Markdown("Test the **SPCW Engine** on real signals. Inject noise, adjust heat tolerance, and measure SSIM.")
281
+ with gr.Row():
282
+ with gr.Column():
283
+ inp = gr.Image(label="Source Signal", type="numpy", height=250)
284
+ tol = gr.Slider(0.01, 0.5, value=0.1, label="Heat Tolerance (Persistence)")
285
+ noise = gr.Slider(0.0, 5.0, value=0.0, label="Noise Injection (Interference)")
286
+ btn_run = gr.Button("TRANSMIT STREAM", variant="primary")
287
+ out_stats = gr.Textbox(label="Telemetry", lines=5)
288
+
289
+ with gr.Column():
290
+ out_img = gr.Image(label="Reconstructed Signal")
291
+ out_heat = gr.Image(label="Phase Map (Red=Change, Cyan=Persist)")
292
+
293
+ btn_run.click(run_logos_pipeline, inputs=[inp, tol, noise], outputs=[out_img, out_heat, out_stats])
294
+
295
+ return demo
296
 
297
  if __name__ == "__main__":
298
+ demo = build_demo()
299
  demo.launch(ssr_mode=False)