phammminhhieu's picture
TRACE-VLA code snapshot 2026-11-22 11:47 +07: 456 canonical files + SHA256 manifest + sync report (part 2)
ae1ed83 verified
Raw History Blame Contribute Delete
8.85 kB
#!/usr/bin/env python3
"""TRACE-VLA dashboard server.
Serves one static page plus live JSON endpoints read fresh from the
validation workspace on the train machine. Binds 127.0.0.1 only;
external access goes through the cloudflared tunnel started by start.sh.
Endpoints:
/ -> www/index.html
/data/status -> trace_validation/status.json (+ STATUS.md markers)
/data/train -> trace_validation/train_progress.json (may not exist yet)
/data/results -> flattened numeric metrics from trace_validation/results/*.json
/data/machine -> GPU / disk / running train-eval processes (cached 10 s)
"""
import json
import os
import re
import subprocess
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse
HOME = os.path.expanduser("~")
ROOT = os.path.join(HOME, "trace_dashboard")
WWW = os.path.join(ROOT, "www")
VAL = os.path.join(HOME, "sera_v4_experiments", "trace_validation")
STATUS_JSON = os.path.join(VAL, "status.json")
V2_JSON = os.path.join(VAL, "status_v2.json")
TRAIN_JSON = os.path.join(VAL, "train_progress.json")
STATUS_MD = os.path.join(VAL, "STATUS.md")
RESULTS_DIR = os.path.join(VAL, "results")
PORT = 8901
_machine_cache = {"t": 0.0, "data": None}
def fmt_mtime(path):
try:
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getmtime(path)))
except OSError:
return None
def load_json(path):
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return None
def status_payload():
data = load_json(STATUS_JSON)
markers = {}
try:
with open(STATUS_MD, "r", encoding="utf-8", errors="replace") as f:
text = f.read()
# e.g. PB1_DONE, PB2_FINAL_DONE, A03_DONE, TESTS26_DONE
for m in re.finditer(r"\b([A-Za-z][A-Za-z0-9\-]{1,20}?)_(FINAL_DONE|RERUN_DONE|DONE|PASS|FAIL)\b", text):
key = m.group(1)
val = "DONE" if m.group(2) != "FAIL" else "FAIL"
if key not in markers or val == "FAIL":
markers[key] = val
gm = re.search(r"Gate\s*A\s*:\s*(PASS|FAIL)", text)
if gm:
markers["GateA_md"] = gm.group(1)
except OSError:
pass
return {
"available": data is not None,
"updated_at": fmt_mtime(STATUS_JSON),
"status_md_updated_at": fmt_mtime(STATUS_MD),
"data": data,
"markers": markers,
}
def v2_payload():
data = load_json(V2_JSON)
return {
"available": data is not None,
"updated_at": fmt_mtime(V2_JSON),
"data": data,
}
def train_payload():
data = load_json(TRAIN_JSON)
return {
"available": data is not None,
"updated_at": fmt_mtime(TRAIN_JSON),
"data": data,
}
def flatten(obj, prefix, out, depth=0):
if depth > 5 or len(out) > 80:
return
if isinstance(obj, dict):
for k, v in obj.items():
flatten(v, f"{prefix}{k}." if prefix else f"{k}.", out, depth + 1)
elif isinstance(obj, list):
scalars = [x for x in obj if isinstance(x, (int, float)) and not isinstance(x, bool)]
if scalars and len(scalars) == len(obj) and len(obj) <= 8:
for i, x in enumerate(obj):
out[f"{prefix[:-1]}[{i}]"] = x
elif isinstance(obj, (int, float)) and not isinstance(obj, bool):
out[prefix[:-1]] = obj
elif isinstance(obj, str) and len(obj) <= 40 and prefix.rstrip(".").lower().endswith(("verdict", "status")):
out[prefix[:-1]] = obj
def results_payload():
files = []
try:
names = sorted(os.listdir(RESULTS_DIR))
except OSError:
names = []
for name in names:
if not name.endswith(".json"):
continue
path = os.path.join(RESULTS_DIR, name)
data = load_json(path)
if data is None:
continue
metrics = {}
flatten(data, "", metrics)
files.append({"file": name, "updated_at": fmt_mtime(path), "metrics": metrics})
return {"available": bool(files), "files": files}
def run_cmd(cmd, timeout=8):
try:
return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout.strip()
except Exception:
return ""
def machine_payload():
now = time.time()
if _machine_cache["data"] is not None and now - _machine_cache["t"] < 10:
return _machine_cache["data"]
gpu = {}
out = run_cmd(["nvidia-smi", "--query-gpu=name,utilization.gpu,memory.used,memory.total,temperature.gpu",
"--format=csv,noheader,nounits"])
if out:
parts = [p.strip() for p in out.splitlines()[0].split(",")]
if len(parts) == 5:
try:
gpu = {"name": parts[0], "util_pct": float(parts[1]),
"mem_used_mib": float(parts[2]), "mem_total_mib": float(parts[3]),
"temp_c": float(parts[4])}
except ValueError:
gpu = {"name": parts[0]}
disk = {}
out = run_cmd(["df", "-h", HOME])
if out:
lines = out.splitlines()
if len(lines) >= 2:
p = lines[1].split()
if len(p) >= 5:
disk = {"total": p[1], "used": p[2], "avail": p[3], "use_pct": p[4]}
procs = []
out = run_cmd(["ps", "-eo", "pid,etime,pcpu,pmem,args", "--sort=-pcpu"])
for line in out.splitlines()[1:]:
low = line.lower()
if ("trace_validation" in low or "train_pilot" in low or "eval_trace" in low
or "master_chain" in low or "phase_b" in low) and "trace_dashboard" not in low:
procs.append(line.strip()[:220])
if len(procs) >= 8:
break
data = {"available": True, "time": time.strftime("%Y-%m-%d %H:%M:%S"),
"gpu": gpu, "disk": disk, "processes": procs}
_machine_cache["t"] = now
_machine_cache["data"] = data
return data
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def send_json(self, obj, code=200):
body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
path = urlparse(self.path).path
try:
if path in ("/", "/index.html"):
fpath = os.path.join(WWW, "index.html")
with open(fpath, "rb") as f:
body = f.read()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif path == "/data/status":
self.send_json(status_payload())
elif path == "/data/v2":
self.send_json(v2_payload())
elif path == "/data/train":
self.send_json(train_payload())
elif path == "/data/results":
self.send_json(results_payload())
elif path == "/data/machine":
self.send_json(machine_payload())
elif path == "/healthz":
self.send_json({"ok": True})
else:
# static assets from www/ (e.g. vendored chart.umd.min.js fallback)
rel = path.lstrip("/")
fpath = os.path.normpath(os.path.join(WWW, rel))
if fpath.startswith(WWW) and os.path.isfile(fpath):
types = {".js": "application/javascript", ".css": "text/css",
".png": "image/png", ".json": "application/json",
".html": "text/html; charset=utf-8"}
with open(fpath, "rb") as f:
body = f.read()
self.send_response(200)
self.send_header("Content-Type", types.get(os.path.splitext(fpath)[1], "application/octet-stream"))
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
self.send_json({"error": "not found"}, 404)
except Exception as e: # keep the server alive on any single-request error
try:
self.send_json({"error": str(e)}, 500)
except Exception:
pass
if __name__ == "__main__":
ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()