LordXido commited on
Commit
eb17519
·
verified ·
1 Parent(s): 526154c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +173 -95
app.py CHANGED
@@ -1,23 +1,23 @@
1
  import gradio as gr
2
  import requests
3
  import time
4
- import hashlib
5
  import json
 
6
  import random
 
7
 
8
  # ======================================================
9
- # GLOBAL MEMORY
10
  # ======================================================
11
 
12
- CHAT_MEMORY = []
13
- LAST_STATE = {}
14
 
15
  # ======================================================
16
- # PUBLIC MACRO DATA (WORLD BANK)
17
  # ======================================================
18
 
19
  WORLD_BANK_BASE = "https://api.worldbank.org/v2"
20
-
21
  INDICATORS = {
22
  "GDP": "NY.GDP.MKTP.CD",
23
  "INFLATION": "FP.CPI.TOTL.ZG",
@@ -38,160 +38,238 @@ def fetch_indicator(indicator, country="WLD", year="2022"):
38
  def fetch_macro_anchor(country="WLD"):
39
  return {
40
  "country": country,
41
- "global_gdp": fetch_indicator(INDICATORS["GDP"], country),
42
  "inflation": fetch_indicator(INDICATORS["INFLATION"], country),
43
  "population": fetch_indicator(INDICATORS["POPULATION"], country),
44
- "timestamp": time.time(),
45
  }
46
 
47
  # ======================================================
48
- # ECONOMIC ENGINE
49
  # ======================================================
50
 
51
- def economic_kernel(commodity, anchor, macro):
52
- gdp_scale = macro["global_gdp"] / 1e14 if macro["global_gdp"] else 1.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  supply = anchor * gdp_scale
54
  demand = supply * 0.95
55
- price_index = round((supply / 10) * gdp_scale, 2)
56
-
57
  return {
 
58
  "commodity": commodity,
59
- "supply": round(supply, 2),
60
- "demand": round(demand, 2),
61
  "price_index": price_index,
62
- "currency_flow": round(demand * price_index, 2),
63
  }
64
 
65
- def logistics_engine(econ):
66
- friction = abs(econ["supply"] - econ["demand"]) / max(econ["supply"], 1)
67
  return {
68
- "throughput": round(econ["supply"] * (1 - friction), 2),
69
- "friction": round(friction, 4),
 
70
  }
71
 
72
- def energy_engine(econ):
73
  return {
74
- "energy_cost_index": round(econ["price_index"] * 0.4, 2),
75
- "energy_dependency": (
76
- "high" if econ["commodity"].lower() in ["oil", "gas"] else "moderate"
77
- ),
78
  }
79
 
80
- def sentiment_engine(commodity):
81
- random.seed(sum(ord(c) for c in commodity))
82
  confidence = random.uniform(0.6, 0.9)
83
  return {
84
- "market_confidence": round(confidence, 3),
 
85
  "risk_bias": "neutral" if confidence > 0.7 else "risk_off",
86
  }
87
 
88
- def analytics_engine(econ, logistics, sentiment, lag):
89
  projected_price = econ["price_index"] * (
90
- 1 + (1 - sentiment["market_confidence"]) * 0.08 - logistics["friction"] * 0.1
91
  )
92
  return {
93
- "projected_price": round(projected_price, 2),
94
- "lag_days": lag,
 
 
95
  }
96
 
97
  # ======================================================
98
- # Ω-PROOF
99
  # ======================================================
100
 
101
- def omega_proof(state):
102
- return hashlib.sha256(json.dumps(state, sort_keys=True).encode()).hexdigest()
 
 
 
 
 
 
 
 
 
 
 
103
 
104
- # ======================================================
105
- # MASTER RUN
106
- # ======================================================
107
 
108
- def run_codexflow(commodity, anchor, lag, country, live):
109
- macro = fetch_macro_anchor(country) if live else {
110
- "country": country,
111
- "global_gdp": None,
112
- "inflation": None,
113
- "population": None,
114
- "timestamp": time.time(),
115
- }
116
 
117
- econ = economic_kernel(commodity, anchor, macro)
118
- logistics = logistics_engine(econ)
119
- energy = energy_engine(econ)
120
- sentiment = sentiment_engine(commodity)
121
- projection = analytics_engine(econ, logistics, sentiment, lag)
122
-
123
- state = {
124
- "macro": macro,
125
- "economy": econ,
126
- "logistics": logistics,
127
- "energy": energy,
128
- "sentiment": sentiment,
129
- "projection": projection,
130
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
- proof = omega_proof(state)
133
-
134
- global LAST_STATE
135
- LAST_STATE = state
 
 
 
136
 
137
- return state, proof
 
 
138
 
139
  # ======================================================
140
- # JARVIS X CHAT
141
  # ======================================================
142
 
143
- def jarvis_x_chat(message, history):
144
- CHAT_MEMORY.append(message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
- m = message.lower()
147
- if "state" in m:
148
- return json.dumps(LAST_STATE, indent=2) if LAST_STATE else "No state yet."
149
- if "proof" in m:
150
- return "Ω-Proof secures the current economic state deterministically."
151
  if "what is this" in m:
152
- return "CodexFlow ΩΞ is an executable economic world simulation engine."
153
- if "memory" in m:
154
- return f"I retain {len(CHAT_MEMORY)} interaction steps."
 
 
155
 
156
- return "Jarvis X acknowledged. Ask about system state, projections, or design."
157
 
158
  # ======================================================
159
  # GRADIO UI (HF SAFE)
160
  # ======================================================
161
 
162
  with gr.Blocks() as app:
163
- gr.Markdown("# 🌍 CodexFlow ΩΞ")
164
- gr.Markdown("**Economic World Engine + Jarvis X Interface**")
165
 
166
  with gr.Row():
167
  with gr.Column(scale=2):
168
- commodity = gr.Dropdown(
169
- ["Gold", "Oil", "Gas", "Wheat", "Copper"],
170
- value="Gold",
171
- label="Commodity"
172
- )
173
  anchor = gr.Number(value=950, label="Physical Anchor")
 
174
  lag = gr.Slider(1, 365, value=7, step=1, label="Reporting Lag (days)")
175
- country = gr.Textbox(value="WLD", label="Country Code")
176
- live = gr.Checkbox(value=True, label="Use Live Public Data")
177
 
178
- run = gr.Button("Execute CodexFlow")
179
 
180
- state_out = gr.JSON(label="Economic State")
181
- proof_out = gr.Textbox(label="Ω-Proof")
182
 
183
- run.click(
184
- run_codexflow,
185
- inputs=[commodity, anchor, lag, country, live],
186
- outputs=[state_out, proof_out],
187
  )
188
 
 
 
 
 
 
 
189
  with gr.Column(scale=1):
190
- gr.Markdown("## 🧠 Jarvis X")
191
- gr.ChatInterface(fn=jarvis_x_chat, height=420)
192
 
193
  gr.Markdown(
194
- "_Simulation only. No trading, enforcement, or private systems._"
 
195
  )
196
 
197
  app.launch()
 
1
  import gradio as gr
2
  import requests
3
  import time
 
4
  import json
5
+ import hashlib
6
  import random
7
+ from typing import Dict, Any, List
8
 
9
  # ======================================================
10
+ # GLOBAL LEDGER (in-memory for HF; can persist later)
11
  # ======================================================
12
 
13
+ LEDGER: List[Dict[str, Any]] = []
14
+ CHAT_MEMORY: List[str] = []
15
 
16
  # ======================================================
17
+ # PUBLIC MACRO DATA (World Bank)
18
  # ======================================================
19
 
20
  WORLD_BANK_BASE = "https://api.worldbank.org/v2"
 
21
  INDICATORS = {
22
  "GDP": "NY.GDP.MKTP.CD",
23
  "INFLATION": "FP.CPI.TOTL.ZG",
 
38
  def fetch_macro_anchor(country="WLD"):
39
  return {
40
  "country": country,
41
+ "gdp": fetch_indicator(INDICATORS["GDP"], country),
42
  "inflation": fetch_indicator(INDICATORS["INFLATION"], country),
43
  "population": fetch_indicator(INDICATORS["POPULATION"], country),
 
44
  }
45
 
46
  # ======================================================
47
+ # BIT + METADATA LAYER
48
  # ======================================================
49
 
50
+ def canonical_bytes(obj: Any) -> bytes:
51
+ return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()
52
+
53
+ def bit_stats(payload: Dict[str, Any]) -> Dict[str, Any]:
54
+ b = canonical_bytes(payload)
55
+ return {
56
+ "bytes": len(b),
57
+ "bits": len(b) * 8,
58
+ "symbol_diversity": len(set(b)),
59
+ "entropy_proxy": round(len(set(b)) / max(len(b), 1), 6)
60
+ }
61
+
62
+ def hash_payload(payload: Dict[str, Any], prev_hash: str) -> str:
63
+ b = canonical_bytes({"payload": payload, "prev_hash": prev_hash})
64
+ return hashlib.sha256(b).hexdigest()
65
+
66
+ def reliability_score(source: str, latency_s: float) -> float:
67
+ # simple, explainable scoring model (can be replaced with learned model)
68
+ base = 0.85 if source == "world_bank" else 0.65
69
+ penalty = min(0.25, latency_s / 20.0)
70
+ return round(max(0.1, base - penalty), 3)
71
+
72
+ # ======================================================
73
+ # SIGNAL GENERATORS (global “bit rails”)
74
+ # ======================================================
75
+
76
+ def commodity_signal(commodity: str, anchor: float, macro: Dict[str, Any]) -> Dict[str, Any]:
77
+ gdp_scale = (macro["gdp"] / 1e14) if macro.get("gdp") else 1.0
78
  supply = anchor * gdp_scale
79
  demand = supply * 0.95
80
+ price_index = round((supply / 10.0) * gdp_scale, 4)
 
81
  return {
82
+ "type": "commodity",
83
  "commodity": commodity,
84
+ "supply": round(supply, 4),
85
+ "demand": round(demand, 4),
86
  "price_index": price_index,
87
+ "currency_flow": round(demand * price_index, 4),
88
  }
89
 
90
+ def logistics_signal(econ: Dict[str, Any]) -> Dict[str, Any]:
91
+ friction = abs(econ["supply"] - econ["demand"]) / max(econ["supply"], 1e-9)
92
  return {
93
+ "type": "logistics",
94
+ "throughput": round(econ["supply"] * (1 - friction), 4),
95
+ "friction": round(friction, 6),
96
  }
97
 
98
+ def energy_signal(econ: Dict[str, Any]) -> Dict[str, Any]:
99
  return {
100
+ "type": "energy",
101
+ "energy_cost_index": round(econ["price_index"] * 0.4, 4),
102
+ "dependency": "high" if econ["commodity"].lower() in ["oil", "gas"] else "moderate",
 
103
  }
104
 
105
+ def sentiment_signal(seed_key: str) -> Dict[str, Any]:
106
+ random.seed(sum(ord(c) for c in seed_key))
107
  confidence = random.uniform(0.6, 0.9)
108
  return {
109
+ "type": "sentiment",
110
+ "market_confidence": round(confidence, 6),
111
  "risk_bias": "neutral" if confidence > 0.7 else "risk_off",
112
  }
113
 
114
+ def derived_features(econ, logi, energy, sent, lag_days: int) -> Dict[str, Any]:
115
  projected_price = econ["price_index"] * (
116
+ 1 + (1 - sent["market_confidence"]) * 0.08 - logi["friction"] * 0.1
117
  )
118
  return {
119
+ "type": "features",
120
+ "lag_days": lag_days,
121
+ "projected_price": round(projected_price, 6),
122
+ "volatility_proxy": round(0.015 * lag_days, 6),
123
  }
124
 
125
  # ======================================================
126
+ # LEDGER APPEND (global bit+metadata record)
127
  # ======================================================
128
 
129
+ def append_record(payload: Dict[str, Any], meta: Dict[str, Any]) -> Dict[str, Any]:
130
+ prev = LEDGER[-1]["hash"] if LEDGER else "GENESIS"
131
+ h = hash_payload(payload, prev)
132
+ record = {
133
+ "hash": h,
134
+ "prev_hash": prev,
135
+ "payload": payload,
136
+ "metadata": meta,
137
+ "bit_stats": bit_stats(payload),
138
+ "ts": time.time(),
139
+ }
140
+ LEDGER.append(record)
141
+ return record
142
 
143
+ def run_tick(commodity: str, anchor: float, country: str, lag_days: int, use_live: bool):
144
+ t0 = time.time()
 
145
 
146
+ macro = fetch_macro_anchor(country) if use_live else {"country": country, "gdp": None, "inflation": None, "population": None}
147
+ latency = time.time() - t0
 
 
 
 
 
 
148
 
149
+ # 1) macro record
150
+ meta_macro = {
151
+ "source": "world_bank" if use_live else "synthetic",
152
+ "country": country,
153
+ "latency_s": round(latency, 4),
154
+ "reliability": reliability_score("world_bank" if use_live else "synthetic", latency),
155
+ "schema": "macro.v1",
 
 
 
 
 
 
156
  }
157
+ append_record({"type": "macro", **macro}, meta_macro)
158
+
159
+ # 2) derived signals
160
+ econ = commodity_signal(commodity, anchor, macro)
161
+ logi = logistics_signal(econ)
162
+ ener = energy_signal(econ)
163
+ sent = sentiment_signal(commodity + country)
164
+ feat = derived_features(econ, logi, ener, sent, lag_days)
165
+
166
+ for payload, schema in [
167
+ (econ, "commodity.v1"),
168
+ (logi, "logistics.v1"),
169
+ (ener, "energy.v1"),
170
+ (sent, "sentiment.v1"),
171
+ (feat, "features.v1"),
172
+ ]:
173
+ meta = {
174
+ "source": "derived",
175
+ "country": country,
176
+ "latency_s": 0.0,
177
+ "reliability": 0.9,
178
+ "schema": schema,
179
+ }
180
+ append_record(payload, meta)
181
 
182
+ return {
183
+ "status": "tick_ok",
184
+ "ledger_len": len(LEDGER),
185
+ "tip_hash": LEDGER[-1]["hash"],
186
+ "latest_macro": macro,
187
+ "latest_features": feat,
188
+ }, LEDGER[-1]["hash"]
189
 
190
+ def query_ledger(n: int):
191
+ n = max(1, min(int(n), 200))
192
+ return LEDGER[-n:]
193
 
194
  # ======================================================
195
+ # CHAT INTERFACE (queries the ledger)
196
  # ======================================================
197
 
198
+ def jarvis_chat(msg, history):
199
+ CHAT_MEMORY.append(msg)
200
+ m = msg.lower().strip()
201
+
202
+ if "latest" in m or "tip" in m:
203
+ if not LEDGER:
204
+ return "Ledger is empty. Run a tick first."
205
+ r = LEDGER[-1]
206
+ return json.dumps({"tip_hash": r["hash"], "payload": r["payload"], "metadata": r["metadata"]}, indent=2)
207
+
208
+ if "ledger" in m or "records" in m:
209
+ return f"Ledger records: {len(LEDGER)}. Ask 'latest' or 'show last 10'."
210
+
211
+ if "show last" in m:
212
+ try:
213
+ k = int(m.split("show last")[-1].strip())
214
+ except Exception:
215
+ k = 10
216
+ data = query_ledger(k)
217
+ return json.dumps(data, indent=2)
218
+
219
+ if "proof" in m or "hash" in m:
220
+ if not LEDGER:
221
+ return "No proof yet. Run a tick to generate chained hashes."
222
+ return f"Tip hash: {LEDGER[-1]['hash']} (prev: {LEDGER[-1]['prev_hash']})"
223
 
 
 
 
 
 
224
  if "what is this" in m:
225
+ return (
226
+ "This is GVBDMS v1: a Global Virtual Bit + Metadata Ledger. "
227
+ "It ingests public anchors, derives signals, stores payload+metadata, "
228
+ "and chains records with hashes for tamper-evident provenance."
229
+ )
230
 
231
+ return "Ask: 'latest', 'proof', 'show last 10', or run a tick to ingest data."
232
 
233
  # ======================================================
234
  # GRADIO UI (HF SAFE)
235
  # ======================================================
236
 
237
  with gr.Blocks() as app:
238
+ gr.Markdown("# 🌐 CodexFlow — Global Virtual Bit + Metadata System (GVBDMS v1)")
239
+ gr.Markdown("A byte-verifiable, provenance-tracked ledger for global economic signals.")
240
 
241
  with gr.Row():
242
  with gr.Column(scale=2):
243
+ commodity = gr.Dropdown(["Gold","Oil","Gas","Wheat","Copper"], value="Gold", label="Commodity")
 
 
 
 
244
  anchor = gr.Number(value=950, label="Physical Anchor")
245
+ country = gr.Textbox(value="WLD", label="Country Code (WLD/USA/CHN/ZAF...)")
246
  lag = gr.Slider(1, 365, value=7, step=1, label="Reporting Lag (days)")
247
+ live = gr.Checkbox(value=True, label="Use Live World Bank Anchors")
 
248
 
249
+ run_btn = gr.Button("Run Tick (Ingest + Derive + Ledger Append)")
250
 
251
+ tick_out = gr.JSON(label="Tick Result")
252
+ tip_hash = gr.Textbox(label="Tip Hash")
253
 
254
+ run_btn.click(
255
+ fn=run_tick,
256
+ inputs=[commodity, anchor, country, lag, live],
257
+ outputs=[tick_out, tip_hash],
258
  )
259
 
260
+ n = gr.Slider(1, 200, value=20, step=1, label="Query last N records")
261
+ q_btn = gr.Button("Query Ledger")
262
+ ledger_out = gr.JSON(label="Ledger Records (last N)")
263
+
264
+ q_btn.click(fn=query_ledger, inputs=[n], outputs=[ledger_out])
265
+
266
  with gr.Column(scale=1):
267
+ gr.Markdown("## 🧠 Jarvis X — Ledger Interface")
268
+ gr.ChatInterface(fn=jarvis_chat, height=420)
269
 
270
  gr.Markdown(
271
+ "_GVBDMS stores public/derived signals with metadata & hash chaining. "
272
+ "It is not a trading system, bank interface, or contract enforcer._"
273
  )
274
 
275
  app.launch()