ram-lexsi's picture
Status pills: once 3+ reviews are submitted, show a green pill for every judge who submitted
00776fa verified
Raw History Blame Contribute Delete
20.8 kB
"""Lexsi Hackathon judging — HF Space (Docker).
Judges sign in with Hugging Face; only usernames on one of the four judge lists get in.
Anyone else gets a sign-in or "not on the list" card and nothing else: no form, no submissions.
Judge lists (comma-separated HF usernames, all Space secrets):
JUDGES common list: sees every submission still pending (fewer than TARGET_REVIEWS
submitted reviews), in any track, plus any submission they already started
JUDGES_T1/T2/T3 track lists: see every submission whose labeled track is t1 / t2 / t3
A username may be on several lists; it then sees the union.
Each judge is stored under an anonymous id = HMAC(JUDGE_SALT, username), never the username.
Reviews are JSON files in a private HF dataset (REVIEWS_DATASET), so they survive Space restarts.
Space secrets / variables:
TARGET_REVIEWS optional, submitted reviews after which a submission stops being pending (default 3)
JUDGE_SALT random key for the anonymous judge ids (keep private, never change mid-judging)
SESSION_SECRET random key for login cookies
REVIEWS_DATASET private dataset repo for reviews + submissions.json, e.g. Lexsi/Hackathon_judging_reviews
HF_TOKEN write token for that dataset
REVIEW_DEADLINE optional, ISO time (UTC) after which reviews are locked, e.g. 2026-11-20T18:00:00Z
DEV_USER local testing only: pretend this user is logged in (ignored when OAuth is configured)
"""
import hashlib, hmac, json, os, secrets, threading
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlencode
import httpx
import jwt
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from starlette.middleware.sessions import SessionMiddleware
ROOT = Path(__file__).parent
DATA = Path(os.getenv("DATA_DIR", "/tmp/judging-data"))
FORM = json.loads((ROOT / "static" / "form.json").read_text())
CLIENT_ID = os.getenv("OAUTH_CLIENT_ID")
CLIENT_SECRET = os.getenv("OAUTH_CLIENT_SECRET")
PROVIDER = os.getenv("OPENID_PROVIDER_URL", "https://huggingface.co").rstrip("/")
SPACE_HOST = os.getenv("SPACE_HOST", "").split(",")[0].strip() # may list "x.hf.space,custom.domain"
def _names(var):
return {u.strip().lower().lstrip("@") for u in os.getenv(var, "").split(",") if u.strip()}
COMMON = _names("JUDGES")
TRACK_JUDGES = {t: _names(f"JUDGES_{t.upper()}") for t in ("t1", "t2", "t3")}
JUDGES = COMMON.union(*TRACK_JUDGES.values())
TARGET = int(os.getenv("TARGET_REVIEWS", "3") or 3)
SALT = os.getenv("JUDGE_SALT", "")
DATASET = os.getenv("REVIEWS_DATASET", "")
HF_TOKEN = os.getenv("HF_TOKEN", "")
DEADLINE = os.getenv("REVIEW_DEADLINE", "")
SPACE_ID = os.getenv("SPACE_ID", "")
DEV_USER = None if (CLIENT_ID or SPACE_ID) else os.getenv("DEV_USER")
if SPACE_ID and not SALT:
raise SystemExit("JUDGE_SALT secret is missing")
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.add_middleware(SessionMiddleware, secret_key=os.getenv("SESSION_SECRET") or secrets.token_hex(32),
same_site="none" if CLIENT_ID else "lax", https_only=bool(CLIENT_ID), max_age=14 * 86400)
lock = threading.Lock()
# ---------- storage: local copy of the private dataset ----------
def pull_dataset():
DATA.mkdir(parents=True, exist_ok=True)
if DATASET and HF_TOKEN:
from huggingface_hub import snapshot_download
try:
snapshot_download(DATASET, repo_type="dataset", token=HF_TOKEN, local_dir=DATA)
except Exception as e:
print("Could not pull reviews dataset:", e)
def push_file(path: Path):
if not (DATASET and HF_TOKEN):
return
from huggingface_hub import HfApi
HfApi(token=HF_TOKEN).upload_file(path_or_fileobj=str(path), path_in_repo=str(path.relative_to(DATA)),
repo_id=DATASET, repo_type="dataset",
commit_message=f"review {path.parent.name}/{path.stem}")
pull_dataset()
def submissions():
f = DATA / "submissions.json"
src = f if f.exists() else ROOT / "submissions.sample.json"
return json.loads(src.read_text())
def review_path(judge: str, sid: str) -> Path:
if not sid.replace("-", "").replace("_", "").isalnum():
raise HTTPException(400, "bad submission id")
return DATA / "reviews" / judge / f"{sid}.json"
# ---------- form logic (same rules as the page) ----------
def cond(c, a):
if not c:
return True
if "all" in c:
return all(cond(x, a) for x in c["all"])
if "any" in c:
return any(cond(x, a) for x in c["any"])
return a.get(c["f"]) in c["in"]
def visible_sections(a):
out = []
for s in FORM["sections"]:
if not cond(s.get("show_if"), a):
continue
out.append(s)
if s.get("ends_if") and cond(s["ends_if"], a):
return out, True
return out, False
def validate(a, track=None):
a = {**a, "track": track} # track is set by the internal team in submissions.json
missing = []
secs, ended = visible_sections(a)
for s in secs:
for f in s["fields"]:
if f.get("optional") or not cond(f.get("show_if"), a):
continue
v = a.get(f["id"])
if f["type"] == "choice" and v not in f["options"]:
missing.append(f["id"])
elif f["type"] == "number":
try:
ok = f["min"] <= float(v) <= f["max"]
except (TypeError, ValueError):
ok = False
if not ok:
missing.append(f["id"])
elif f["type"] == "text" and not str(v or "").strip():
missing.append(f["id"])
return missing, ended
# ---------- auth ----------
def judge_id(username: str) -> str:
return "j_" + hmac.new(SALT.encode(), username.lower().encode(), hashlib.sha256).hexdigest()[:16]
HF_KEYS = None
def hf_keys():
global HF_KEYS
if HF_KEYS is None:
HF_KEYS = {k["kid"]: jwt.PyJWK(k) for k in httpx.get(f"{PROVIDER}/api/keys/jwt", timeout=20).json()}
return HF_KEYS
def user_from_sign(token: str):
"""A private Space is shown on huggingface.co with ?__sign=<JWT>, signed by HF for the person viewing it."""
try:
kid = jwt.get_unverified_header(token)["kid"]
claims = jwt.decode(token, hf_keys()[kid].key, algorithms=["EdDSA"], issuer=PROVIDER,
options={"require": ["exp", "sub"], "verify_aud": False})
except Exception:
return None
if SPACE_ID and claims.get("sub") != f"/spaces/{SPACE_ID}":
return None
who = claims.get("onBehalfOf") or {}
return who.get("user") if who.get("kind") == "user" else None
_tok_cache = {}
def user_from_token(request: Request):
"""A judge may also call the API with their own Hugging Face token (Authorization: Bearer hf_...).
Hugging Face says whose token it is, so a token can only ever act as its own owner."""
auth = request.headers.get("authorization", "")
if not auth.lower().startswith("bearer "):
return None
tok = auth[7:].strip()
key = hashlib.sha256(tok.encode()).hexdigest()
if key in _tok_cache:
return _tok_cache[key]
try:
r = httpx.get(f"{PROVIDER}/api/whoami-v2", headers={"Authorization": f"Bearer {tok}"}, timeout=15)
info = r.json() if r.status_code == 200 else {}
name = info.get("name") if info.get("type") == "user" else None
except Exception:
name = None
if name:
_tok_cache[key] = name
return name
def current_user(request: Request):
if DEV_USER: # local testing only; ?as=<user> switches the pretend judge
return request.query_params.get("as") or request.cookies.get("dev_as") or DEV_USER
sign = request.query_params.get("__sign") or request.headers.get("x-hf-sign")
return (user_from_sign(sign) if sign else None) or request.session.get("user") or user_from_token(request)
def require_judge(request: Request) -> str:
u = current_user(request)
if not u:
raise HTTPException(401, "not signed in")
if u.lower() not in JUDGES:
raise HTTPException(403, "not on the judges list")
return judge_id(u)
@app.get("/login")
def login(request: Request):
if not CLIENT_ID:
return RedirectResponse("/")
if SPACE_HOST and request.url.hostname != SPACE_HOST: # keep the whole login on one host so the cookie sticks
return RedirectResponse(f"https://{SPACE_HOST}/login")
state = secrets.token_urlsafe(24)
request.session["state"] = state
q = urlencode({"client_id": CLIENT_ID, "redirect_uri": f"https://{SPACE_HOST}/login/callback",
"scope": "openid profile", "state": state, "response_type": "code"})
return RedirectResponse(f"{PROVIDER}/oauth/authorize?{q}")
@app.get("/login/callback")
def callback(request: Request, code: str = "", state: str = ""):
if not code or state != request.session.pop("state", None):
return RedirectResponse("/?li=retry") # cookie didn't stick: show the button instead of looping
tok = httpx.post(f"{PROVIDER}/oauth/token", auth=(CLIENT_ID, CLIENT_SECRET), timeout=20,
data={"grant_type": "authorization_code", "code": code,
"redirect_uri": f"https://{SPACE_HOST}/login/callback"}).json()
info = httpx.get(f"{PROVIDER}/oauth/userinfo", timeout=20,
headers={"Authorization": f"Bearer {tok['access_token']}"}).json()
request.session["user"] = info["preferred_username"]
return RedirectResponse("/?li=1")
@app.get("/logout")
def logout(request: Request):
request.session.clear()
return RedirectResponse("/")
# ---------- API ----------
def build_index():
"""One self-contained page: logo, fonts and form inlined, so a private Space needs no extra requests."""
import base64
st = ROOT / "static"
b64 = lambda f, mime: f"data:{mime};base64," + base64.b64encode((st / f).read_bytes()).decode()
fonts = (st / "fonts" / "fonts.css").read_text()
for f in ("space-grotesk-latin.woff2", "space-grotesk-latin-ext.woff2", "space-grotesk-vietnamese.woff2"):
fonts = fonts.replace(f"url({f})", f"url({b64('fonts/' + f, 'font/woff2')})")
return ((st / "index.html").read_text().replace("__FONTS__", fonts)
.replace("__LOGO__", b64("lexsi-logo.png", "image/png"))
.replace("__FAVICON__", b64("favicon-black.png", "image/png"))
.replace("__FORM__", json.dumps(FORM)))
INDEX = build_index()
def gate_page(title, body, button=""):
return f"""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow"><title>Judging | Lexsi</title>
<style>*{{box-sizing:border-box;margin:0}}html{{color-scheme:dark;height:100%}}body{{background:#000;color:#fff;font-family:system-ui,sans-serif;height:100%;overflow:hidden}}
.c{{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);width:min(420px,calc(100% - 32px));border:2px solid #FF4B0A;border-radius:12px;padding:36px 28px;text-align:center}}h1{{font-size:24px;margin-bottom:10px}}p{{color:#FFFFFFD1;font-size:15px;line-height:1.5}}
a{{display:inline-block;margin-top:22px;background:#FFD21E;color:#000;font-weight:600;padding:12px 22px;border-radius:8px;text-decoration:none}}</style></head>
<body><div class="c"><h1>{title}</h1><p>{body}</p>{button}</div></body></html>"""
@app.get("/")
def index(request: Request):
u = current_user(request)
if not u:
url = f"https://{SPACE_HOST}/login" if SPACE_HOST else "/login"
if not request.query_params.get("li"): # first visit: sign in right here (inside the HF page too), no click
return RedirectResponse(url)
return HTMLResponse(gate_page("Judges only", "Sign in with the Hugging Face account you were invited with.",
f'<a href="{url}">Sign in with Hugging Face</a>'),
status_code=401, headers={"Cache-Control": "no-store"})
if u.lower() not in JUDGES:
import html
return HTMLResponse(gate_page("Not on the judges list", f"You're signed in as @{html.escape(u)}, which isn't an invited judge account. "
"If that's a mistake, message the Lexsi team."),
status_code=403, headers={"Cache-Control": "no-store"})
r = HTMLResponse(INDEX, headers={"Cache-Control": "no-store"})
if DEV_USER and request.query_params.get("as"):
r.set_cookie("dev_as", request.query_params["as"])
return r
@app.get("/api/me")
def me(request: Request):
u = current_user(request)
allowed = bool(u) and u.lower() in JUDGES
roles = (["common"] if allowed and u.lower() in COMMON else []) + \
[t for t, ns in TRACK_JUDGES.items() if allowed and u.lower() in ns]
return {"user": u, "allowed": allowed, "judge": judge_id(u) if allowed else None, "roles": roles,
"target": TARGET, "deadline": DEADLINE or None, "locked": locked()}
def locked():
if not DEADLINE:
return False
return datetime.now(timezone.utc) > datetime.fromisoformat(DEADLINE.replace("Z", "+00:00"))
def all_statuses():
"""{submission id: {judge id: status}} from the review files on disk."""
out = {}
for f in (DATA / "reviews").glob("*/*.json"):
try:
out.setdefault(f.stem, {})[f.parent.name] = json.loads(f.read_text()).get("status", "draft")
except Exception:
pass
return out
DONE = ("submitted", "ended_checklist")
def visible(u, j, s, st):
"""Can judge u (id j) see submission s? st = {judge id: status} for s."""
u = u.lower()
if u in TRACK_JUDGES.get(s.get("track"), ()):
return True
if u in COMMON:
if j in st:
return True
return sum(1 for k, v in st.items() if k != j and v in DONE) < TARGET
return False
def light(v):
return "done" if v in DONE else "draft" if v == "draft" else "off"
def lights(u, j, s, st):
"""Slot 1 is the viewer. Slots 2-3: two other judges on this submission, picked at random
(stable per viewer and submission), from its track list plus anyone who has started it. None = empty."""
done_others = sorted(o for o, v in st.items() if o != j and v == "submitted")
if sum(v == "submitted" for v in st.values()) >= 3:
# 3+ submitted reviews: one green pill per other judge who submitted, after your own
return [light(st.get(j))] + ["done"] * len(done_others)
others = {judge_id(x) for x in TRACK_JUDGES.get(s.get("track"), ())} | set(st)
others.discard(j)
import random
pick = random.Random(f"{j}:{s['id']}").sample(sorted(others), min(2, len(others)))
return [light(st.get(j))] + [light(st.get(o)) for o in pick] + [None] * (2 - len(pick))
def my_subs(request: Request):
j = require_judge(request)
u = current_user(request)
st_all = all_statuses()
return j, u, st_all, [s for s in submissions() if visible(u, j, s, st_all.get(s["id"], {}))]
def review_stats():
"""{submission id: (number of submitted reviews, mean overall of those)} from the review files on disk."""
acc = {}
for f in (DATA / "reviews").glob("*/*.json"):
try:
r = json.loads(f.read_text())
except Exception:
continue
if r.get("status") != "submitted":
continue
a = acc.setdefault(f.stem, [0, []])
a[0] += 1
try:
a[1].append(float(r.get("answers", {}).get("overall")))
except (TypeError, ValueError):
pass
return {k: (n, sum(v) / len(v) if v else 0.0) for k, (n, v) in acc.items()}
@app.get("/api/submissions")
def list_submissions(request: Request):
"""Ordered for judges: fewest submitted reviews first, then higher mean overall first. Only the order is sent,
never the scores. The page keeps the track grouping."""
j, u, st_all, subs = my_subs(request)
stats = review_stats()
key = lambda s: (stats.get(s["id"], (0, 0.0))[0], -stats.get(s["id"], (0, 0.0))[1], str(s.get("number", "")))
out = []
for i, s in enumerate(sorted(subs, key=key)):
st = st_all.get(s["id"], {})
out.append({**s, "status": st.get(j, "not_started"), "lights": lights(u, j, s, st), "order": i})
return out
def require_access(request: Request, sid: str) -> str:
j, _, _, subs = my_subs(request)
if not any(s["id"] == sid for s in subs):
raise HTTPException(404, "not assigned to you")
return j
@app.get("/api/review/{sid}")
def get_review(sid: str, request: Request):
p = review_path(require_access(request, sid), sid)
return json.loads(p.read_text()) if p.exists() else {"answers": {}, "status": "not_started"}
@app.post("/api/review/{sid}")
async def save_review(sid: str, request: Request):
j = require_access(request, sid)
if locked():
raise HTTPException(423, "reviews are locked after the deadline")
sub = next((s for s in submissions() if s["id"] == sid), None)
if not sub:
raise HTTPException(404, "unknown submission")
body = await request.json()
a = {k: v for k, v in (body.get("answers") or {}).items() if isinstance(k, str) and len(k) < 40 and k != "track"}
missing, ended = validate(a, sub.get("track"))
final = bool(body.get("final"))
if final and missing:
return JSONResponse({"ok": False, "missing": missing}, status_code=422)
status = ("ended_checklist" if ended else "submitted") if final else "draft"
rec = {"submission": sid, "judge": j, "status": status, "answers": a,
"updated": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")}
p = review_path(j, sid)
with lock:
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(json.dumps(rec, indent=1))
try:
push_file(p)
except Exception as e:
print("push failed:", e)
return JSONResponse({"ok": False, "error": "Saved on the Space but not backed up yet. Please save again."}, status_code=502)
return {"ok": True, "status": status, "updated": rec["updated"]}
@app.post("/api/reviews/bulk")
async def save_reviews_bulk(request: Request):
"""Submit many final reviews for the calling judge in one dataset commit. Never overwrites a review
the judge already submitted. Body: {"reviews": [{"submission": id, "answers": {...}}]}"""
if locked():
raise HTTPException(423, "reviews are locked after the deadline")
j, _, _, subs = my_subs(request)
byid = {s["id"]: s for s in subs}
body = await request.json()
done, skipped, bad = [], [], []
stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
with lock:
paths = []
for item in body.get("reviews") or []:
sid = str(item.get("submission", ""))
sub = byid.get(sid)
if not sub:
bad.append({"submission": sid, "error": "not visible to you"}); continue
p = review_path(j, sid)
if p.exists() and json.loads(p.read_text()).get("status") in ("submitted", "ended_checklist"):
skipped.append(sid); continue
a = {k: v for k, v in (item.get("answers") or {}).items() if isinstance(k, str) and len(k) < 40 and k != "track"}
missing, ended = validate(a, sub.get("track"))
if missing:
bad.append({"submission": sid, "missing": missing}); continue
rec = {"submission": sid, "judge": j, "status": "ended_checklist" if ended else "submitted", "answers": a, "updated": stamp}
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(json.dumps(rec, indent=1))
paths.append(p); done.append(sid)
if paths and DATASET and HF_TOKEN:
from huggingface_hub import HfApi, CommitOperationAdd
try:
HfApi(token=HF_TOKEN).create_commit(DATASET, repo_type="dataset", commit_message=f"reviews {j} (bulk, {len(paths)})",
operations=[CommitOperationAdd(path_in_repo=str(p.relative_to(DATA)), path_or_fileobj=str(p)) for p in paths])
except Exception as e:
print("bulk push failed:", e)
return JSONResponse({"ok": False, "error": "Saved on the Space but not backed up yet. Please retry.", "saved": done}, status_code=502)
return {"ok": True, "judge": j, "saved": done, "skipped_already_submitted": skipped, "rejected": bad}