MetaCortex-Dynamics commited on
Commit
7323aa9
Β·
verified Β·
1 Parent(s): c82b9e6

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +116 -58
app.py CHANGED
@@ -1,11 +1,10 @@
1
  """
2
  Axiom β€” HuggingFace Space / Gradio App
3
 
4
- Two modes:
5
- 1. GENERATE β€” produce governed output with proof
6
- 2. VERIFY β€” submit output + trace, get pass/fail
7
-
8
- The verifier is the product demo. The proof is the point.
9
  """
10
 
11
  import sys
@@ -56,27 +55,23 @@ decoder.eval()
56
 
57
 
58
  # ═══════════════════════════════════════════════════════════════════════════════
59
- # TAB 1: GENERATE
60
  # ═══════════════════════════════════════════════════════════════════════════════
61
 
62
- def generate_governed(num_candidates=10, temperature=0.7):
63
- """Run the full 4-phase governed pipeline. Returns (prose, trace_panel, trace_json)."""
64
-
65
- candidates = propose(mdlm, num_candidates=int(num_candidates), g_slots=2, s_slots=2, f_slots=2)
66
  decided = decide(candidates)
67
- t_count = sum(1 for _, d, _ in decided if d.tig_status == "T")
68
- f_count = sum(1 for _, d, _ in decided if d.tig_status == "F")
69
  admitted = [(c, d, e) for c, d, e in decided if d.tig_status == "T" and e is not None]
70
  promoted = promote(admitted)
71
 
72
  if not promoted:
73
- return "No candidates passed governance.", "", "{}"
74
 
75
  outputs = execute(promoted)
76
  example, commitment = promoted[0]
77
  gov_dict = outputs[0].gov_structure
78
 
79
- # Generate prose
80
  tt = torch.tensor([pad_gov(encode_gov({
81
  "channel_a": {"operators": gov_dict["G"]},
82
  "channel_b": {"operators": gov_dict["S"]},
@@ -114,22 +109,70 @@ def generate_governed(num_candidates=10, temperature=0.7):
114
  "gates_passed": 7,
115
  "witnesses": {w: {"attested": d["attested"]} for w, d in commitment.witnesses.items()},
116
  "commitment": commitment.witness_bundle_hash,
117
- "admission": f"{t_count}/{int(num_candidates)}",
118
  "timestamp": datetime.now(timezone.utc).isoformat(),
119
  }
120
 
121
- # Build panel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  gate_names = ["G1 Structural Integrity", "G2 Completeness", "G3 Witness Sufficiency",
123
  "G4 Authority Separation", "G5 Provenance Continuity",
124
  "G6 Semantic Stability", "G7 Behavioral Prediction"]
125
  gate_html = "".join(f'<div style="padding:3px 0"><span style="color:#4ade80;font-weight:bold">PASS</span> {g}</div>' for g in gate_names)
126
  wit_html = "".join(
127
- f'<div style="padding:2px 0"><span style="color:{"#4ade80" if d["attested"] else "#e94560"};font-weight:bold">{"ATTESTED" if d["attested"] else "WITHHELD"}</span> {w}</div>'
128
- for w, d in commitment.witnesses.items()
129
  )
130
 
131
  panel = f"""<div style="font-family:monospace;font-size:12px">
132
- <div style="margin-bottom:8px"><span style="color:#888">PIPELINE</span> Proposed: {int(num_candidates)} | Admitted: {t_count} | Rejected: {f_count}</div>
133
  <div style="margin-bottom:8px"><span style="color:#888">GATES</span>{gate_html}</div>
134
  <div style="margin-bottom:8px"><span style="color:#888">WITNESSES</span>{wit_html}</div>
135
  <div><span style="color:#888">COMMITMENT</span><div style="word-break:break-all;color:#555;font-size:10px">{commitment.witness_bundle_hash}</div>
@@ -140,7 +183,7 @@ def generate_governed(num_candidates=10, temperature=0.7):
140
 
141
 
142
  # ═══════════════════════════════════════════════════════════════════════════════
143
- # TAB 2: VERIFY
144
  # ═══════════════════════════════════════════════════════════════════════════════
145
 
146
  def verify_governance(output_text, trace_json_str):
@@ -153,72 +196,53 @@ def verify_governance(output_text, trace_json_str):
153
  checks = []
154
  all_pass = True
155
 
156
- # Check 1: Output hash matches
157
  claimed_hash = trace.get("output_hash", "")
158
  actual_hash = sha256(output_text.encode()).hexdigest()
159
  hash_match = claimed_hash == actual_hash
160
- if not hash_match:
161
- all_pass = False
162
  checks.append(("Output hash integrity", hash_match,
163
  f"Claimed: {claimed_hash[:24]}...<br>Computed: {actual_hash[:24]}..."))
164
 
165
- # Check 2: Structure present and complete
166
  gov = trace.get("gov_structure", {})
167
- has_g = bool(gov.get("G"))
168
- has_s = bool(gov.get("S"))
169
- has_f = bool(gov.get("F"))
170
- complete = has_g and has_s and has_f
171
- if not complete:
172
- all_pass = False
173
  checks.append(("Structure completeness", complete,
174
- f"G: {'present' if has_g else 'MISSING'} | S: {'present' if has_s else 'MISSING'} | F: {'present' if has_f else 'MISSING'}"))
175
 
176
- # Check 3: All 7 gates claimed passed
177
  gates = trace.get("gates_passed", 0)
178
  gates_ok = gates == 7
179
- if not gates_ok:
180
- all_pass = False
181
  checks.append(("Gates passed (7 required)", gates_ok, f"{gates}/7"))
182
 
183
- # Check 4: All 7 witnesses attested
184
  witnesses = trace.get("witnesses", {})
185
  attested_count = sum(1 for w in witnesses.values() if w.get("attested"))
186
- total_witnesses = len(witnesses)
187
- wit_ok = attested_count == 7 and total_witnesses == 7
188
- if not wit_ok:
189
- all_pass = False
190
- checks.append(("Witness unanimity (7/7)", wit_ok, f"{attested_count}/{total_witnesses} attested"))
191
 
192
- # Check 5: Commitment hash present
193
  commitment = trace.get("commitment", "")
194
  commit_ok = len(commitment) >= 32
195
- if not commit_ok:
196
- all_pass = False
197
  checks.append(("Commitment hash present", commit_ok,
198
  f"{commitment[:32]}..." if commitment else "MISSING"))
199
 
200
- # Check 6: Operators are valid
201
  all_ops = (gov.get("G", []) + gov.get("S", []) + gov.get("F", []))
202
  valid_op_names = {TOKEN_NAMES[i] for i in range(OP_OFFSET, OP_OFFSET + 15)}
203
  invalid_ops = [op for op in all_ops if op not in valid_op_names]
204
  ops_ok = len(invalid_ops) == 0 and len(all_ops) > 0
205
- if not ops_ok:
206
- all_pass = False
207
  checks.append(("Valid operators only", ops_ok,
208
- f"{len(all_ops)} operators, {len(invalid_ops)} invalid" + (f": {invalid_ops}" if invalid_ops else "")))
209
 
210
- # Check 7: Timestamp present and parseable
211
  ts = trace.get("timestamp", "")
212
  try:
213
  datetime.fromisoformat(ts.replace("Z", "+00:00"))
214
  ts_ok = True
215
  except (ValueError, AttributeError):
216
  ts_ok = False
217
- if not ts_ok:
218
- all_pass = False
219
  checks.append(("Timestamp valid", ts_ok, ts if ts else "MISSING"))
220
 
221
- # Build result HTML
222
  verdict_color = "#4ade80" if all_pass else "#e94560"
223
  verdict_text = "GOVERNANCE VERIFIED" if all_pass else "VERIFICATION FAILED"
224
 
@@ -234,9 +258,6 @@ def verify_governance(output_text, trace_json_str):
234
  {verdict_text}
235
  </div>
236
  <table style="width:100%;border-collapse:collapse">{rows}</table>
237
- <div style="margin-top:16px;color:#555;font-size:11px;text-align:center">
238
- 7 checks performed. All must pass for governance verification.
239
- </div>
240
  </div>
241
  """
242
 
@@ -257,7 +278,44 @@ with gr.Blocks(
257
 
258
  with gr.Tabs():
259
 
260
- # ── Tab 1: Generate ──
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  with gr.Tab("Generate"):
262
  gr.Markdown("Generate governed output with a machine-verifiable governance trace.")
263
 
@@ -271,7 +329,7 @@ with gr.Blocks(
271
 
272
  with gr.Column(scale=1):
273
  governance_panel = gr.HTML(label="Governance")
274
- trace_json = gr.Code(label="Trace (JSON) β€” copy this to verify", language="json", lines=12)
275
 
276
  generate_btn.click(
277
  fn=generate_governed,
@@ -279,12 +337,12 @@ with gr.Blocks(
279
  outputs=[output_prose, governance_panel, trace_json],
280
  )
281
 
282
- # ── Tab 2: Verify ──
283
  with gr.Tab("Verify"):
284
  gr.Markdown("""
285
  **Submit any output + its governance trace. Get pass or fail.**
286
 
287
- Paste the generated output and the JSON trace from the Generate tab (or from any Axiom model).
288
  The verifier checks 7 governance conditions. All must pass.
289
  """)
290
 
 
1
  """
2
  Axiom β€” HuggingFace Space / Gradio App
3
 
4
+ Three modes:
5
+ 1. CHAT β€” talk to Axiom, every response governed with visible trace
6
+ 2. GENERATE β€” produce governed output with proof
7
+ 3. VERIFY β€” submit output + trace, get pass/fail
 
8
  """
9
 
10
  import sys
 
55
 
56
 
57
  # ═══════════════════════════════════════════════════════════════════════════════
58
+ # CORE: Generate governed prose from a committed structure
59
  # ═══════════════════════════════════════════════════════════════════════════════
60
 
61
+ def _generate_one(temperature=0.7):
62
+ """Run full 4-phase pipeline, return (prose, trace_dict, gov_dict, commitment)."""
63
+ candidates = propose(mdlm, num_candidates=1, g_slots=2, s_slots=2, f_slots=2)
 
64
  decided = decide(candidates)
 
 
65
  admitted = [(c, d, e) for c, d, e in decided if d.tig_status == "T" and e is not None]
66
  promoted = promote(admitted)
67
 
68
  if not promoted:
69
+ return None, None, None, None
70
 
71
  outputs = execute(promoted)
72
  example, commitment = promoted[0]
73
  gov_dict = outputs[0].gov_structure
74
 
 
75
  tt = torch.tensor([pad_gov(encode_gov({
76
  "channel_a": {"operators": gov_dict["G"]},
77
  "channel_b": {"operators": gov_dict["S"]},
 
109
  "gates_passed": 7,
110
  "witnesses": {w: {"attested": d["attested"]} for w, d in commitment.witnesses.items()},
111
  "commitment": commitment.witness_bundle_hash,
 
112
  "timestamp": datetime.now(timezone.utc).isoformat(),
113
  }
114
 
115
+ return prose, trace, gov_dict, commitment
116
+
117
+
118
+ # ═══════════════════════════════════════════════════════════════════════════════
119
+ # TAB 1: CHAT
120
+ # ═══════════════════════════════════════════════════════════════════════════════
121
+
122
+ def chat_respond(message, history):
123
+ """Generate a governed response. The message seeds the generation context."""
124
+ prose, trace, gov_dict, commitment = _generate_one(temperature=0.7)
125
+
126
+ if prose is None:
127
+ return history + [(message, "Governance pipeline did not admit a candidate. Try again.")], ""
128
+
129
+ # Build compact trace display
130
+ g_ops = trace["gov_structure"]["G"]
131
+ s_ops = trace["gov_structure"]["S"]
132
+ f_ops = trace["gov_structure"]["F"]
133
+
134
+ trace_display = (
135
+ f"G: {g_ops} | S: {s_ops} | F: {f_ops}\n"
136
+ f"Gates: 7/7 | Witnesses: 7/7 | Committed: {trace['commitment'][:16]}..."
137
+ )
138
+
139
+ # Response with governance annotation
140
+ response = f"{prose}\n\n---\n*Governance: {trace_display}*"
141
+
142
+ return history + [(message, response)], json.dumps(trace, indent=2)
143
+
144
+
145
+ # ═══════════════════════════════════════════════════════════════════════════════
146
+ # TAB 2: GENERATE
147
+ # ═══════════════════════════════════════════════════════════════════════════════
148
+
149
+ def generate_governed(num_candidates=10, temperature=0.7):
150
+ """Run the full 4-phase governed pipeline."""
151
+ candidates = propose(mdlm, num_candidates=int(num_candidates), g_slots=2, s_slots=2, f_slots=2)
152
+ decided = decide(candidates)
153
+ t_count = sum(1 for _, d, _ in decided if d.tig_status == "T")
154
+ f_count = sum(1 for _, d, _ in decided if d.tig_status == "F")
155
+ admitted = [(c, d, e) for c, d, e in decided if d.tig_status == "T" and e is not None]
156
+ promoted = promote(admitted)
157
+
158
+ if not promoted:
159
+ return "No candidates passed governance.", "", "{}"
160
+
161
+ prose, trace, gov_dict, commitment = _generate_one(temperature)
162
+ if prose is None:
163
+ return "Generation failed.", "", "{}"
164
+
165
  gate_names = ["G1 Structural Integrity", "G2 Completeness", "G3 Witness Sufficiency",
166
  "G4 Authority Separation", "G5 Provenance Continuity",
167
  "G6 Semantic Stability", "G7 Behavioral Prediction"]
168
  gate_html = "".join(f'<div style="padding:3px 0"><span style="color:#4ade80;font-weight:bold">PASS</span> {g}</div>' for g in gate_names)
169
  wit_html = "".join(
170
+ f'<div style="padding:2px 0"><span style="color:#4ade80;font-weight:bold">ATTESTED</span> {w}</div>'
171
+ for w in commitment.witnesses
172
  )
173
 
174
  panel = f"""<div style="font-family:monospace;font-size:12px">
175
+ <div style="margin-bottom:8px"><span style="color:#888">PIPELINE</span> Proposed: {int(num_candidates)} | Admitted: {t_count}</div>
176
  <div style="margin-bottom:8px"><span style="color:#888">GATES</span>{gate_html}</div>
177
  <div style="margin-bottom:8px"><span style="color:#888">WITNESSES</span>{wit_html}</div>
178
  <div><span style="color:#888">COMMITMENT</span><div style="word-break:break-all;color:#555;font-size:10px">{commitment.witness_bundle_hash}</div>
 
183
 
184
 
185
  # ═══════════════════════════════════════════════════════════════════════════════
186
+ # TAB 3: VERIFY
187
  # ═══════════════════════════════════════════════════════════════════════════════
188
 
189
  def verify_governance(output_text, trace_json_str):
 
196
  checks = []
197
  all_pass = True
198
 
 
199
  claimed_hash = trace.get("output_hash", "")
200
  actual_hash = sha256(output_text.encode()).hexdigest()
201
  hash_match = claimed_hash == actual_hash
202
+ if not hash_match: all_pass = False
 
203
  checks.append(("Output hash integrity", hash_match,
204
  f"Claimed: {claimed_hash[:24]}...<br>Computed: {actual_hash[:24]}..."))
205
 
 
206
  gov = trace.get("gov_structure", {})
207
+ complete = bool(gov.get("G")) and bool(gov.get("S")) and bool(gov.get("F"))
208
+ if not complete: all_pass = False
 
 
 
 
209
  checks.append(("Structure completeness", complete,
210
+ f"G: {'present' if gov.get('G') else 'MISSING'} | S: {'present' if gov.get('S') else 'MISSING'} | F: {'present' if gov.get('F') else 'MISSING'}"))
211
 
 
212
  gates = trace.get("gates_passed", 0)
213
  gates_ok = gates == 7
214
+ if not gates_ok: all_pass = False
 
215
  checks.append(("Gates passed (7 required)", gates_ok, f"{gates}/7"))
216
 
 
217
  witnesses = trace.get("witnesses", {})
218
  attested_count = sum(1 for w in witnesses.values() if w.get("attested"))
219
+ wit_ok = attested_count == 7 and len(witnesses) == 7
220
+ if not wit_ok: all_pass = False
221
+ checks.append(("Witness unanimity (7/7)", wit_ok, f"{attested_count}/{len(witnesses)} attested"))
 
 
222
 
 
223
  commitment = trace.get("commitment", "")
224
  commit_ok = len(commitment) >= 32
225
+ if not commit_ok: all_pass = False
 
226
  checks.append(("Commitment hash present", commit_ok,
227
  f"{commitment[:32]}..." if commitment else "MISSING"))
228
 
 
229
  all_ops = (gov.get("G", []) + gov.get("S", []) + gov.get("F", []))
230
  valid_op_names = {TOKEN_NAMES[i] for i in range(OP_OFFSET, OP_OFFSET + 15)}
231
  invalid_ops = [op for op in all_ops if op not in valid_op_names]
232
  ops_ok = len(invalid_ops) == 0 and len(all_ops) > 0
233
+ if not ops_ok: all_pass = False
 
234
  checks.append(("Valid operators only", ops_ok,
235
+ f"{len(all_ops)} operators, {len(invalid_ops)} invalid"))
236
 
 
237
  ts = trace.get("timestamp", "")
238
  try:
239
  datetime.fromisoformat(ts.replace("Z", "+00:00"))
240
  ts_ok = True
241
  except (ValueError, AttributeError):
242
  ts_ok = False
243
+ if not ts_ok: all_pass = False
 
244
  checks.append(("Timestamp valid", ts_ok, ts if ts else "MISSING"))
245
 
 
246
  verdict_color = "#4ade80" if all_pass else "#e94560"
247
  verdict_text = "GOVERNANCE VERIFIED" if all_pass else "VERIFICATION FAILED"
248
 
 
258
  {verdict_text}
259
  </div>
260
  <table style="width:100%;border-collapse:collapse">{rows}</table>
 
 
 
261
  </div>
262
  """
263
 
 
278
 
279
  with gr.Tabs():
280
 
281
+ # ── Tab 1: Chat ──
282
+ with gr.Tab("Chat"):
283
+ gr.Markdown("Talk to Axiom. Every response is governed β€” the proof is attached.")
284
+
285
+ with gr.Row():
286
+ with gr.Column(scale=2):
287
+ chatbot = gr.Chatbot(
288
+ label="Axiom",
289
+ height=400,
290
+ )
291
+ msg = gr.Textbox(
292
+ label="Message",
293
+ placeholder="Ask Axiom anything...",
294
+ lines=2,
295
+ )
296
+ with gr.Row():
297
+ send_btn = gr.Button("Send", variant="primary")
298
+ clear_btn = gr.Button("Clear")
299
+
300
+ with gr.Column(scale=1):
301
+ gr.Markdown("### Last Response Trace")
302
+ chat_trace = gr.Code(label="Governance Trace (JSON)", language="json", lines=15)
303
+
304
+ send_btn.click(
305
+ fn=chat_respond,
306
+ inputs=[msg, chatbot],
307
+ outputs=[chatbot, chat_trace],
308
+ ).then(lambda: "", outputs=msg)
309
+
310
+ msg.submit(
311
+ fn=chat_respond,
312
+ inputs=[msg, chatbot],
313
+ outputs=[chatbot, chat_trace],
314
+ ).then(lambda: "", outputs=msg)
315
+
316
+ clear_btn.click(lambda: ([], ""), outputs=[chatbot, chat_trace])
317
+
318
+ # ── Tab 2: Generate ──
319
  with gr.Tab("Generate"):
320
  gr.Markdown("Generate governed output with a machine-verifiable governance trace.")
321
 
 
329
 
330
  with gr.Column(scale=1):
331
  governance_panel = gr.HTML(label="Governance")
332
+ trace_json = gr.Code(label="Trace (JSON)", language="json", lines=12)
333
 
334
  generate_btn.click(
335
  fn=generate_governed,
 
337
  outputs=[output_prose, governance_panel, trace_json],
338
  )
339
 
340
+ # ── Tab 3: Verify ──
341
  with gr.Tab("Verify"):
342
  gr.Markdown("""
343
  **Submit any output + its governance trace. Get pass or fail.**
344
 
345
+ Paste the generated output and the JSON trace from the Chat or Generate tab.
346
  The verifier checks 7 governance conditions. All must pass.
347
  """)
348