File size: 12,278 Bytes
c1c64b0 5b18b64 c1c64b0 5b18b64 5148712 b46dbbf c1c64b0 071c08c 5b18b64 071c08c 5148712 071c08c 5148712 071c08c 5148712 071c08c 5148712 071c08c c4efb1f 5148712 c4efb1f c1c64b0 5b18b64 e3a9170 c1c64b0 e3a9170 071c08c e3a9170 071c08c e3a9170 68a1ee1 c1c64b0 98e9950 071c08c e3a9170 98e9950 c1c64b0 68a1ee1 c1c64b0 5b18b64 c1c64b0 e3a9170 071c08c 68a1ee1 5148712 68a1ee1 5148712 071c08c 5148712 3560b9c 396030b 6112dc6 396030b f06e956 396030b c1c64b0 5148712 3560b9c 396030b 68a1ee1 396030b 5148712 396030b 5148712 396030b c4efb1f 5148712 c4efb1f 5148712 c4efb1f 396030b c1c64b0 3560b9c fa9b766 c1c64b0 396030b c1c64b0 5b18b64 5bcfbea 5b18b64 c1c64b0 5b18b64 c1c64b0 e3a9170 c1c64b0 5b18b64 c1c64b0 d7b67af 5b18b64 c1c64b0 e3a9170 c1c64b0 5b18b64 e3a9170 071c08c 5b18b64 e3a9170 98e9950 c1c64b0 e3a9170 5b18b64 e3a9170 071c08c 5b18b64 e3a9170 d7b67af c1c64b0 3560b9c 5b18b64 c1c64b0 396030b c1c64b0 396030b c1c64b0 fa9b766 | 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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | # Phi-Infinity-Lattice-Compression/hf_space/app.py
import gradio as gr
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import torch
import time
from nrc_engine import PhiInfinityEngine
import os
import asyncio
from huggingface_hub import login
# Institutional Authentication
# We check for HF_TOKEN in the environment (provided by HF Spaces Secrets)
hf_token = os.getenv("HF_TOKEN")
if hf_token:
print("[SYSTEM] Institutional HF_TOKEN detected. Authenticating...")
login(token=hf_token)
else:
print("[WARNING] No HF_TOKEN detected. Proceeding as unauthenticated (rate limits may apply).")
# Initialize the Engine
engine = PhiInfinityEngine()
# Custom CSS for NRC Obsidian/Gold Aesthetic
custom_css = """
body { background-color: #0A0A0A; color: #D4AF37; font-family: 'Inter', sans-serif; }
.gradio-container { border: 1px solid #D4AF37; border-radius: 12px; padding: 20px; background: rgba(10, 10, 10, 0.95) !important; }
.nrc-title { font-size: 2.5em; font-weight: 800; color: #FFD700; text-align: center; margin-bottom: 0.1em; text-shadow: 0 0 15px rgba(212, 175, 55, 0.5); }
.nrc-subtitle { font-size: 1.1em; color: #D4AF37; text-align: center; margin-bottom: 2em; letter-spacing: 2px; text-transform: uppercase; }
.log-console {
background-color: #050505 !important;
color: #00FF41 !important;
font-family: 'Fira Code', monospace !important;
padding: 15px;
border: 1px solid #00FF4122;
border-radius: 8px;
height: 450px;
overflow-y: auto;
font-size: 0.85em;
line-height: 1.4;
box-shadow: inset 0 0 20px rgba(0, 255, 65, 0.05);
scrollbar-width: thin;
scrollbar-color: #00FF41 #000;
}
.plot-container {
height: 600px !important;
min-height: 600px !important;
transform: translateZ(0);
will-change: transform;
backface-visibility: hidden;
}
"""
def load_bible():
try:
with open("bible.txt", "r") as f:
return f.read()
except Exception as e:
return f"Error loading preloaded context: {e}"
def generate_viz(residuals, highlights=None):
coords = engine.get_spiral_coordinates(residuals, highlights)
df = pd.DataFrame(coords)
colorscale = 'YlOrBr'
intensity_vals = df['intensity']
if highlights:
colorscale = [[0, 'rgba(50,50,50,0.2)'], [0.2, 'gold'], [1, 'cyan']]
# Normalize intensity for better contrast
max_int = intensity_vals.max() if intensity_vals.max() > 0 else 1.0
intensity_vals = (intensity_vals / max_int).clip(0, 1)
if df.empty:
return go.Figure().update_layout(title="No Lattice Data Available", template="plotly_dark")
fig = go.Figure(data=[go.Scatter3d(
x=df['x'], y=df['y'], z=df['z'],
mode='markers',
marker=dict(
size=4 if not highlights else 6,
color=intensity_vals,
colorscale=colorscale,
opacity=0.8,
line=dict(width=0)
),
text=df.get('label', [])
)])
fig.update_layout(
template="plotly_dark",
margin=dict(l=0, r=0, b=0, t=0),
scene=dict(
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False, title=""),
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False, title=""),
zaxis=dict(showgrid=False, zeroline=False, showticklabels=False, title=""),
bgcolor="rgba(0,0,0,0)"
)
)
return fig
def format_logs(logs):
if logs is None:
return "<div class='log-console'>[SYSTEM] Initializing telemetry...</div>"
# Virtualized projection: Only show the last 50 lines to prevent DOM bloat
lines = str(logs).split('\n')
projection = '\n'.join(lines[-50:])
return f"<div class='log-console'>{projection.replace('\n', '<br>')}</div>"
async def process_context(text, state_residuals, state_logs):
print(f"[EVENT] Starting Compression. Input length: {len(text)}")
try:
if not text.strip():
new_logs = (state_logs or "") + "\n[ERROR] No input text provided."
yield None, "Please provide input text.", state_residuals, new_logs, format_logs(new_logs), ""
return
logs = (state_logs or "") + "\n[SYSTEM] Initializing φ^∞ Compression Sequence..."
yield None, "", state_residuals, logs, format_logs(logs), ""
segments = [s.strip() for s in text.split("\n") if s.strip()]
logs += f"\n[LATTICE] Detected {len(segments)} semantic shards."
batch_size = 512
all_embeddings = []
for i in range(0, len(segments), batch_size):
progress = (i / len(segments)) * 100
current_batch_count = min(i + batch_size, len(segments))
logs += f"\n[BATCH] Encoded {current_batch_count}/{len(segments)} shards ({progress:.1f}%)..."
yield None, f"Encoding {progress:.1f}%...", state_residuals, logs, format_logs(logs), ""
batch = segments[i:i + batch_size]
embeddings = await asyncio.to_thread(engine.embed_model.encode, batch, convert_to_tensor=True, show_progress_bar=False)
all_embeddings.append(embeddings)
embeddings_tensor = torch.cat(all_embeddings, dim=0)
centroid = torch.mean(embeddings_tensor, dim=0)
residuals = engine.hierarchy.compress(centroid)
stats = engine.hierarchy.get_memory_usage()
stats["shards_folded"] = len(segments)
stats["theoretical_ratio"] = 0.3819 # Fallback if missing
audit = engine.run_ttt_audit(centroid)
stats["ttt_audit"] = audit
logs += f"\n[SYSTEM] Successfully folded {len(segments)} shards into φ-manifold."
audit_report = f"### TTT Stability Audit\n**Status**: {stats['ttt_audit']['status']}\n**Root**: {stats['ttt_audit']['digital_root']}\n**Energy**: {stats['ttt_audit']['energy']:.6f}"
raw_view = f"Manifold Depth: {len(residuals)}\nShards Folded: {stats['shards_folded']}\n"
raw_view += f"Theoretical Ratio: {stats['theoretical_ratio']}"
fig = generate_viz(residuals)
print(f"[EVENT] Compression Completed. Manifold Depth: {len(residuals)}")
yield fig, audit_report, residuals, logs, format_logs(logs), raw_view
except Exception as e:
error_msg = f"\n[CRITICAL ERROR] {str(e)}"
print(f"[CRASH] {error_msg}")
yield None, "Compression Failed", state_residuals, (state_logs or "") + error_msg, format_logs((state_logs or "") + error_msg), ""
async def search_query(query, state_residuals, state_logs):
print(f"[EVENT] Starting Search Query: '{query}'")
try:
if not state_residuals:
new_logs = (state_logs or "") + "\n[ERROR] Attempted search on empty lattice."
yield "Lattice is empty.", state_logs, format_logs(new_logs), None
return
logs = (state_logs or "") + f"\n[QUERY] Projecting search shard: '{query}'..."
yield "Initializing scan...", logs, format_logs(logs), generate_viz(state_residuals)
await asyncio.sleep(0.5)
logs += "\n[RECON] Reconstructing high-dimensional manifold from residual stack..."
yield "Reconstructed.", logs, format_logs(logs), generate_viz(state_residuals)
result = engine.search_context(query, state_residuals)
res_resonances = result['res_resonances']
logs += "\n[SCAN] Measuring semantic resonance across 8192 dimensions..."
# Progressive LOD Animation
for step in [64, 32, 16]:
temp_highlights = [0.0] * len(state_residuals)
for j in range(0, len(state_residuals), step):
temp_highlights[j] = 0.3
yield f"Scanning (LOD {step})...", logs, format_logs(logs), generate_viz(state_residuals, temp_highlights)
await asyncio.sleep(0.3)
logs += f"\n[SIGNAL] Peak Resonance identified: {result['resonance']:.4f}"
final_fig = generate_viz(state_residuals, res_resonances)
status = "HIGH RESONANCE" if result['resonance'] > 0.5 else "LOW SIGNAL"
report = f"### Semantic Resonance Result\n**Score**: {result['resonance']:.4f}\n**Match Status**: {status}"
print(f"[QUERY] Completed. Resonance: {result['resonance']:.4f}")
yield report, logs, format_logs(logs), final_fig
except Exception as e:
error_msg = f"\n[CRITICAL ERROR] {str(e)}"
print(f"[CRASH] {error_msg}")
yield "Search Failed", (state_logs or "") + error_msg, format_logs((state_logs or "") + error_msg), None
def handle_preload():
print("[EVENT] Preloading High-Volume Context (Bible)...")
return load_bible()
with gr.Blocks(title="NRC φ^∞ Engine") as demo:
state_residuals = gr.State([])
state_logs = gr.State("")
with gr.Row():
with gr.Column(scale=4):
gr.Markdown("<div class='nrc-title'>φ^∞ Infinite Context Engine</div>")
gr.Markdown("<div class='nrc-subtitle'>Institutional High-Dimensional Lattice Resonance</div>")
gr.Markdown("[Repository](https://github.com/Nexus-Resonance-Codex/Phi-Infinity-Lattice-Compression) | [Space](https://huggingface.co/spaces/Nexus-Resonance-Codex/LLM-Infinite-Context-Engine)")
with gr.Column(scale=1):
preload_btn = gr.Button("Preload Bible (High-Vol)", variant="secondary")
with gr.Tabs():
with gr.Tab("Manifold Deployment"):
with gr.Row():
with gr.Column(scale=1):
input_text = gr.Textbox(
label="Input Context",
placeholder="Paste text...",
lines=15
)
compress_btn = gr.Button("Compress to φ-Lattice", variant="primary")
with gr.Row():
with gr.Column(elem_classes=["metric-card"]):
gr.Markdown("<div class='metric-label'>Lattice Dim</div>")
gr.Markdown("<div class='metric-value'>8192</div>")
with gr.Column(elem_classes=["metric-card"]):
gr.Markdown("<div class='metric-label'>Stability</div>")
gr.Markdown("<div class='metric-value'>TTT-7</div>")
with gr.Column(scale=2):
viz_output = gr.Plot(label="3D Manifold Spiral", elem_classes=["plot-container"])
audit_output = gr.Markdown("Audit telemetry will appear here.")
with gr.Tab("Execution Trace & Raw Data"):
with gr.Row():
with gr.Column(scale=2):
gr.Markdown("### System Log Console (Raw Data Stream)")
log_console = gr.HTML(format_logs("Waiting for sequence initialization..."))
with gr.Column(scale=1):
gr.Markdown("### Residual Shard Registry")
raw_lattice_view = gr.Code(label="Norms & Tensor Samples", language="python", interactive=False)
with gr.Tab("Semantic Retrieval"):
with gr.Row():
with gr.Column(scale=1):
search_input = gr.Textbox(label="Query the Lattice", placeholder="Search for concepts...")
search_btn = gr.Button("Retrieve Signal", variant="primary")
search_output = gr.Markdown("Search results will appear here...")
with gr.Column(scale=2):
search_viz = gr.Plot(label="Retrieval Animation", elem_classes=["plot-container"])
preload_btn.click(handle_preload, outputs=[input_text])
compress_btn.click(
process_context,
inputs=[input_text, state_residuals, state_logs],
outputs=[viz_output, audit_output, state_residuals, state_logs, log_console, raw_lattice_view]
)
search_btn.click(
search_query,
inputs=[search_input, state_residuals, state_logs],
outputs=[search_output, state_logs, log_console, search_viz]
)
if __name__ == "__main__":
demo.launch(css=custom_css, theme=gr.themes.Soft())
|