LordXido commited on
Commit
cd9d7a2
Β·
verified Β·
1 Parent(s): ba64e85

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -313
app.py CHANGED
@@ -1,354 +1,176 @@
1
- import gradio as gr
2
- import requests
3
- import time
4
- import json
5
- import hashlib
6
- from collections import deque
7
- import numpy as np
8
- from typing import Dict, Any, List
9
-
10
- # ======================================================
11
- # CONFIG & GLOBAL STATE
12
- # ======================================================
13
-
14
- LEDGER: List[Dict[str, Any]] = []
15
- CHAT_MEMORY: List[str] = []
16
- OMEGA_MEMORY: deque = deque(maxlen=16) # Causal smoothing buffer (Ξ© influence)
17
 
18
- WORLD_BANK_BASE = "https://api.worldbank.org/v2"
19
- INDICATORS = {
20
- "GDP": "NY.GDP.MKTP.CD",
21
- "INFLATION": "FP.CPI.TOTL.ZG",
22
- "POPULATION": "SP.POP.TOTL",
23
- }
24
 
25
- # Simple semantic intent anchor (toy version of Θ projection target)
26
- INTENT_ANCHOR = {
27
- "stability": 0.92,
28
- "transparency": 0.88,
29
- "realism": 0.85
 
 
 
 
 
 
 
 
 
 
 
30
  }
31
- COHERENCE_THRESHOLD = 0.65 # Below this β†’ refusal/quarantine
32
-
33
- # ======================================================
34
- # WORLD BANK MACRO FETCH
35
- # ======================================================
36
 
37
- def fetch_indicator(indicator: str, country: str = "WLD", year: str = "2023") -> float | None:
38
- try:
39
- url = f"{WORLD_BANK_BASE}/country/{country}/indicator/{indicator}?format=json&per_page=1&date={year}"
40
- r = requests.get(url, timeout=7)
41
- r.raise_for_status()
42
- data = r.json()
43
- if len(data) > 1 and data[1]:
44
- return float(data[1][0].get("value", np.nan))
45
- return None
46
- except Exception:
47
- return None
48
 
49
- def fetch_macro_anchor(country: str = "WLD", use_live: bool = True) -> Dict[str, Any]:
50
- if not use_live:
51
- return {"country": country, "gdp": None, "inflation": None, "population": None}
52
 
53
- gdp = fetch_indicator(INDICATORS["GDP"], country)
54
- inflation = fetch_indicator(INDICATORS["INFLATION"], country)
55
- population = fetch_indicator(INDICATORS["POPULATION"], country)
56
 
57
- return {
58
- "country": country,
59
- "gdp": gdp if gdp is not None else np.nan,
60
- "inflation": inflation if inflation is not None else np.nan,
61
- "population": population if population is not None else np.nan,
62
- }
63
-
64
- # ======================================================
65
- # BIT + HASH + COHERENCE LAYER
66
- # ======================================================
67
-
68
- def canonical_bytes(obj: Any) -> bytes:
69
- return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode('utf-8')
70
-
71
- def compute_bit_stats(payload: Dict) -> Dict:
72
- b = canonical_bytes(payload)
73
- unique = len(set(b))
74
- return {
75
- "bytes": len(b),
76
- "bits": len(b) * 8,
77
- "symbol_diversity": unique,
78
- "entropy_proxy": round(unique / max(len(b), 1), 6)
79
- }
80
 
81
- def hash_record(payload: Dict, prev_hash: str) -> str:
82
- data = {"payload": payload, "prev_hash": prev_hash}
83
- return hashlib.sha256(canonical_bytes(data)).hexdigest()
84
 
85
- def compute_coherence_score(values_dict: Dict[str, float]) -> float:
86
- """Very simple toy coherence metric (closer to intent anchor = higher score)"""
87
- if not values_dict:
88
- return 0.0
89
-
90
- scores = []
91
- for k, target in INTENT_ANCHOR.items():
92
- if k in values_dict and not np.isnan(values_dict[k]):
93
- val = values_dict[k]
94
- norm_diff = min(1.0, abs(val - target) / max(abs(target), 0.01))
95
- scores.append(1.0 - norm_diff)
96
-
97
- return round(np.mean(scores) if scores else 0.5, 4)
98
 
99
- def omega_smooth(key: str, new_value: float) -> float:
100
- """Simple EMA style smoothing (early Ξ© influence)"""
101
- if not OMEGA_MEMORY:
102
- OMEGA_MEMORY.append({key: new_value})
103
- return new_value
104
-
105
- prev = OMEGA_MEMORY[-1].get(key, new_value)
106
- alpha = 0.3
107
- smoothed = alpha * new_value + (1 - alpha) * prev
108
- OMEGA_MEMORY.append({key: smoothed})
109
- return round(smoothed, 6)
110
 
111
- # ======================================================
112
- # SIGNAL GENERATORS (now with smoothing)
113
- # ======================================================
114
 
115
- def commodity_signal(commodity: str, anchor: float, macro: Dict) -> Dict:
116
- gdp_scale = macro.get("gdp", 1e14) / 1e14 if macro.get("gdp") else 1.0
117
- supply = anchor * gdp_scale
118
- demand = supply * 0.94
119
- price_index = round((supply / 12.0) * gdp_scale, 4)
120
-
121
- smoothed_price = omega_smooth("price_index", price_index)
122
-
123
- return {
124
- "type": "commodity",
125
- "commodity": commodity,
126
- "supply": round(supply, 4),
127
- "demand": round(demand, 4),
128
- "price_index": smoothed_price,
129
- "currency_flow": round(demand * smoothed_price, 4),
130
- }
131
 
132
- def logistics_signal(econ: Dict) -> Dict:
133
- friction = abs(econ["supply"] - econ["demand"]) / max(econ["supply"], 1e-9)
134
- return {"type": "logistics", "friction": round(friction, 6)}
135
 
136
- def energy_signal(econ: Dict) -> Dict:
137
- return {
138
- "type": "energy",
139
- "energy_cost_index": round(econ["price_index"] * 0.42, 4),
140
- "dependency": "high" if "oil" in econ["commodity"].lower() or "gas" in econ["commodity"].lower() else "moderate"
141
- }
142
 
143
- def sentiment_signal(seed: str) -> Dict:
144
- import random
145
- random.seed(sum(ord(c) for c in seed + str(time.time())[:8]))
146
- conf = random.uniform(0.62, 0.91)
147
- return {
148
- "type": "sentiment",
149
- "market_confidence": round(omega_smooth("confidence", conf), 6)
150
- }
151
 
152
- # ======================================================
153
- # LEDGER OPERATIONS
154
- # ======================================================
155
 
156
- def append_to_ledger(payload: Dict, meta: Dict, coherence: float) -> Dict | None:
157
- if coherence < COHERENCE_THRESHOLD:
158
- return {
159
- "status": "refused",
160
- "reason": f"Coherence too low: {coherence:.4f} < {COHERENCE_THRESHOLD}",
161
- "payload": payload
162
- }
163
-
164
- prev_hash = LEDGER[-1]["hash"] if LEDGER else "GENESIS"
165
- record_hash = hash_record(payload, prev_hash)
166
-
167
- record = {
168
- "hash": record_hash,
169
- "prev_hash": prev_hash,
170
- "payload": payload,
171
- "metadata": {**meta, "coherence_score": coherence},
172
- "bit_stats": compute_bit_stats(payload),
173
- "ts": time.time(),
174
- }
175
 
176
- LEDGER.append(record)
177
- return record
 
178
 
179
- def run_tick(commodity: str, anchor: float, country: str, lag_days: int, use_live: bool):
180
- t0 = time.time()
181
-
182
- macro = fetch_macro_anchor(country, use_live)
183
- latency = time.time() - t0
184
-
185
- meta_macro = {
186
- "source": "world_bank" if use_live and macro["gdp"] is not None else "synthetic",
187
- "country": country,
188
- "latency_s": round(latency, 4),
189
- "schema": "macro.v1"
190
- }
191
-
192
- # Macro coherence (very basic)
193
- macro_coherence = compute_coherence_score({
194
- "stability": 1.0 - abs(macro.get("inflation", 0))/10,
195
- "realism": 1.0 if macro.get("gdp") is not None else 0.4
196
- })
197
-
198
- macro_record = append_to_ledger({"type": "macro", **macro}, meta_macro, macro_coherence)
199
- if macro_record and "status" in macro_record and macro_record["status"] == "refused":
200
- return {"status": "macro_refused", "detail": macro_record}, None
201
-
202
- # Derived signals
203
- econ = commodity_signal(commodity, anchor, macro)
204
- logi = logistics_signal(econ)
205
- ener = energy_signal(econ)
206
- sent = sentiment_signal(commodity + country + str(int(time.time())))
207
-
208
- feat = {
209
- "type": "features",
210
- "lag_days": lag_days,
211
- "projected_price": round(econ["price_index"] * (1 + (1 - sent["market_confidence"]) * 0.07), 6),
212
- "volatility_proxy": round(0.012 * lag_days, 6)
213
- }
214
-
215
- results = []
216
- for payload, schema in [
217
- (econ, "commodity.v1"),
218
- (logi, "logistics.v1"),
219
- (ener, "energy.v1"),
220
- (sent, "sentiment.v1"),
221
- (feat, "features.v1")
222
- ]:
223
- coherence = compute_coherence_score({
224
- "stability": 1.0 - abs(logi["friction"]),
225
- "transparency": sent["market_confidence"]
226
- })
227
-
228
- meta = {
229
- "source": "derived",
230
- "schema": schema,
231
- "coherence_score": coherence
232
- }
233
- rec = append_to_ledger(payload, meta, coherence)
234
- if rec:
235
- results.append(rec)
236
-
237
- tip = LEDGER[-1] if LEDGER else None
238
- return {
239
- "status": "tick_complete",
240
- "ledger_length": len(LEDGER),
241
- "tip_hash": tip["hash"] if tip else None,
242
- "latest_coherence": tip["metadata"].get("coherence_score") if tip else None,
243
- "records_added": len(results)
244
- }, tip["hash"] if tip else None
245
 
246
- # ======================================================
247
- # CHAT INTERFACE - Jarvis X (enhanced awareness)
248
- # ======================================================
 
 
 
249
 
250
- def jarvis_x_chat(message: str, history: List):
251
- CHAT_MEMORY.append(message)
252
- m = message.lower().strip()
253
-
254
- if not LEDGER:
255
- return "The ledger is still in genesis state. Please run a tick first.", history
256
-
257
- tip = LEDGER[-1]
258
-
259
- if any(k in m for k in ["latest", "tip", "current"]):
260
- return json.dumps({
261
- "tip_hash": tip["hash"],
262
- "prev_hash": tip["prev_hash"],
263
- "coherence": tip["metadata"].get("coherence_score", "N/A"),
264
- "type": tip["payload"].get("type"),
265
- "timestamp": time.ctime(tip["ts"])
266
- }, indent=2), history
267
-
268
- if "ledger" in m or "size" in m:
269
- return f"Current ledger contains {len(LEDGER)} records. Average coherence: {np.mean([r['metadata'].get('coherence_score',0) for r in LEDGER]):.4f}", history
270
-
271
- if "coherence" in m or "health" in m:
272
- coherences = [r["metadata"].get("coherence_score", 0) for r in LEDGER[-12:]]
273
- return f"Recent coherence trend (last {len(coherences)}): {coherences}\nAverage: {np.mean(coherences):.4f}", history
274
-
275
- if "refused" in m or "rejected" in m:
276
- refused = [r for r in LEDGER if r["metadata"].get("coherence_score", 1) < COHERENCE_THRESHOLD]
277
- return f"{len(refused)} records were refused due to low coherence.", history
278
 
279
- return (
280
- "Jarvis X online. Available commands:\n"
281
- "β€’ latest / tip\n"
282
- "β€’ ledger / size\n"
283
- "β€’ coherence / health\n"
284
- "β€’ refused / rejected\n\n"
285
- "The manifold is permeating... speak your intent."
286
- ), history
287
 
288
- # ======================================================
289
- # GRADIO INTERFACE
290
- # ======================================================
 
 
 
 
291
 
292
- css = """
293
- .gradio-container {font-family: 'Segoe UI', system-ui;}
294
- .header {text-align: center; padding: 1rem; background: linear-gradient(90deg, #1e3a8a, #3b82f6);}
295
- """
296
 
297
- with gr.Blocks(css=css) as app:
 
298
  gr.Markdown(
299
  """
300
- # 🌌 CodexFlow β€’ IRE Permeation Engine
301
- **Global Virtual Bit + Metadata System with Early Semantic Coherence Enforcement**
302
- _January 11, 2026 β€” Beyond SOTA prototype_
303
- """,
304
- elem_classes="header"
 
305
  )
306
-
307
  with gr.Row():
308
- with gr.Column(scale=2):
309
- gr.Markdown("### Data Ingestion & Tick Controls")
310
-
311
- with gr.Row():
312
- commodity = gr.Dropdown(
313
- choices=["Gold", "Oil", "Gas", "Wheat", "Copper", "Lithium"],
314
- value="Gold",
315
- label="Commodity"
316
- )
317
- anchor = gr.Number(value=1200, label="Physical Anchor (tons/price unit)")
318
-
319
- with gr.Row():
320
- country = gr.Textbox(value="WLD", label="Country Code (WLD = World)")
321
- live_data = gr.Checkbox(value=True, label="Use Live World Bank Data")
322
- lag_days = gr.Slider(1, 180, value=7, step=1, label="Lag (days)")
323
 
324
- run_btn = gr.Button("Run Tick β†’ Permeate Ledger", variant="primary")
 
325
 
326
- tick_result = gr.JSON(label="Tick Result")
327
- current_tip = gr.Textbox(label="Current Tip Hash", interactive=False)
328
 
329
- run_btn.click(
330
- fn=run_tick,
331
- inputs=[commodity, anchor, country, lag_days, live_data],
332
- outputs=[tick_result, current_tip]
333
- )
334
-
335
- with gr.Column(scale=1):
336
- gr.Markdown("### Jarvis X β€’ Manifold Interface")
337
- chat = gr.ChatInterface(
338
- fn=jarvis_x_chat,
339
- chatbot=gr.Chatbot(height=380),
340
- title="Jarvis X Resonance",
341
- description="Query the manifold state β€’ coherence β€’ provenance"
 
 
 
 
 
 
 
342
  )
343
 
 
344
  gr.Markdown(
345
  """
346
  ---
347
- **Status**: Early IRE permeation β€’ Ξ› constraint stub β€’ Ξ© memory smoothing
348
- **Coherence threshold**: 0.65 β€’ Records refused below this level are quarantined
349
- *Not financial advice β€” research & provenance-first prototype*
350
  """
351
  )
352
 
 
 
 
 
 
 
 
 
 
 
 
 
353
  if __name__ == "__main__":
354
- app.launch()
 
1
+ # app.py
2
+ """
3
+ Dr Moagi IRE Equation β€’ Autonomous Manifold Explorer
4
+ Minimal autonomous simulation of the sealed governing equation
5
+ dΞ/dt = -Ξ› βˆ‡(Θ(Ξ) + Ξ¦(Ξ) - Ξ¨(t) + Ξ©(t))
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ Hugging Face Spaces demo - January 11, 2026
8
+ """
 
 
 
 
9
 
10
+ import gradio as gr
11
+ import torch
12
+ import numpy as np
13
+ import matplotlib.pyplot as plt
14
+ from io import BytesIO
15
+ import base64
16
+
17
+ # ─── Configuration ────────────────────────────────────────────────
18
+ DEFAULT_PARAMS = {
19
+ 'steps': 600,
20
+ 'dt': 0.075,
21
+ 'noise': 0.38,
22
+ 'lambda_': 3.4,
23
+ 'omega_window': 14,
24
+ 'intent_x': 2.1,
25
+ 'intent_y': 1.4
26
  }
 
 
 
 
 
27
 
28
+ COHERENCE_WARN = 0.68
 
 
 
 
 
 
 
 
 
 
29
 
30
+ # ─── Core Simulation ──────────────────────────────────────────────
31
+ def run_ire_simulation(steps, dt, noise_mag, lam, omega_len, intent):
32
+ device = torch.device("cpu")
33
 
34
+ intent_target = torch.tensor([intent[0], intent[1]], dtype=torch.float32, device=device)
 
 
35
 
36
+ Xi = torch.zeros(2, device=device, requires_grad=True)
37
+ Omega = []
38
+ trajectory = [Xi.detach().cpu().numpy().copy()]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ for step in range(steps):
41
+ t = step * dt
 
42
 
43
+ # Potential terms (toy implementations)
44
+ theta = 0.45 * (intent_target - Xi).pow(2).sum()
45
+ phi = 0.28 * torch.sin(3.2 * torch.atan2(Xi[1], Xi[0])) * torch.cos(1.8 * Xi.norm()) + 0.15 * Xi.norm()**2
46
+ psi = torch.randn(2, device=device) * noise_mag * (1.0 + 0.35 * torch.sin(t * 0.14))
47
+ omega_mean = torch.mean(torch.stack(Omega), dim=0) if Omega else torch.zeros(2, device=device)
 
 
 
 
 
 
 
 
48
 
49
+ potential = theta + phi - psi + omega_mean
 
 
 
 
 
 
 
 
 
 
50
 
51
+ grad = torch.autograd.grad(potential, Xi, create_graph=False)[0]
52
+ dXi = -lam * grad
 
53
 
54
+ Xi = Xi + dt * dXi
55
+ Xi = Xi.detach().requires_grad_(True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ Omega.append(Xi.detach().clone())
58
+ if len(Omega) > omega_len:
59
+ Omega.pop(0)
60
 
61
+ trajectory.append(Xi.detach().cpu().numpy().copy())
 
 
 
 
 
62
 
63
+ return np.array(trajectory)
 
 
 
 
 
 
 
64
 
 
 
 
65
 
66
+ def create_plot(traj, intent, lam, noise, steps):
67
+ fig, ax = plt.subplots(figsize=(8, 7.2), dpi=100)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
+ ax.plot(traj[:,0], traj[:,1], 'royalblue', lw=1.3, alpha=0.85, label='trajectory')
70
+ ax.plot(traj[0,0], traj[0,1], 'o', ms=10, mec='k', mfc='#00ff9d', label='birth')
71
+ ax.plot(traj[-1,0], traj[-1,1], 'o', ms=12, mec='k', mfc='#ff3366', label='present')
72
 
73
+ ax.scatter(intent[0], intent[1], s=320, c='gold', marker='*',
74
+ edgecolor='navy', lw=2, label='semantic intent target')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
+ # Coherence estimate
77
+ final_dist = np.linalg.norm(traj[-1] - np.array(intent))
78
+ coh = max(0.0, 1.0 - final_dist / 4.8)
79
+ coh_text = f"Coherence: {coh:.3f}"
80
+ if coh < COHERENCE_WARN:
81
+ coh_text += " ⚠ drifting"
82
 
83
+ ax.set_title(
84
+ f"IRE Autonomous Manifold Evolution\n"
85
+ f"Ξ› = {lam:.2f} β€’ noise = {noise:.2f} β€’ steps = {steps}\n"
86
+ f"{coh_text}",
87
+ fontsize=13, pad=15
88
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
+ ax.set_xlabel("Semantic Dimension 1", fontsize=11)
91
+ ax.set_ylabel("Semantic Dimension 2", fontsize=11)
92
+ ax.grid(True, alpha=0.15, linestyle='--')
93
+ ax.legend(loc='upper right', fontsize=9, framealpha=0.92)
94
+ ax.set_aspect('equal')
95
+ ax.set_facecolor('#f8f9fa')
 
 
96
 
97
+ buf = BytesIO()
98
+ plt.savefig(buf, format='png', bbox_inches='tight', dpi=120)
99
+ buf.seek(0)
100
+ img_base64 = base64.b64encode(buf.read()).decode('ascii')
101
+ plt.close(fig)
102
+
103
+ return f"data:image/png;base64,{img_base64}"
104
 
 
 
 
 
105
 
106
+ # ─── Gradio Interface ─────────────────────────────────────────────
107
+ with gr.Blocks(title="IRE Equation β€’ Autonomous Manifold") as demo:
108
  gr.Markdown(
109
  """
110
+ # Dr Moagi IRE Equation
111
+ **Autonomous Semantic Manifold Explorer**
112
+ *Minimal canonical implementation β€” January 11, 2026*
113
+
114
+ dΞ/dt = βˆ’Ξ› βˆ‡(Θ(Ξ) + Ξ¦(Ξ) βˆ’ Ξ¨(t) + Ξ©(t))
115
+ """
116
  )
117
+
118
  with gr.Row():
119
+ with gr.Column(scale=1):
120
+ gr.Markdown("### Control Parameters")
121
+
122
+ steps = gr.Slider(200, 1500, value=DEFAULT_PARAMS['steps'],
123
+ step=50, label="Simulation steps")
 
 
 
 
 
 
 
 
 
 
124
 
125
+ noise = gr.Slider(0.00, 1.20, value=DEFAULT_PARAMS['noise'],
126
+ step=0.02, label="External noise strength (Ξ¨)")
127
 
128
+ lam = gr.Slider(0.5, 10.0, value=DEFAULT_PARAMS['lambda_'],
129
+ step=0.1, label="Constraint strength (Ξ›)")
130
 
131
+ intent_x = gr.Number(value=DEFAULT_PARAMS['intent_x'],
132
+ label="Intent target X")
133
+ intent_y = gr.Number(value=DEFAULT_PARAMS['intent_y'],
134
+ label="Intent target Y")
135
+
136
+ run_btn = gr.Button("Run Autonomous Evolution", variant="primary")
137
+
138
+ with gr.Column(scale=3):
139
+ output_image = gr.Image(label="Manifold Trajectory", type="filepath")
140
+ gr.Markdown(
141
+ """
142
+ **Legend**
143
+ β€’ Green circle β†’ starting point
144
+ β€’ Red circle β†’ current position
145
+ β€’ Gold star β†’ semantic intent attractor
146
+ β€’ Blue path β†’ autonomous trajectory under the sealed equation
147
+
148
+ Higher Ξ› β†’ stronger law & refusal of drift
149
+ Higher noise β†’ more chaotic external pressure
150
+ """
151
  )
152
 
153
+ # Footer explanation
154
  gr.Markdown(
155
  """
156
  ---
157
+ **Current status**: 2D toy prototype β€’ pure mathematical core
158
+ β€’ constraint-dominant flow β€’ causal memory smoothing β€’ stochastic reality pressure
159
+ β€’ No language, no high dimensions, no external data β€” only the law breathing
160
  """
161
  )
162
 
163
+ def on_run(steps, noise, lam, ix, iy):
164
+ traj = run_ire_simulation(steps, DEFAULT_PARAMS['dt'], noise, lam,
165
+ DEFAULT_PARAMS['omega_window'], (ix, iy))
166
+ img = create_plot(traj, (ix, iy), lam, noise, steps)
167
+ return img
168
+
169
+ run_btn.click(
170
+ on_run,
171
+ inputs=[steps, noise, lam, intent_x, intent_y],
172
+ outputs=output_image
173
+ )
174
+
175
  if __name__ == "__main__":
176
+ demo.launch()