#!/usr/bin/env python3 """Local review server (standard library only). python code/serve.py then open http://127.0.0.1:8765/web/ Serves results/ and accepts reviewer edits: GET /api/ping -> {"ok": true} POST /api/review {"records": [...]} validated against code/ontology.yaml, appended to results/annotations/review.jsonl (never edits measurements) POST /api/rebuild reruns stages sft, tables, release, web (seconds; no video work) Bound to 127.0.0.1 only.""" import argparse import json import subprocess import sys import threading from functools import partial from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from common import CODE, load_config, load_ontology # noqa: E402 from review import load_people, review_path, stamp, validate # noqa: E402 LOCK = threading.Lock() class Handler(SimpleHTTPRequestHandler): def log_message(self, fmt, *args): first = str(args[0]) if args else "" # args[0] can be an HTTPStatus, not a string if "/api/" in first: sys.stderr.write(" " + fmt % args + "\n") def _json(self, code, obj): body = json.dumps(obj).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def end_headers(self): if self.path.endswith("data.js") or self.path.endswith(".html") or self.path.endswith("/"): self.send_header("Cache-Control", "no-store") super().end_headers() def do_GET(self): if self.path == "/api/ping": return self._json(200, {"ok": True}) if self.path == "/favicon.ico": # browsers ask for this; answer quietly self.send_response(204); self.end_headers(); return if self.path in ("/", ""): self.send_response(302); self.send_header("Location", "/web/"); self.end_headers(); return return super().do_GET() def do_POST(self): n = int(self.headers.get("Content-Length", 0)) if n > 2_000_000: return self._json(413, {"error": "request too large"}) try: body = json.loads(self.rfile.read(n) or b"{}") except json.JSONDecodeError: return self._json(400, {"error": "invalid JSON"}) if self.path == "/api/review": onto = load_ontology() recs = body.get("records") or [] if not recs: return self._json(400, {"error": "no records"}) people = load_people() errs = [e for e in (validate(r, onto, people) for r in recs) if e] if errs: return self._json(400, {"error": "; ".join(errs)}) stamped = [stamp(r, onto) for r in recs] p = review_path(self.server.results) p.parent.mkdir(parents=True, exist_ok=True) with LOCK, open(p, "a") as f: for r in stamped: f.write(json.dumps(r, ensure_ascii=False) + "\n") return self._json(200, {"saved": len(stamped), "ids": [r["id"] for r in stamped]}) if self.path == "/api/rebuild": with LOCK: out = subprocess.run([sys.executable, str(CODE / "run_all.py"), "--stages", "sft,tables,evaluate,release,web"], capture_output=True, text=True) if out.returncode: return self._json(500, {"error": out.stderr[-1500:]}) return self._json(200, {"ok": True, "log": out.stdout[-1500:]}) return self._json(404, {"error": "unknown endpoint"}) def main(): ap = argparse.ArgumentParser() ap.add_argument("--port", type=int, default=8765) a = ap.parse_args() cfg = load_config() R = cfg["_paths"]["results"] if not (R / "web" / "index.html").exists(): raise SystemExit("results/web/index.html not found - run python code/run_all.py first") srv = ThreadingHTTPServer(("127.0.0.1", a.port), partial(Handler, directory=str(R))) srv.results = R print(f"Review server: http://127.0.0.1:{a.port}/web/ (Ctrl+C to stop)") print(f"Edits are appended to {review_path(R)}") try: srv.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main()