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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -59
app.py CHANGED
@@ -1,31 +1,48 @@
1
  import gradio as gr
2
  import numpy as np
3
  import cv2
 
4
  import sys
5
  import os
6
 
7
- # --- INTEGRATION: Import your actual LOGOS modules ---
8
- # We add the current directory to path so we can import the uploaded files
9
- sys.path.append(os.path.dirname(__file__))
10
-
11
- try:
12
- import logos_core
13
- from bake_stream import tile_to_quadtree_path
14
- from fractal_engine import LogosFractalEngine
15
- # If you have a specific class in bake_stream, import it here.
16
- # For now, I will use your logic patterns based on the files provided.
17
- except ImportError as e:
18
- print(f"⚠️ LOGOS MODULE MISSING: {e}")
19
- print("Ensure logos_core.py, bake_stream.py, and fractal_engine.py are uploaded!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- # --- MODULE 1: THE REAL BAKER (Using your Quadtree Logic) ---
22
- def run_logos_baker(image, tolerance):
23
  """
24
- Wraps your actual 'bake_stream.py' logic.
 
25
  """
26
- if image is None: return None
27
 
28
- # 1. Prepare Image (Grayscale for Heat Analysis)
29
  if len(image.shape) == 3:
30
  gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
31
  else:
@@ -33,73 +50,104 @@ def run_logos_baker(image, tolerance):
33
 
34
  h, w = gray.shape
35
 
36
- # 2. Simulate the Baker's Heat Analysis
37
- # We use the Adaptive Quadtree logic found in your files
38
- chunks = []
 
 
 
 
 
 
 
39
 
40
- # Simple recursive implementation of your architecture
41
  def recursive_bake(x, y, w, h):
42
- region = gray[y:y+h, x:x+w]
43
  if region.size == 0: return
44
 
45
- # Calculate Heat (Variance)
46
  heat = np.std(region)
47
 
48
- # Threshold check (Your "Heat Tolerance")
49
- # Scaled to 0-100 matches your 'tolerance' slider
50
- if heat > (tolerance * 100) and w > 4: # Atomic limit
 
 
 
 
 
51
  hw, hh = w // 2, h // 2
52
  recursive_bake(x, y, hw, hh)
53
  recursive_bake(x+hw, y, w-hw, hh)
54
  recursive_bake(x, y+hh, hw, h-hh)
55
  recursive_bake(x+hw, y+hh, w-hw, h-hh)
56
  else:
57
- # PERSIST STATE (00) - Determine Color
58
- avg_color = np.mean(region)
59
- chunks.append((x, y, w, h, avg_color, heat))
60
 
61
  recursive_bake(0, 0, w, h)
 
62
 
63
- # 3. Render the Result (The "Cake")
64
- # We rebuild the image from the atoms to prove round-trip fidelity
65
- output_canvas = np.zeros_like(gray)
66
- heatmap_overlay = np.zeros((h, w, 3), dtype=np.uint8)
67
 
68
- for (x, y, cw, ch, color, heat) in chunks:
69
- # Reconstruct Reality
70
- output_canvas[y:y+ch, x:x+cw] = color
71
-
72
- # Visualize Heat/Structure
73
- # Small blocks = Red (High Heat), Large = Blue (Persistence)
74
- is_hot = cw < 16
75
- overlay_color = (255, 0, 85) if is_hot else (0, 255, 234) # Red / Cyan
76
 
77
- cv2.rectangle(heatmap_overlay, (x, y), (x+cw, y+ch), overlay_color, 1)
 
 
 
78
 
79
- # Blend for visual effect
80
- final_view = cv2.addWeighted(
81
- cv2.cvtColor(output_canvas, cv2.COLOR_GRAY2RGB), 0.7,
82
- heatmap_overlay, 0.3, 0
 
 
 
 
 
 
 
83
  )
84
 
85
- return final_view, f"Total Atoms: {len(chunks)}"
 
 
 
86
 
87
  # --- THE INTERFACE ---
88
  with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
89
- gr.Markdown("# LOGOS: Production Validator")
90
- gr.Markdown("Running active `bake_stream.py` logic on the backend.")
91
 
92
  with gr.Row():
93
- with gr.Column():
94
- inp = gr.Image(label="Source Input", type="numpy")
95
- tol = gr.Slider(0.01, 1.0, value=0.15, label="Heat Tolerance (Persistence)")
96
- btn = gr.Button("Bake Stream", variant="primary")
97
-
98
- with gr.Column():
99
- out = gr.Image(label="Reconstructed Reality (Visualized)")
100
- stats = gr.Label(label="Stream Stats")
 
 
 
101
 
102
- btn.click(run_logos_baker, inputs=[inp, tol], outputs=[out, stats])
 
 
 
 
 
 
 
 
 
 
103
 
104
  if __name__ == "__main__":
105
  demo.launch(ssr_mode=False)
 
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:
 
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
 
 
64
  def recursive_bake(x, y, w, h):
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)
81
  recursive_bake(x+hw, y, w-hw, hh)
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)