dehezhang2 commited on
Commit
479db49
·
verified ·
1 Parent(s): 40eec04

deploy v2 study (40-runs baselines) at /v2/: dual-study backend + static/v2 rater UI; v1 study untouched

Browse files
Files changed (3) hide show
  1. app.py +90 -0
  2. static/v2/index.html +29 -2
  3. static/v2/mobile.html +22 -1
app.py CHANGED
@@ -118,9 +118,23 @@ def build_study_router(
118
  submissions_root: str,
119
  annotations_path: str,
120
  normalize_legacy: bool,
 
121
  ) -> APIRouter:
122
  """One study's full API surface, writing under its own dataset folders."""
123
  router = APIRouter(prefix=prefix)
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
  def _load_annotations() -> dict:
126
  """Return the study's current annotations file, or an empty shell."""
@@ -409,6 +423,80 @@ def build_study_router(
409
  raise HTTPException(502, f"delete failed ({status}): {e}")
410
  return JSONResponse({"ok": True, "deleted": path})
411
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
412
  @router.get("/rater_state")
413
  async def get_rater_state(email: str = ""):
414
  """Return the rater's most recent in-progress JSON (if any).
@@ -514,6 +602,7 @@ app.include_router(build_study_router(
514
  submissions_root="submissions",
515
  annotations_path="annotations.json",
516
  normalize_legacy=True,
 
517
  ))
518
 
519
  # v2 — the 40-runs baseline study; everything lives under v2/ in the dataset.
@@ -522,6 +611,7 @@ app.include_router(build_study_router(
522
  submissions_root="v2/submissions",
523
  annotations_path="v2/annotations.json",
524
  normalize_legacy=False,
 
525
  ))
526
 
527
  # Static rater UIs live in ./static (v1 at /, v2 at /v2/). Mount last so the
 
118
  submissions_root: str,
119
  annotations_path: str,
120
  normalize_legacy: bool,
121
+ cases_file: str,
122
  ) -> APIRouter:
123
  """One study's full API surface, writing under its own dataset folders."""
124
  router = APIRouter(prefix=prefix)
125
+ _case_ids_cache: list[str] = []
126
+
127
+ def _manifest_case_ids() -> list[str]:
128
+ """Case ids in manifest order, read from this study's static
129
+ cases.json (baked into the container image — safe to cache)."""
130
+ if not _case_ids_cache:
131
+ try:
132
+ with open(cases_file, "r", encoding="utf-8") as f:
133
+ _case_ids_cache.extend(
134
+ c["id"] for c in json.load(f) if c.get("id"))
135
+ except Exception:
136
+ pass
137
+ return _case_ids_cache
138
 
139
  def _load_annotations() -> dict:
140
  """Return the study's current annotations file, or an empty shell."""
 
423
  raise HTTPException(502, f"delete failed ({status}): {e}")
424
  return JSONResponse({"ok": True, "deleted": path})
425
 
426
+ @router.get("/assign_cases")
427
+ async def assign_cases(email: str = "", n: int = 10):
428
+ """Coverage-first case assignment for a newly registering rater.
429
+
430
+ Returns the `n` case ids with the FEWEST distinct raters covering
431
+ them so far (random tie-break, manifest order in the response), so
432
+ un-rated cases get picked up before already-rated ones. A case counts
433
+ as "covered" by a rater when that rater either has >=1 actual rating
434
+ on it or was assigned it at registration (`chosen_case_ids`) —
435
+ counting assignments too keeps two near-simultaneous registrants from
436
+ landing on the identical least-rated subset. The requesting rater's
437
+ own files are excluded.
438
+
439
+ The client treats this as advisory: on any failure it falls back to
440
+ its original per-rater seeded random pick.
441
+ """
442
+ email = (email or "").strip().lower()
443
+ manifest_ids = _manifest_case_ids()
444
+ if _api is None or not manifest_ids:
445
+ return JSONResponse({"case_ids": [], "reason": "unavailable"})
446
+ try:
447
+ tree_list = [
448
+ t for t in _api.list_repo_tree(
449
+ repo_id=DATASET_REPO, repo_type="dataset",
450
+ path_in_repo=submissions_root, recursive=True,
451
+ )
452
+ if getattr(t, "path", "").endswith(".json")
453
+ ]
454
+ except HfHubHTTPError as e:
455
+ status = e.response.status_code if e.response is not None else 500
456
+ if status != 404: # 404 = no submissions yet — zero coverage
457
+ return JSONResponse({"case_ids": [], "reason": f"HTTP {status}"})
458
+ tree_list = []
459
+
460
+ per_rater: dict[str, set] = {}
461
+ for t in tree_list:
462
+ try:
463
+ local = hf_hub_download(
464
+ repo_id=DATASET_REPO, repo_type="dataset",
465
+ filename=t.path, force_download=False,
466
+ )
467
+ with open(local, "r", encoding="utf-8") as f:
468
+ data = json.load(f)
469
+ except Exception:
470
+ continue
471
+ rater = data.get("rater") or {}
472
+ em = (rater.get("email") or "").strip().lower()
473
+ if email and em == email:
474
+ continue
475
+ covered = per_rater.setdefault(em or t.path, set())
476
+ for cid in rater.get("chosen_case_ids") or []:
477
+ covered.add(cid)
478
+ for case in data.get("cases") or []:
479
+ for v in case.get("videos") or []:
480
+ if any(_is_score(s) for s in (v.get("ratings") or {}).values()):
481
+ covered.add(case.get("id"))
482
+ break
483
+
484
+ coverage = {cid: 0 for cid in manifest_ids}
485
+ for covered in per_rater.values():
486
+ for cid in covered:
487
+ if cid in coverage:
488
+ coverage[cid] += 1
489
+
490
+ import random as _random
491
+ n = max(1, min(n, len(manifest_ids)))
492
+ picked = sorted(
493
+ manifest_ids,
494
+ key=lambda c: (coverage[c], _random.random()),
495
+ )[:n]
496
+ order = {cid: i for i, cid in enumerate(manifest_ids)}
497
+ picked.sort(key=lambda c: order[c])
498
+ return JSONResponse({"case_ids": picked, "coverage": coverage})
499
+
500
  @router.get("/rater_state")
501
  async def get_rater_state(email: str = ""):
502
  """Return the rater's most recent in-progress JSON (if any).
 
602
  submissions_root="submissions",
603
  annotations_path="annotations.json",
604
  normalize_legacy=True,
605
+ cases_file="static/cases.json",
606
  ))
607
 
608
  # v2 — the 40-runs baseline study; everything lives under v2/ in the dataset.
 
611
  submissions_root="v2/submissions",
612
  annotations_path="v2/annotations.json",
613
  normalize_legacy=False,
614
+ cases_file="static/v2/cases.json",
615
  ))
616
 
617
  # Static rater UIs live in ./static (v1 at /, v2 at /v2/). Mount last so the
static/v2/index.html CHANGED
@@ -1093,6 +1093,29 @@ function pickRandomSubsetIds(allCases) {
1093
  .map(i => allCases[i].id);
1094
  }
1095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1096
  function selectCasesForRater(allCases) {
1097
  if (isAdmin()) return allCases.slice();
1098
  if (allCases.length <= CASES_PER_RATER) return allCases.slice();
@@ -2516,9 +2539,13 @@ function handleRegistrationSubmit() {
2516
  // their locked case subset + earlier ratings carry across devices.
2517
  (async () => {
2518
  await recoverRaterStateFromServer(email);
 
 
 
2519
  // Now pick (or restore) the case subset. If chosen_case_ids came back
2520
- // from the server, selectCasesForRater honours it; otherwise it picks
2521
- // a fresh deterministic 10 and locks them in.
 
2522
  CASES = selectCasesForRater(ALL_CASES);
2523
  SHUFFLE = {};
2524
  buildShuffle(CASES);
 
1093
  .map(i => allCases[i].id);
1094
  }
1095
 
1096
+ // Coverage-first assignment: ask the server which cases have the fewest
1097
+ // raters so far, so un-rated videos get picked up before already-rated ones.
1098
+ // Advisory only — no-op if a locked list already exists, and any failure
1099
+ // (offline, server-less static hosting) falls back to the seeded random
1100
+ // pick in selectCasesForRater.
1101
+ async function assignCasesFromServer() {
1102
+ if (isAdmin()) return;
1103
+ if (Array.isArray(RATER.chosen_case_ids) && RATER.chosen_case_ids.length) return;
1104
+ if (!Array.isArray(ALL_CASES) || ALL_CASES.length <= CASES_PER_RATER) return;
1105
+ try {
1106
+ const r = await fetch(
1107
+ `./api/assign_cases?email=${encodeURIComponent(RATER.email || "")}&n=${CASES_PER_RATER}`,
1108
+ { cache: "no-cache" });
1109
+ if (!r.ok) return;
1110
+ const j = await r.json();
1111
+ const valid = new Set(ALL_CASES.map(c => c.id));
1112
+ const ids = (Array.isArray(j.case_ids) ? j.case_ids : []).filter(id => valid.has(id));
1113
+ if (ids.length >= Math.min(CASES_PER_RATER, ALL_CASES.length)) {
1114
+ RATER.chosen_case_ids = ids;
1115
+ }
1116
+ } catch (e) { /* fall back to seeded random */ }
1117
+ }
1118
+
1119
  function selectCasesForRater(allCases) {
1120
  if (isAdmin()) return allCases.slice();
1121
  if (allCases.length <= CASES_PER_RATER) return allCases.slice();
 
2539
  // their locked case subset + earlier ratings carry across devices.
2540
  (async () => {
2541
  await recoverRaterStateFromServer(email);
2542
+ // Fresh rater: prefer the server's coverage-first assignment (least-rated
2543
+ // cases first) over the local seeded random pick.
2544
+ await assignCasesFromServer();
2545
  // Now pick (or restore) the case subset. If chosen_case_ids came back
2546
+ // from the server (recovery or coverage-first assignment),
2547
+ // selectCasesForRater honours it; otherwise it picks a fresh
2548
+ // deterministic 10 and locks them in.
2549
  CASES = selectCasesForRater(ALL_CASES);
2550
  SHUFFLE = {};
2551
  buildShuffle(CASES);
static/v2/mobile.html CHANGED
@@ -754,6 +754,26 @@ function pickRandomSubsetIds(allCases){
754
  }
755
  return idx.slice(0,CASES_PER_RATER).sort((a,b)=>a-b).map(i => allCases[i].id);
756
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
757
  function selectCasesForRater(allCases){
758
  if (isAdmin()) return allCases.slice();
759
  if (allCases.length <= CASES_PER_RATER) return allCases.slice();
@@ -1361,9 +1381,10 @@ function handleRegister(){
1361
  if (!isAdmin()) anonymize = true;
1362
  closeRegister();
1363
  // Recover any prior locked case subset + ratings from the server first,
1364
- // then resolve the subset (locked > deterministic pick).
1365
  (async () => {
1366
  await recoverRaterStateFromServer(email);
 
1367
  CASES = selectCasesForRater(ALL_CASES);
1368
  SHUFFLE = {}; buildShuffle(CASES); saveState();
1369
  renderShell();
 
754
  }
755
  return idx.slice(0,CASES_PER_RATER).sort((a,b)=>a-b).map(i => allCases[i].id);
756
  }
757
+ // Coverage-first assignment: ask the server which cases have the fewest
758
+ // raters so far. Advisory — no-op if a locked list exists; any failure falls
759
+ // back to the seeded random pick in selectCasesForRater.
760
+ async function assignCasesFromServer(){
761
+ if (isAdmin()) return;
762
+ if (Array.isArray(RATER.chosen_case_ids) && RATER.chosen_case_ids.length) return;
763
+ if (!Array.isArray(ALL_CASES) || ALL_CASES.length <= CASES_PER_RATER) return;
764
+ try {
765
+ const r = await fetch(
766
+ `./api/assign_cases?email=${encodeURIComponent(RATER.email||"")}&n=${CASES_PER_RATER}`,
767
+ { cache: "no-cache" });
768
+ if (!r.ok) return;
769
+ const j = await r.json();
770
+ const valid = new Set(ALL_CASES.map(c => c.id));
771
+ const ids = (Array.isArray(j.case_ids) ? j.case_ids : []).filter(id => valid.has(id));
772
+ if (ids.length >= Math.min(CASES_PER_RATER, ALL_CASES.length)){
773
+ RATER.chosen_case_ids = ids;
774
+ }
775
+ } catch(e){ /* fall back to seeded random */ }
776
+ }
777
  function selectCasesForRater(allCases){
778
  if (isAdmin()) return allCases.slice();
779
  if (allCases.length <= CASES_PER_RATER) return allCases.slice();
 
1381
  if (!isAdmin()) anonymize = true;
1382
  closeRegister();
1383
  // Recover any prior locked case subset + ratings from the server first,
1384
+ // then resolve the subset (locked > coverage-first > deterministic pick).
1385
  (async () => {
1386
  await recoverRaterStateFromServer(email);
1387
+ await assignCasesFromServer();
1388
  CASES = selectCasesForRater(ALL_CASES);
1389
  SHUFFLE = {}; buildShuffle(CASES); saveState();
1390
  renderShell();