Qalam commited on
Commit
0c940ab
·
verified ·
1 Parent(s): 4e4768b

Auto: deploy Nuclear Intelligence v5.0

Browse files
Files changed (1) hide show
  1. app.py +107 -8
app.py CHANGED
@@ -1239,6 +1239,26 @@ def get_category_chart():
1239
 
1240
  # ─── Action functions ─────────────────────────────────────────────
1241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1242
  def run_cycle(dev_mode=True, sync_hf=True):
1243
  if not core:
1244
  return "❌ System initializing..."
@@ -1441,7 +1461,8 @@ if gradio_available:
1441
  with gr.Tab("🚀 Research Center"):
1442
  with gr.Row():
1443
  run_btn = gr.Button("🚀 Run Research Cycle", variant="primary")
1444
- dev_chk = gr.Checkbox(label="Developer Mode", value=True)
 
1445
  sync_chk = gr.Checkbox(label="Sync to HF Dataset", value=True)
1446
  cycle_out = gr.Markdown("### Click button to start research...")
1447
 
@@ -1478,25 +1499,103 @@ if gradio_available:
1478
  refresh_stats.click(get_system_stats, outputs=stats_box)
1479
  refresh_llm.click(get_llm_status, outputs=llm_status)
1480
  run_btn.click(run_cycle, inputs=[dev_chk, sync_chk], outputs=cycle_out)
 
1481
  q_btn.click(ask_q, inputs=[q_input, dev_chk], outputs=q_out)
1482
  verify_btn.click(verify_chain, outputs=verify_out)
1483
  search_btn.click(search_kg, inputs=[search_input, limit_input], outputs=search_out)
1484
  export_btn.click(export_state, outputs=export_out)
1485
 
1486
- # Auto-refresh stats every 30s
1487
- timer = gr.Timer(30)
1488
- timer.tick(get_system_stats, outputs=stats_box)
1489
- timer.tick(get_chain_df, outputs=chain_table)
1490
- timer.tick(get_entities_df, outputs=entities_table)
1491
- timer.tick(get_history_df, outputs=history_table)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1492
 
1493
 
1494
  if __name__ == "__main__":
1495
  if demo is not None:
 
 
 
 
 
 
 
 
 
 
1496
  try:
1497
  demo.launch(server_name="0.0.0.0", server_port=PORT, css=CSS)
1498
  except TypeError:
1499
  # Gradio 6.0+ deprecated css in launch() too; pass only valid kwargs
1500
  demo.launch(server_name="0.0.0.0", server_port=PORT)
1501
  else:
1502
- print("⚠️ Gradio not available; cannot launch UI. Run via 'huggingface_hub' sync or programmatic import.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1239
 
1240
  # ─── Action functions ─────────────────────────────────────────────
1241
 
1242
+ def discover_question():
1243
+ """Generate one research question without committing to a full cycle.
1244
+ Used by the 🔍 Discover Question button."""
1245
+ if not core:
1246
+ return "❌ System initializing..."
1247
+ try:
1248
+ q = core.generate_question()
1249
+ return (
1250
+ f"## 🔍 Discovered Question\n\n"
1251
+ f"**Question:** {q.get('question','')}\n\n"
1252
+ f"- **Category:** `{q.get('category','N/A')}`\n"
1253
+ f"- **Difficulty:** `{q.get('difficulty','N/A')}/10`\n"
1254
+ f"- **Keywords:** `{' · '.join(q.get('keywords', []))}`\n"
1255
+ f"- **Source:** `{q.get('source','?')}`\n\n"
1256
+ f"_Hit 🚀 Run Research Cycle to research, evaluate, and possibly mint an NES token._"
1257
+ )
1258
+ except Exception as e:
1259
+ return f"❌ Error: {e}"
1260
+
1261
+
1262
  def run_cycle(dev_mode=True, sync_hf=True):
1263
  if not core:
1264
  return "❌ System initializing..."
 
1461
  with gr.Tab("🚀 Research Center"):
1462
  with gr.Row():
1463
  run_btn = gr.Button("🚀 Run Research Cycle", variant="primary")
1464
+ discover_btn = gr.Button("🔍 Discover Question", variant="secondary")
1465
+ dev_chk = gr.Checkbox(label="Developer Mode", value=False)
1466
  sync_chk = gr.Checkbox(label="Sync to HF Dataset", value=True)
1467
  cycle_out = gr.Markdown("### Click button to start research...")
1468
 
 
1499
  refresh_stats.click(get_system_stats, outputs=stats_box)
1500
  refresh_llm.click(get_llm_status, outputs=llm_status)
1501
  run_btn.click(run_cycle, inputs=[dev_chk, sync_chk], outputs=cycle_out)
1502
+ discover_btn.click(discover_question, outputs=cycle_out)
1503
  q_btn.click(ask_q, inputs=[q_input, dev_chk], outputs=q_out)
1504
  verify_btn.click(verify_chain, outputs=verify_out)
1505
  search_btn.click(search_kg, inputs=[search_input, limit_input], outputs=search_out)
1506
  export_btn.click(export_state, outputs=export_out)
1507
 
1508
+ # Auto-refresh stats every 30s (gr.Timer was added in 4.40+, guard it)
1509
+ try:
1510
+ timer = gr.Timer(30)
1511
+ timer.tick(get_system_stats, outputs=stats_box)
1512
+ timer.tick(get_chain_df, outputs=chain_table)
1513
+ timer.tick(get_entities_df, outputs=entities_table)
1514
+ timer.tick(get_history_df, outputs=history_table)
1515
+ except (AttributeError, TypeError):
1516
+ # Gradio < 4.40: no Timer; auto-refresh via load-event poll instead.
1517
+ logger.warning("gr.Timer unavailable (Gradio < 4.40) — auto-refresh disabled, use 🔄 buttons.")
1518
+
1519
+
1520
+ # ═══════════════════════════════════════════════════════════════════
1521
+ # ALWAYS-ON: background autonomous loop (thread, headless)
1522
+ # ═══════════════════════════════════════════════════════════════════
1523
+
1524
+ _autonomous_thread_started = False
1525
+
1526
+
1527
+ def _autonomous_loop():
1528
+ """Background autonomous research loop. Runs every INTERVAL minutes."""
1529
+ interval_seconds = int(os.getenv("OPERATION_LOOP_INTERVAL_MINUTES", "25")) * 60
1530
+ logger.info(f"🤖 Autonomous loop started (interval={interval_seconds}s)")
1531
+ # Initial warm-up delay so Space finishes starting first
1532
+ time.sleep(30)
1533
+ while True:
1534
+ try:
1535
+ logger.info("🤖 Auto-cycle: starting research cycle")
1536
+ res = core.run_cycle(dev_mode=False) if core else {"minted": False, "error": "no core"}
1537
+ if res.get("minted"):
1538
+ logger.info(f"✅ Auto-cycle: MINTED tx={res.get('tx_hash')} overall={res.get('overall')}")
1539
+ # Sync to HF dataset & push to GitHub
1540
+ try:
1541
+ sync_to_hf_dataset(res)
1542
+ except Exception as e:
1543
+ logger.warning(f"HF dataset sync failed: {e}")
1544
+ else:
1545
+ logger.info(f"⏭️ Auto-cycle: rejected (overall={res.get('overall', 0)}) — trying again next interval")
1546
+ except Exception as e:
1547
+ logger.error(f"Auto-cycle error: {e}")
1548
+ time.sleep(interval_seconds)
1549
 
1550
 
1551
  if __name__ == "__main__":
1552
  if demo is not None:
1553
+ # Always-on autonomous loop in background
1554
+ if os.getenv("AUTO_START_LOOP", "true").lower() == "true" and not _autonomous_thread_started:
1555
+ try:
1556
+ t = threading.Thread(target=_autonomous_loop, daemon=True, name="ni-autonomous")
1557
+ t.start()
1558
+ _autonomous_thread_started = True
1559
+ logger.info("✅ Background autonomous loop launched")
1560
+ except Exception as e:
1561
+ logger.warning(f"Could not start autonomous loop: {e}")
1562
+
1563
  try:
1564
  demo.launch(server_name="0.0.0.0", server_port=PORT, css=CSS)
1565
  except TypeError:
1566
  # Gradio 6.0+ deprecated css in launch() too; pass only valid kwargs
1567
  demo.launch(server_name="0.0.0.0", server_port=PORT)
1568
  else:
1569
+ # Gradio unavailable — keep the Space alive with a tiny health HTTP server
1570
+ print("⚠️ Gradio not available; cannot launch UI. Starting minimal health server.")
1571
+ try:
1572
+ from http.server import HTTPServer, BaseHTTPRequestHandler
1573
+ import json as _json
1574
+
1575
+ class _Health(BaseHTTPRequestHandler):
1576
+ def log_message(self, *a, **k):
1577
+ pass
1578
+
1579
+ def do_GET(self):
1580
+ if self.path == "/" or self.path == "/health":
1581
+ body = _json.dumps({
1582
+ "status": "ok",
1583
+ "name": "Nuclear Intelligence",
1584
+ "version": "5.0",
1585
+ "gradio_available": False,
1586
+ "core_initialized": core is not None,
1587
+ }).encode()
1588
+ self.send_response(200)
1589
+ self.send_header("Content-Type", "application/json")
1590
+ self.send_header("Content-Length", str(len(body)))
1591
+ self.end_headers()
1592
+ self.wfile.write(body)
1593
+ else:
1594
+ self.send_response(404)
1595
+ self.end_headers()
1596
+
1597
+ srv = HTTPServer(("0.0.0.0", PORT), _Health)
1598
+ logger.info(f"Health server on :{PORT}")
1599
+ srv.serve_forever()
1600
+ except Exception as e:
1601
+ print(f"Health server failed: {e}")