LordXido commited on
Commit
96ebea1
·
verified ·
1 Parent(s): 4686c51

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -308
app.py CHANGED
@@ -1,309 +1,29 @@
1
  import gradio as gr
2
- import os, json, time, uuid, hashlib, random, math
3
- from datetime import datetime
4
- from typing import Dict
5
-
6
- # ============================================================
7
- # 1. WHITE-LABEL / IDENTITY CONFIG
8
- # ============================================================
9
-
10
- BRAND = os.getenv("CODEX_BRAND", "CodexFlow ΩΞ")
11
- ORG = os.getenv("CODEX_ORG", "Codex Sovereign")
12
- CCY = os.getenv("CODEX_CCY", "USD")
13
-
14
- STATE_DIR = "state"
15
- os.makedirs(STATE_DIR, exist_ok=True)
16
-
17
- FILES = {
18
- "history": f"{STATE_DIR}/history.json",
19
- "audit": f"{STATE_DIR}/audit.json",
20
- "usage": f"{STATE_DIR}/usage.json",
21
- "graph": f"{STATE_DIR}/causal_graph.json",
22
- "prov": f"{STATE_DIR}/provenance.json",
23
- "sys": f"{STATE_DIR}/system_state.json",
24
- }
25
-
26
- # ============================================================
27
- # 2. ACCESS CONTROL (RBAC + QUOTAS)
28
- # ============================================================
29
-
30
- API_KEYS = {
31
- "DEMO_KEY": {"tier": "demo", "quota": 50},
32
- "PRO_KEY": {"tier": "pro", "quota": 500},
33
- "INSTITUTIONAL_KEY": {"tier": "institutional", "quota": 50_000},
34
- "SOVEREIGN_KEY": {"tier": "sovereign", "quota": 10**9},
35
- }
36
-
37
- # ============================================================
38
- # 3. STORAGE UTILITIES
39
- # ============================================================
40
-
41
- def load(path, default=None):
42
- if os.path.exists(path):
43
- with open(path, "r") as f:
44
- return json.load(f)
45
- return [] if default is None else default
46
-
47
- def save(path, data, limit=5000):
48
- with open(path, "w") as f:
49
- json.dump(data[-limit:], f, indent=2)
50
-
51
- # ============================================================
52
- # 4. SECURITY / QUOTA ENFORCEMENT
53
- # ============================================================
54
-
55
- def authorize(key: str) -> str:
56
- if key not in API_KEYS:
57
- raise ValueError("Invalid API key")
58
-
59
- usage = load(FILES["usage"], [])
60
- if sum(1 for u in usage if u["k"] == key) >= API_KEYS[key]["quota"]:
61
- raise ValueError("Quota exceeded")
62
-
63
- usage.append({"k": key, "t": time.time()})
64
- save(FILES["usage"], usage)
65
- return API_KEYS[key]["tier"]
66
-
67
- # ============================================================
68
- # 5. CRYPTOGRAPHIC PROVENANCE (HASH-CHAIN)
69
- # ============================================================
70
-
71
- def sha(obj):
72
- return hashlib.sha256(json.dumps(obj, sort_keys=True).encode()).hexdigest()
73
-
74
- def attest(payload: Dict) -> Dict:
75
- chain = load(FILES["prov"], [])
76
- prev = chain[-1]["hash"] if chain else "GENESIS"
77
-
78
- record = {
79
- "id": str(uuid.uuid4()),
80
- "time": datetime.utcnow().isoformat(),
81
- "prev": prev,
82
- "hash": sha({**payload, "prev": prev}),
83
- }
84
-
85
- chain.append(record)
86
- save(FILES["prov"], chain)
87
- payload["provenance"] = record
88
- return payload
89
-
90
- # ============================================================
91
- # 6. FEDERATED CODEX MESH (NODE ID + BROADCAST HOOK)
92
- # ============================================================
93
-
94
- def mesh_node():
95
- return sha(os.getenv("HOSTNAME", "codex-node"))[:16]
96
-
97
- def mesh_emit(payload: Dict) -> Dict:
98
- payload["mesh"] = {
99
- "node": mesh_node(),
100
- "msg_id": str(uuid.uuid4()),
101
- "time": datetime.utcnow().isoformat(),
102
- }
103
- return payload
104
-
105
- # ============================================================
106
- # 7. REALITY ADAPTERS (SAFE STUBS)
107
- # ============================================================
108
-
109
- def exchange_price(commodity: str) -> float:
110
- base = {"Gold": 1000, "Iron Ore": 1200, "Crude Oil": 800}
111
- return round(base.get(commodity, 1000) + random.uniform(-6, 6), 2)
112
-
113
- def producer_state(commodity: str) -> Dict:
114
- return {
115
- "output_tpd": random.randint(8000, 15000),
116
- "inventory_t": random.randint(20_000, 60_000),
117
- "logistics": random.choice(["normal", "tight"]),
118
- "energy": random.choice(["stable", "volatile"]),
119
- }
120
-
121
- # ============================================================
122
- # 8. CAUSAL GRAPH + ANOMALY DETECTION
123
- # ============================================================
124
-
125
- def update_graph(commodity, distortion, lag):
126
- g = load(FILES["graph"], [])
127
- g.append({
128
- "commodity": commodity,
129
- "distortion": distortion,
130
- "lag": lag,
131
- "time": datetime.utcnow().isoformat(),
132
- })
133
- save(FILES["graph"], g)
134
-
135
- def anomaly(distortion):
136
- return abs(distortion) > 0.15
137
-
138
- # ============================================================
139
- # 9. AUTONOMOUS MATHEMATICAL CORE
140
- # ============================================================
141
-
142
- """
143
- System evolves via a stabilising gradient flow:
144
-
145
- E = d² + 0.01·lag² + (1 − c)²
146
- biasₜ₊₁ = clamp(biasₜ − η ∂E/∂d)
147
-
148
- This ensures:
149
- • no runaway correction
150
- • bounded adaptation
151
- • deterministic convergence
152
- """
153
-
154
- def system_state():
155
- return load(FILES["sys"], {"eta": 0.2, "bias": 0.0})
156
-
157
- def save_state(s):
158
- save(FILES["sys"], [s], limit=1)
159
-
160
- def energy(d, lag, c):
161
- return d*d + 0.01*lag*lag + (1-c)**2
162
-
163
- def update_state(d, lag, c):
164
- s = system_state()
165
- grad = 2*d + 0.02*lag - 2*(1-c)
166
- s["bias"] = max(-0.2, min(0.2, s["bias"] - s["eta"] * grad))
167
- save_state(s)
168
- return s
169
-
170
- # ============================================================
171
- # 10. ECONOMIC TRANSFORMS
172
- # ============================================================
173
-
174
- def harmonize(synth, phys, lag):
175
- lf = min(lag / 10, 1.0)
176
- corr = (synth - phys) * lf
177
- harm = synth - corr
178
- conf = max(0.0, 1 - abs(corr) / max(synth, 1))
179
- return round(harm, 2), round(-corr, 2), round(conf, 2)
180
-
181
- def accelerate(value, lag, conf):
182
- rate = 0.03 + (1 - conf) * 0.05
183
- return round(value / ((1 + rate) ** (lag / 365)), 2)
184
-
185
- def grade(conf):
186
- return "AAA" if conf >= 0.9 else "AA" if conf >= 0.75 else "A"
187
-
188
- def scenarios(base):
189
- return {
190
- "optimistic": round(base * 1.05, 2),
191
- "baseline": round(base, 2),
192
- "stress": round(base * 0.9, 2),
193
- }
194
-
195
- # ============================================================
196
- # 11. TREASURY / SOVEREIGN POLICY LAYER
197
- # ============================================================
198
-
199
- def treasury(tier, conf):
200
- if tier == "sovereign":
201
- return {"gate": "open", "confidence_floor": 0.7}
202
- return {"gate": "market", "confidence_floor": 0.75}
203
-
204
- # ============================================================
205
- # 12. REGULATORY EXPORT
206
- # ============================================================
207
-
208
- def regulatory(entry):
209
- return {
210
- "engine": BRAND,
211
- "org": ORG,
212
- "commodity": entry["commodity"],
213
- "harmonized_price": entry["harmonized_price"],
214
- "confidence": entry["confidence"],
215
- "mesh_node": entry["mesh"]["node"],
216
- "prov_hash": entry["provenance"]["hash"],
217
- "time": entry["timestamp"],
218
- }
219
-
220
- # ============================================================
221
- # 13. MAIN AUTONOMOUS RUNTIME
222
- # ============================================================
223
-
224
- def run(commodity, physical_anchor, lag_days, api_key, live_feed):
225
- tier = authorize(api_key)
226
-
227
- synth = exchange_price(commodity) if live_feed else round(physical_anchor * 1.05, 2)
228
- producer = producer_state(commodity)
229
-
230
- harm, dist, conf = harmonize(synth, physical_anchor, lag_days)
231
-
232
- state = update_state(abs(dist), lag_days, conf)
233
- harm = round(harm * (1 + state["bias"]), 2)
234
-
235
- accel = accelerate(harm, lag_days, conf)
236
- update_graph(commodity, dist, lag_days)
237
-
238
- result = {
239
- "engine": BRAND,
240
- "org": ORG,
241
- "tier": tier,
242
- "currency": CCY,
243
- "timestamp": datetime.utcnow().isoformat(),
244
- "commodity": commodity,
245
- "synthetic_price": synth,
246
- "physical_anchor": physical_anchor,
247
- "harmonized_price": harm,
248
- "distortion": dist,
249
- "confidence": conf,
250
- "grade": grade(conf),
251
- "accelerated_cashflow": accel,
252
- "anomaly": anomaly(dist),
253
- "producer_state": producer,
254
- "scenarios": scenarios(harm),
255
- "treasury": treasury(tier, conf),
256
- "system_state": state,
257
- }
258
-
259
- hist = load(FILES["history"], [])
260
- hist.append(result)
261
- save(FILES["history"], hist)
262
-
263
- aud = load(FILES["audit"], [])
264
- aud.append(result)
265
- save(FILES["audit"], aud)
266
-
267
- result = mesh_emit(result)
268
- result = attest(result)
269
- result["regulatory_export"] = regulatory(result)
270
- return result
271
-
272
- # ============================================================
273
- # 14. HUGGING FACE UI
274
- # ============================================================
275
-
276
- with gr.Blocks() as demo:
277
- gr.Markdown(f"# {BRAND}\n### Autonomous Economic Reflex Operating System")
278
-
279
- api = gr.Textbox(label="API Key", type="password")
280
- com = gr.Dropdown(["Gold", "Iron Ore", "Crude Oil"], label="Commodity")
281
- phys = gr.Number(950, label="Physical Anchor")
282
- lag = gr.Slider(0, 30, 7, 1, label="Reporting Lag (Days)")
283
- live = gr.Checkbox(True, label="Use Live Exchange Feed")
284
-
285
- btn = gr.Button("Execute")
286
- out = gr.JSON()
287
-
288
- btn.click(run, inputs=[com, phys, lag, api, live], outputs=out)
289
-
290
- with gr.Tab("Audit Log"):
291
- gr.Button("Load").click(lambda: load(FILES["audit"], []), outputs=gr.JSON())
292
-
293
- with gr.Tab("Causal Graph"):
294
- gr.Button("Load").click(lambda: load(FILES["graph"], []), outputs=gr.JSON())
295
-
296
- with gr.Tab("Provenance"):
297
- gr.Button("Load").click(lambda: load(FILES["prov"], []), outputs=gr.JSON())
298
-
299
- # ============================================================
300
- # 15. HF DEPLOY PATCH
301
- # ============================================================
302
-
303
- if __name__ == "__main__":
304
- demo.launch(
305
- server_name="0.0.0.0",
306
- server_port=7860,
307
- show_error=True,
308
- ssr_mode=False,
309
- )
 
1
  import gradio as gr
2
+ from compiler import compile_codexbyte
3
+ from codexbyte_vm import CodexByteVM
4
+
5
+ vm = CodexByteVM()
6
+
7
+ def run_codexbyte(source: str):
8
+ try:
9
+ program = compile_codexbyte(source.strip().splitlines())
10
+ ledger = vm.run(program)
11
+ return {
12
+ "registers": vm.reg,
13
+ "memory": vm.mem,
14
+ "omega_ledger": ledger
15
+ }
16
+ except Exception as e:
17
+ return {"error": str(e)}
18
+
19
+ gr.Interface(
20
+ fn=run_codexbyte,
21
+ inputs=gr.Textbox(
22
+ lines=16,
23
+ label="CodexByte Program",
24
+ placeholder="LOAD_IMM 0 1000\nLOAD_MEM 1 0x20\nCMP 1 0\nJZ 10\nHALT"
25
+ ),
26
+ outputs=gr.JSON(label="Ω-State Proof"),
27
+ title="CodexByte ΩΞ Runtime",
28
+ description="Bytecode execution is enforcement. Execution trace is proof."
29
+ ).launch()