ram-lexsi commited on
Commit
f59ccc0
·
verified ·
1 Parent(s): 5f7cb06

API: judges can authenticate with their own HF token; bulk submit route

Browse files
Files changed (1) hide show
  1. app.py +65 -1
app.py CHANGED
@@ -172,11 +172,35 @@ def user_from_sign(token: str):
172
  return who.get("user") if who.get("kind") == "user" else None
173
 
174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  def current_user(request: Request):
176
  if DEV_USER: # local testing only; ?as=<user> switches the pretend judge
177
  return request.query_params.get("as") or request.cookies.get("dev_as") or DEV_USER
178
  sign = request.query_params.get("__sign") or request.headers.get("x-hf-sign")
179
- return (user_from_sign(sign) if sign else None) or request.session.get("user")
180
 
181
 
182
  def require_judge(request: Request) -> str:
@@ -381,3 +405,43 @@ async def save_review(sid: str, request: Request):
381
  print("push failed:", e)
382
  return JSONResponse({"ok": False, "error": "Saved on the Space but not backed up yet. Please save again."}, status_code=502)
383
  return {"ok": True, "status": status, "updated": rec["updated"]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  return who.get("user") if who.get("kind") == "user" else None
173
 
174
 
175
+ _tok_cache = {}
176
+
177
+
178
+ def user_from_token(request: Request):
179
+ """A judge may also call the API with their own Hugging Face token (Authorization: Bearer hf_...).
180
+ Hugging Face says whose token it is, so a token can only ever act as its own owner."""
181
+ auth = request.headers.get("authorization", "")
182
+ if not auth.lower().startswith("bearer "):
183
+ return None
184
+ tok = auth[7:].strip()
185
+ key = hashlib.sha256(tok.encode()).hexdigest()
186
+ if key in _tok_cache:
187
+ return _tok_cache[key]
188
+ try:
189
+ r = httpx.get(f"{PROVIDER}/api/whoami-v2", headers={"Authorization": f"Bearer {tok}"}, timeout=15)
190
+ info = r.json() if r.status_code == 200 else {}
191
+ name = info.get("name") if info.get("type") == "user" else None
192
+ except Exception:
193
+ name = None
194
+ if name:
195
+ _tok_cache[key] = name
196
+ return name
197
+
198
+
199
  def current_user(request: Request):
200
  if DEV_USER: # local testing only; ?as=<user> switches the pretend judge
201
  return request.query_params.get("as") or request.cookies.get("dev_as") or DEV_USER
202
  sign = request.query_params.get("__sign") or request.headers.get("x-hf-sign")
203
+ return (user_from_sign(sign) if sign else None) or request.session.get("user") or user_from_token(request)
204
 
205
 
206
  def require_judge(request: Request) -> str:
 
405
  print("push failed:", e)
406
  return JSONResponse({"ok": False, "error": "Saved on the Space but not backed up yet. Please save again."}, status_code=502)
407
  return {"ok": True, "status": status, "updated": rec["updated"]}
408
+
409
+
410
+ @app.post("/api/reviews/bulk")
411
+ async def save_reviews_bulk(request: Request):
412
+ """Submit many final reviews for the calling judge in one dataset commit. Never overwrites a review
413
+ the judge already submitted. Body: {"reviews": [{"submission": id, "answers": {...}}]}"""
414
+ if locked():
415
+ raise HTTPException(423, "reviews are locked after the deadline")
416
+ j, _, _, subs = my_subs(request)
417
+ byid = {s["id"]: s for s in subs}
418
+ body = await request.json()
419
+ done, skipped, bad = [], [], []
420
+ stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
421
+ with lock:
422
+ paths = []
423
+ for item in body.get("reviews") or []:
424
+ sid = str(item.get("submission", ""))
425
+ sub = byid.get(sid)
426
+ if not sub:
427
+ bad.append({"submission": sid, "error": "not visible to you"}); continue
428
+ p = review_path(j, sid)
429
+ if p.exists() and json.loads(p.read_text()).get("status") in ("submitted", "ended_checklist"):
430
+ skipped.append(sid); continue
431
+ a = {k: v for k, v in (item.get("answers") or {}).items() if isinstance(k, str) and len(k) < 40 and k != "track"}
432
+ missing, ended = validate(a, sub.get("track"))
433
+ if missing:
434
+ bad.append({"submission": sid, "missing": missing}); continue
435
+ rec = {"submission": sid, "judge": j, "status": "ended_checklist" if ended else "submitted", "answers": a, "updated": stamp}
436
+ p.parent.mkdir(parents=True, exist_ok=True)
437
+ p.write_text(json.dumps(rec, indent=1))
438
+ paths.append(p); done.append(sid)
439
+ if paths and DATASET and HF_TOKEN:
440
+ from huggingface_hub import HfApi, CommitOperationAdd
441
+ try:
442
+ HfApi(token=HF_TOKEN).create_commit(DATASET, repo_type="dataset", commit_message=f"reviews {j} (bulk, {len(paths)})",
443
+ operations=[CommitOperationAdd(path_in_repo=str(p.relative_to(DATA)), path_or_fileobj=str(p)) for p in paths])
444
+ except Exception as e:
445
+ print("bulk push failed:", e)
446
+ return JSONResponse({"ok": False, "error": "Saved on the Space but not backed up yet. Please retry.", "saved": done}, status_code=502)
447
+ return {"ok": True, "judge": j, "saved": done, "skipped_already_submitted": skipped, "rejected": bad}