agent-dashboard / app.py
ndwdgda's picture
Upload folder using huggingface_hub
93c04c0 verified
# 🛸 ANTIGRAVITY AGENT DASHBOARD – Full Implementation with Extreme Logging
# This file runs as the main entry‑point for the HuggingFace Space.
import os, threading, time, logging
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import uvicorn
import gradio as gr
from typing import List, Dict
# --------------------------------------------------------------
# Logging infrastructure (in‑memory for demo purposes)
# --------------------------------------------------------------
logging.basicConfig(level=logging.INFO)
log_lock = threading.Lock()
log_entries: List[Dict] = [] # each entry: {"timestamp": ..., "level": ..., "msg": ...}
def add_log(level: str, msg: str):
entry = {"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), "level": level.upper(), "msg": msg}
with log_lock:
log_entries.append(entry)
# keep only recent 200 entries to avoid memory blow‑up
if len(log_entries) > 200:
log_entries.pop(0)
logging.getLogger("dashboard").info(f"{level.upper()}: {msg}")
# --------------------------------------------------------------
# Core FastAPI app – handles node registration, failures, and logs
# --------------------------------------------------------------
app = FastAPI()
registered_nodes: Dict[str, Dict] = {} # url -> info dict
@app.post("/register_node")
def register_node(req: Request):
data = req.json()
url = data.get("data") if isinstance(data, dict) else None
if not url:
return JSONResponse({"status": "error", "detail": "missing url"}, status_code=400)
registered_nodes[url] = {"last_seen": time.time()}
add_log("info", f"Node registered: {url}")
return {"status": "ok"}
@app.post("/node_failure")
def node_failure(req: Request):
data = req.json()
url = data.get("url", "unknown")
add_log("error", f"Node failure reported: {url}")
# remove from registry if present
registered_nodes.pop(url, None)
return {"status": "received"}
@app.post("/log")
def receive_log(req: Request):
data = req.json()
level = data.get("level", "info")
msg = data.get("msg", "")
add_log(level, msg)
return {"status": "logged"}
@app.get("/health")
def health():
return {"status": "online", "nodes": len(registered_nodes)}
# --------------------------------------------------------------
# Gradio UI – Mission Control, System Health, Engineered Logs, Quick Actions
# --------------------------------------------------------------
def get_node_status():
# simple summary string
lines = []
for url, info in registered_nodes.items():
age = int(time.time() - info["last_seen"])
lines.append(f"{url} – last seen {age}s ago")
return "\n".join(lines) if lines else "No nodes connected"
def get_logs():
with log_lock:
return "\n".join([f"[{e['timestamp']}] {e['level']}: {e['msg']}" for e in log_entries])
with gr.Blocks() as demo:
gr.Markdown("# 🛸 ANTIGRAVITY Enterprise Dashboard (v2 PRO)")
with gr.Tab("Mission Control"):
gr.Markdown("Chat interface placeholder – integrate your agent here.")
with gr.Tab("System Health & Telemetry"):
health_box = gr.Textbox(label="Node Status", lines=5)
refresh_btn = gr.Button("Refresh")
refresh_btn.click(fn=get_node_status, inputs=None, outputs=health_box)
with gr.Tab("Engineered Logs"):
log_box = gr.Textbox(label="Logs", lines=15)
log_refresh = gr.Button("Refresh Logs")
log_refresh.click(fn=get_logs, inputs=None, outputs=log_box)
with gr.Tab("Quick Actions"):
# Button that opens the Colab notebook – replace <NOTEBOOK_URL> with your actual URL
colab_url = os.getenv("COLAB_NOTEBOOK_URL", "https://colab.research.google.com/drive/<YOUR_NOTEBOOK_ID>")
launch_btn = gr.Button("🚀 Start the AI via Google Colab T4 GPU", variant="primary")
launch_btn.click(fn=None, js=f"() => window.open('{colab_url}', '_blank')")
# Optional manual URL input for debugging
manual_input = gr.Textbox(label="Connect Locally (if auto‑connect fails)")
connect_btn = gr.Button("🔗 Connect Link")
# The actual connection logic is handled by the Colab node itself.
# --------------------------------------------------------------
# Run FastAPI in a background thread so Gradio can serve the UI
# --------------------------------------------------------------
def run_fastapi():
uvicorn.run(app, host="0.0.0.0", port=8001, log_level="error")
threading.Thread(target=run_fastapi, daemon=True).start()
# Expose the Gradio demo as the Space entry point
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)