LordXido commited on
Commit
cf02a3c
·
verified ·
1 Parent(s): 509df0d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +169 -206
app.py CHANGED
@@ -1,259 +1,222 @@
1
  import gradio as gr
 
2
  from datetime import datetime
3
  from typing import Dict, List
4
- import os
5
- import json
6
- import uuid
7
 
8
  # ======================================================
9
- # CONFIGURATION
10
  # ======================================================
 
 
 
 
 
11
 
12
- API_KEY = os.environ.get("CODEXFLOW_API_KEY", "DEMO_KEY")
13
- LICENSE_TIERS = {
14
- "DEMO_KEY": "demo",
15
- "PRO_KEY": "pro",
16
- "INSTITUTIONAL_KEY": "institutional"
17
- }
18
- HISTORY_FILE = "history.json"
19
- AUDIT_FILE = "audit_log.json"
20
 
21
  # ======================================================
22
- # PERSISTENCE & GOVERNANCE
23
  # ======================================================
24
-
25
- def _load_file(path):
26
- if os.path.exists(path):
27
- with open(path, "r") as f:
28
- return json.load(f)
29
- return []
30
-
31
- def _save_file(path, data, limit=1000):
32
- with open(path, "w") as f:
33
- json.dump(data[-limit:], f, indent=2)
34
-
35
- def log_audit(entry: Dict):
36
- audit = _load_file(AUDIT_FILE)
37
- audit.append(entry)
38
- _save_file(AUDIT_FILE, audit)
39
-
40
- def save_history(entry: Dict):
41
- hist = _load_file(HISTORY_FILE)
42
- hist.append(entry)
43
- _save_file(HISTORY_FILE, hist)
44
 
45
  # ======================================================
46
- # SECURITY / LICENSING
47
  # ======================================================
 
 
 
 
48
 
49
- def validate_api_key(key: str) -> str:
50
- if key not in LICENSE_TIERS:
51
- raise ValueError("Invalid API key")
52
- return LICENSE_TIERS[key]
53
 
54
  # ======================================================
55
- # LIVE MARKET FEED (SAFE STUB)
56
  # ======================================================
57
-
58
- def fetch_live_market_price(commodity: str) -> float:
59
- """
60
- Stub for live feeds.
61
- Replace with exchange / data-provider API.
62
- """
63
- base_prices = {
64
- "Gold": 1000,
65
- "Iron Ore": 1200,
66
- "Crude Oil": 800
67
- }
68
- return base_prices.get(commodity, 1000)
69
 
70
  # ======================================================
71
- # CORE ECONOMIC ENGINE
72
  # ======================================================
73
-
74
- def harmonize_price(synthetic: float, physical: float, lag: float) -> Dict:
75
- correction = (synthetic - physical) * min(1.0, lag)
76
- harmonized = synthetic - correction
77
- confidence = 1.0 - abs(correction) / max(synthetic, 1.0)
78
-
79
- return {
80
- "synthetic_price": round(synthetic, 2),
81
- "harmonized_price": round(harmonized, 2),
82
- "correction": round(-correction, 2),
83
- "confidence": round(max(0.0, min(confidence, 1.0)), 2)
84
- }
85
-
86
- def accelerate_cashflow(amount: float, delay_days: int, confidence: float) -> float:
87
- base_rate = 0.03
88
- risk_adj = (1 - confidence) * 0.05
89
- rate = base_rate + risk_adj
90
- return round(amount / ((1 + rate) ** (delay_days / 365)), 2)
91
-
92
- def confidence_watermark(c: float) -> str:
93
- if c >= 0.9: return "AAA – High Confidence"
94
- if c >= 0.75: return "AA – Medium Confidence"
95
- return "A – Caution"
96
 
97
  # ======================================================
98
- # CODEX MESH INTEGRATION
99
  # ======================================================
100
-
101
- def codex_mesh_broadcast(payload: Dict):
102
- """
103
- Mesh-ready broadcast stub.
104
- Replace with real message bus / federation layer.
105
- """
106
- payload["mesh_id"] = f"mesh-{uuid.uuid4()}"
107
- payload["mesh_timestamp"] = datetime.utcnow().isoformat()
108
  return payload
109
 
110
  # ======================================================
111
- # MAIN RUNTIME
112
  # ======================================================
 
 
 
113
 
114
- def codexflow_execute(
115
- commodity: str,
116
- synthetic_price: float,
117
- physical_price: float,
118
- lag_days: int,
119
- api_key: str
120
- ) -> Dict:
121
 
122
- tier = validate_api_key(api_key)
 
 
 
 
 
 
 
123
 
124
- lag_factor = min(lag_days / 10, 1.0)
125
- harmonized = harmonize_price(synthetic_price, physical_price, lag_factor)
126
 
127
- accelerated = accelerate_cashflow(
128
- harmonized["harmonized_price"],
129
- lag_days,
130
- harmonized["confidence"]
131
- )
 
 
 
132
 
133
- result = {
134
- "engine": "CodexFlow ΩΞ",
135
- "tier": tier,
136
- "commodity": commodity,
137
- "timestamp": datetime.utcnow().isoformat(),
138
- "harmonized_state": harmonized,
139
- "accelerated_cashflow": accelerated,
140
- "confidence_watermark": confidence_watermark(harmonized["confidence"])
141
- }
142
 
143
- # Governance
144
- save_history(result)
145
- log_audit({
146
- "event": "execution",
147
- "tier": tier,
148
- "commodity": commodity,
149
- "time": result["timestamp"]
150
- })
151
 
152
- # Mesh propagation
153
- return codex_mesh_broadcast(result)
 
 
 
154
 
155
  # ======================================================
156
- # BATCH EXECUTION
157
  # ======================================================
 
 
 
 
 
 
158
 
159
- def codexflow_batch(
160
- commodities: List[str],
161
- lag_days: int,
162
- api_key: str
163
- ) -> List[Dict]:
164
 
165
- validate_api_key(api_key)
166
- outputs = []
167
 
168
- for c in commodities:
169
- synthetic = fetch_live_market_price(c)
170
- physical = synthetic * 0.95 # conservative anchor
171
- outputs.append(
172
- codexflow_execute(c, synthetic, physical, lag_days, api_key)
173
- )
174
 
175
- return outputs
 
 
 
176
 
177
- # ======================================================
178
- # INVESTOR DECK GENERATOR
179
- # ======================================================
180
-
181
- def generate_investor_deck() -> Dict:
182
- return {
183
- "CodexFlow": {
184
- "Problem": "Synthetic price distortion & cashflow delay",
185
- "Solution": "Reality-anchored harmonization + time compression",
186
- "Moat": "Trust, auditability, physical anchoring",
187
- "Revenue": [
188
- "Licensing tiers",
189
- "Transaction fees",
190
- "Institutional APIs"
191
- ],
192
- "Target Clients": [
193
- "Producers",
194
- "Banks",
195
- "Treasuries",
196
- "Exchanges"
197
- ]
198
- }
199
- }
200
 
201
  # ======================================================
202
- # UI
203
  # ======================================================
 
 
 
 
204
 
205
- with gr.Blocks() as demo:
206
- gr.Markdown("""
207
- # CodexFlow ΩΞ
208
- **Autonomous Reality-Anchored Cashflow Operating System**
209
- """)
210
-
211
- api_key = gr.Textbox(label="API Key", type="password")
212
-
213
- with gr.Tab("Single Run"):
214
- commodity = gr.Dropdown(["Gold", "Iron Ore", "Crude Oil"])
215
- synthetic_price = gr.Number(label="Synthetic Price")
216
- physical_price = gr.Number(label="Physical Anchor")
217
- lag = gr.Slider(0, 30, value=7, step=1)
218
- btn = gr.Button("Execute")
219
- out = gr.JSON()
220
-
221
- btn.click(
222
- codexflow_execute,
223
- inputs=[commodity, synthetic_price, physical_price, lag, api_key],
224
- outputs=out
225
- )
226
 
227
- with gr.Tab("Batch / Live Mode"):
228
- commodities = gr.CheckboxGroup(["Gold", "Iron Ore", "Crude Oil"])
229
- lag_b = gr.Slider(0, 30, value=7)
230
- batch_btn = gr.Button("Run Batch")
231
- batch_out = gr.JSON()
232
 
233
- batch_btn.click(
234
- codexflow_batch,
235
- inputs=[commodities, lag_b, api_key],
236
- outputs=batch_out
237
- )
 
 
 
 
 
 
 
 
 
 
 
 
238
 
239
- with gr.Tab("Investor Deck"):
240
- deck_btn = gr.Button("Generate Deck")
241
- deck_out = gr.JSON()
242
- deck_btn.click(generate_investor_deck, outputs=deck_out)
243
 
244
- with gr.Tab("Audit Log"):
245
- audit_btn = gr.Button("View Audit")
246
- audit_out = gr.JSON()
247
- audit_btn.click(lambda: _load_file(AUDIT_FILE), outputs=audit_out)
248
 
249
  # ======================================================
250
- # HUGGING FACE DEPLOY PATCH
251
  # ======================================================
252
-
253
- if __name__ == "__main__":
254
- demo.launch(
255
- server_name="0.0.0.0",
256
- server_port=7860,
257
- show_error=True,
258
- ssr_mode=False
259
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import os, json, time, uuid, hashlib, math, random
3
  from datetime import datetime
4
  from typing import Dict, List
 
 
 
5
 
6
  # ======================================================
7
+ # WHITE-LABEL / GLOBAL CONFIG
8
  # ======================================================
9
+ BRAND = os.getenv("CODEX_BRAND", "CodexFlow ΩΞ")
10
+ ORG = os.getenv("CODEX_ORG", "Codex Sovereign")
11
+ CCY = os.getenv("CODEX_CCY", "USD")
12
+ STATE_DIR = os.getenv("CODEX_STATE_DIR", "state")
13
+ os.makedirs(STATE_DIR, exist_ok=True)
14
 
15
+ # Files
16
+ HIST_F = f"{STATE_DIR}/history.json"
17
+ AUD_F = f"{STATE_DIR}/audit.json"
18
+ USE_F = f"{STATE_DIR}/usage.json"
19
+ GRF_F = f"{STATE_DIR}/causal_graph.json"
20
+ PROV_F = f"{STATE_DIR}/provenance.json"
21
+ STAT_F = f"{STATE_DIR}/system_state.json"
 
22
 
23
  # ======================================================
24
+ # RBAC / QUOTAS
25
  # ======================================================
26
+ API_KEYS = {
27
+ "DEMO_KEY": {"tier":"demo","quota":50},
28
+ "PRO_KEY": {"tier":"pro","quota":500},
29
+ "INSTITUTIONAL_KEY": {"tier":"institutional","quota":50000},
30
+ "SOVEREIGN_KEY": {"tier":"sovereign","quota":10**9},
31
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  # ======================================================
34
+ # STORAGE UTILS
35
  # ======================================================
36
+ def _load(p, d=None):
37
+ if os.path.exists(p):
38
+ with open(p,"r") as f: return json.load(f)
39
+ return [] if d is None else d
40
 
41
+ def _save(p, data, lim=5000):
42
+ with open(p,"w") as f: json.dump(data[-lim:], f, indent=2)
 
 
43
 
44
  # ======================================================
45
+ # SECURITY / RBAC
46
  # ======================================================
47
+ def _use_key(k):
48
+ if k not in API_KEYS: raise ValueError("Invalid API key")
49
+ usage=_load(USE_F,[])
50
+ if sum(1 for u in usage if u["k"]==k)>=API_KEYS[k]["quota"]:
51
+ raise ValueError("Quota exceeded")
52
+ usage.append({"k":k,"t":time.time()}); _save(USE_F,usage)
53
+ return API_KEYS[k]["tier"]
 
 
 
 
 
54
 
55
  # ======================================================
56
+ # CRYPTO PROVENANCE (HASH-CHAIN)
57
  # ======================================================
58
+ def _h(obj): return hashlib.sha256(json.dumps(obj,sort_keys=True).encode()).hexdigest()
59
+ def attest(payload):
60
+ prov=_load(PROV_F,[])
61
+ prev=prov[-1]["hash"] if prov else "GENESIS"
62
+ att={"id":str(uuid.uuid4()),"time":datetime.utcnow().isoformat(),
63
+ "prev":prev,"hash":_h({**payload,"prev":prev})}
64
+ prov.append(att); _save(PROV_F,prov)
65
+ payload["provenance"]=att; return payload
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  # ======================================================
68
+ # MESH / FEDERATION (HOOKS)
69
  # ======================================================
70
+ def mesh_node(): return hashlib.sha256(os.getenv("HOSTNAME","codex-node").encode()).hexdigest()[:16]
71
+ def mesh_broadcast(payload):
72
+ payload["mesh"]={"node":mesh_node(),"msg":str(uuid.uuid4()),
73
+ "time":datetime.utcnow().isoformat()}
74
+ # hook: Kafka/Pulsar/Webhook
 
 
 
75
  return payload
76
 
77
  # ======================================================
78
+ # DATA ADAPTERS
79
  # ======================================================
80
+ def exchange_price(commodity):
81
+ base={"Gold":1000,"Iron Ore":1200,"Crude Oil":800}
82
+ return round(base.get(commodity,1000)+random.uniform(-6,6),2)
83
 
84
+ def producer_state(commodity):
85
+ return {"commodity":commodity,
86
+ "output_tpd":random.randint(8000,15000),
87
+ "inventory_t":random.randint(20000,60000),
88
+ "logistics":random.choice(["normal","tight"]),
89
+ "energy":random.choice(["stable","volatile"])}
 
90
 
91
+ # ======================================================
92
+ # CAUSAL GRAPH + ANOMALY
93
+ # ======================================================
94
+ def update_graph(commodity, distortion, lag):
95
+ g=_load(GRF_F,[])
96
+ g.append({"c":commodity,"d":distortion,"lag":lag,
97
+ "t":datetime.utcnow().isoformat()})
98
+ _save(GRF_F,g)
99
 
100
+ def is_anomaly(dist): return abs(dist)>0.15
 
101
 
102
+ # ======================================================
103
+ # AUTONOMOUS MATHEMATICAL LOGIC
104
+ # ======================================================
105
+ # State evolves via a stabilizing gradient flow:
106
+ # x_{t+1} = x_t - η ∇E(x_t)
107
+ # Energy E penalizes distortion, lag, and low confidence.
108
+ def _state():
109
+ return _load(STAT_F, {"eta":0.2,"bias":0.0})
110
 
111
+ def _save_state(s): _save(STAT_F,[s],lim=1)
 
 
 
 
 
 
 
 
112
 
113
+ def energy(dist, lag, conf):
114
+ return (dist**2) + 0.01*(lag**2) + (1-conf)**2
 
 
 
 
 
 
115
 
116
+ def update_state(dist, lag, conf):
117
+ s=_state()
118
+ grad = 2*dist + 0.02*lag - 2*(1-conf)
119
+ s["bias"] = max(-0.2, min(0.2, s["bias"] - s["eta"]*grad))
120
+ _save_state(s); return s
121
 
122
  # ======================================================
123
+ # ECONOMIC CORE
124
  # ======================================================
125
+ def harmonize(synth, phys, lag):
126
+ lagf=min(lag/10,1.0)
127
+ corr=(synth-phys)*lagf
128
+ harm=synth-corr
129
+ conf=max(0.0,1-abs(corr)/max(synth,1.0))
130
+ return round(harm,2), round(-corr,2), round(conf,2)
131
 
132
+ def accelerate(val, lag, conf):
133
+ r=0.03+(1-conf)*0.05
134
+ return round(val/((1+r)**(lag/365)),2)
 
 
135
 
136
+ def grade(conf): return "AAA" if conf>=0.9 else "AA" if conf>=0.75 else "A"
 
137
 
138
+ def scenarios(base):
139
+ return {"optimistic":round(base*1.05,2),
140
+ "baseline":round(base,2),
141
+ "stress":round(base*0.9,2)}
 
 
142
 
143
+ def treasury_controls(tier, conf):
144
+ if tier=="sovereign":
145
+ return {"gate":"open","policy_cap":"sovereign","floor":0.7}
146
+ return {"gate":"market","policy_cap":tier,"floor":0.75 if tier!="demo" else 0.8}
147
 
148
+ def regulatory(entry):
149
+ return {"engine":BRAND,"org":ORG,"time":entry["timestamp"],
150
+ "commodity":entry["commodity"],
151
+ "harmonized_price":entry["harmonized_price"],
152
+ "confidence":entry["confidence"],
153
+ "mesh_node":entry["mesh"]["node"],
154
+ "prov_hash":entry["provenance"]["hash"]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
 
156
  # ======================================================
157
+ # MAIN RUNTIME (AUTONOMOUS)
158
  # ======================================================
159
+ def run(commodity, physical_anchor, lag_days, api_key, use_live):
160
+ tier=_use_key(api_key)
161
+ synth=exchange_price(commodity) if use_live else round(physical_anchor*1.05,2)
162
+ prod=producer_state(commodity)
163
 
164
+ harm, dist, conf = harmonize(synth, physical_anchor, lag_days)
165
+ # autonomous bias correction
166
+ st=update_state(abs(dist), lag_days, conf)
167
+ harm=round(harm*(1+st["bias"]),2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
+ accel=accelerate(harm, lag_days, conf)
170
+ update_graph(commodity, dist, lag_days)
 
 
 
171
 
172
+ res={
173
+ "engine":BRAND,"org":ORG,"tier":tier,"ccy":CCY,
174
+ "timestamp":datetime.utcnow().isoformat(),
175
+ "commodity":commodity,
176
+ "synthetic_price":synth,
177
+ "physical_anchor":physical_anchor,
178
+ "harmonized_price":harm,
179
+ "distortion":dist,
180
+ "confidence":conf,
181
+ "grade":grade(conf),
182
+ "accelerated_cashflow":accel,
183
+ "anomaly":is_anomaly(dist),
184
+ "producer":prod,
185
+ "scenarios":scenarios(harm),
186
+ "treasury":treasury_controls(tier,conf),
187
+ "state":st
188
+ }
189
 
190
+ hist=_load(HIST_F,[]); hist.append(res); _save(HIST_F,hist)
191
+ aud=_load(AUD_F,[]); aud.append(res); _save(AUD_F,aud)
 
 
192
 
193
+ res=mesh_broadcast(res)
194
+ res=attest(res)
195
+ res["regulatory_export"]=regulatory(res)
196
+ return res
197
 
198
  # ======================================================
199
+ # UI (HF SPACES)
200
  # ======================================================
201
+ with gr.Blocks() as demo:
202
+ gr.Markdown(f"# {BRAND}\n**Autonomous Economic Reflex OS**")
203
+ api=gr.Textbox(label="API Key", type="password")
204
+ com=gr.Dropdown(["Gold","Iron Ore","Crude Oil"], label="Commodity")
205
+ phys=gr.Number(950, label="Physical Anchor")
206
+ lag=gr.Slider(0,30,7,1,label="Reporting Lag (Days)")
207
+ live=gr.Checkbox(True,label="Use Live Exchange Feed")
208
+ btn=gr.Button("Execute"); out=gr.JSON()
209
+ btn.click(run, inputs=[com,phys,lag,api,live], outputs=out)
210
+
211
+ with gr.Tab("Audit"):
212
+ gr.Button("Load").click(lambda:_load(AUD_F,[]), outputs=gr.JSON())
213
+ with gr.Tab("Causal Graph"):
214
+ gr.Button("Load").click(lambda:_load(GRF_F,[]), outputs=gr.JSON())
215
+ with gr.Tab("Provenance"):
216
+ gr.Button("Load").click(lambda:_load(PROV_F,[]), outputs=gr.JSON())
217
+
218
+ # ======================================================
219
+ # HF DEPLOY PATCH
220
+ # ======================================================
221
+ if __name__=="__main__":
222
+ demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True, ssr_mode=False)