dehezhang2 commited on
Commit
20f5b4d
·
verified ·
1 Parent(s): e71c92c

deploy rater (Docker/FastAPI): registration + completeness gate + /api/submit → dataset

Browse files
Files changed (2) hide show
  1. app.py +105 -9
  2. static/index.html +171 -18
app.py CHANGED
@@ -24,6 +24,14 @@ from huggingface_hub.utils import HfHubHTTPError
24
 
25
  DATASET_REPO = "dehezhang2/Frameworker_User_Study"
26
 
 
 
 
 
 
 
 
 
27
  app = FastAPI(title="FrameWorker user-study backend")
28
 
29
  _TOKEN = os.environ.get("HF_TOKEN")
@@ -39,6 +47,31 @@ def _slug(s: str) -> str:
39
  return re.sub(r"[^A-Za-z0-9._-]+", "_", s).strip("_")[:64] or "anon"
40
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  @app.get("/api/health")
43
  def health():
44
  return {
@@ -58,13 +91,7 @@ async def submit(req: Request):
58
  except Exception as e:
59
  raise HTTPException(400, f"invalid JSON: {e}")
60
 
61
- rater = payload.get("rater") or {}
62
- name = (rater.get("name") or "").strip()
63
- email = (rater.get("email") or "").strip().lower()
64
- if not name:
65
- raise HTTPException(400, "rater.name is required")
66
- if not _EMAIL_RE.match(email):
67
- raise HTTPException(400, "rater.email must be a valid email address")
68
 
69
  rubric = payload.get("rubric") or []
70
  cases = payload.get("cases") or []
@@ -109,13 +136,15 @@ async def submit(req: Request):
109
  ts = dt.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
110
  fname = f"submissions/{_slug(email)}_{ts}_{uuid.uuid4().hex[:8]}.json"
111
 
112
- # Annotate the saved blob with the server's view of the submission.
 
113
  payload["_server"] = {
114
  "received_at_utc": dt.datetime.utcnow().isoformat() + "Z",
115
  "client_ip": req.client.host if req.client else None,
116
  "n_videos": n_videos,
117
  "n_scores": n_scores,
118
  "stored_as": fname,
 
119
  }
120
  blob = json.dumps(payload, indent=2, ensure_ascii=False).encode("utf-8")
121
 
@@ -125,7 +154,10 @@ async def submit(req: Request):
125
  repo_type="dataset",
126
  path_or_fileobj=BytesIO(blob),
127
  path_in_repo=fname,
128
- commit_message=f"submission from {email} ({n_scores} scores)",
 
 
 
129
  )
130
  except HfHubHTTPError as e:
131
  status = e.response.status_code if e.response is not None else 500
@@ -140,9 +172,73 @@ async def submit(req: Request):
140
  "stored_as": fname,
141
  "n_videos": n_videos,
142
  "n_scores": n_scores,
 
143
  }
144
  )
145
 
146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  # Static rater UI lives in ./static. Mount last so /api/* takes precedence.
148
  app.mount("/", StaticFiles(directory="static", html=True), name="static")
 
24
 
25
  DATASET_REPO = "dehezhang2/Frameworker_User_Study"
26
 
27
+ # Mirror of the client-side ADMIN_NAMES list. Matched case-insensitively
28
+ # against the rater's `name` field. Server-side computation is the
29
+ # authoritative one — clients can't spoof the flag by lying in the payload.
30
+ ADMIN_NAMES = {
31
+ "deheng zhang",
32
+ "zhendong li",
33
+ }
34
+
35
  app = FastAPI(title="FrameWorker user-study backend")
36
 
37
  _TOKEN = os.environ.get("HF_TOKEN")
 
47
  return re.sub(r"[^A-Za-z0-9._-]+", "_", s).strip("_")[:64] or "anon"
48
 
49
 
50
+ def _is_admin(name: str) -> bool:
51
+ return (name or "").strip().lower() in ADMIN_NAMES
52
+
53
+
54
+ def _count_scores(cases) -> int:
55
+ n = 0
56
+ for c in cases or []:
57
+ for v in c.get("videos", []) or []:
58
+ for s in (v.get("ratings") or {}).values():
59
+ if _is_score(s):
60
+ n += 1
61
+ return n
62
+
63
+
64
+ def _validate_rater(payload) -> tuple[str, str]:
65
+ rater = payload.get("rater") or {}
66
+ name = (rater.get("name") or "").strip()
67
+ email = (rater.get("email") or "").strip().lower()
68
+ if not name:
69
+ raise HTTPException(400, "rater.name is required")
70
+ if not _EMAIL_RE.match(email):
71
+ raise HTTPException(400, "rater.email must be a valid email address")
72
+ return name, email
73
+
74
+
75
  @app.get("/api/health")
76
  def health():
77
  return {
 
91
  except Exception as e:
92
  raise HTTPException(400, f"invalid JSON: {e}")
93
 
94
+ name, email = _validate_rater(payload)
 
 
 
 
 
 
95
 
96
  rubric = payload.get("rubric") or []
97
  cases = payload.get("cases") or []
 
136
  ts = dt.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
137
  fname = f"submissions/{_slug(email)}_{ts}_{uuid.uuid4().hex[:8]}.json"
138
 
139
+ is_admin = _is_admin(name)
140
+ payload["is_admin"] = is_admin
141
  payload["_server"] = {
142
  "received_at_utc": dt.datetime.utcnow().isoformat() + "Z",
143
  "client_ip": req.client.host if req.client else None,
144
  "n_videos": n_videos,
145
  "n_scores": n_scores,
146
  "stored_as": fname,
147
+ "status": "final",
148
  }
149
  blob = json.dumps(payload, indent=2, ensure_ascii=False).encode("utf-8")
150
 
 
154
  repo_type="dataset",
155
  path_or_fileobj=BytesIO(blob),
156
  path_in_repo=fname,
157
+ commit_message=(
158
+ f"submission from {email} ({n_scores} scores"
159
+ f"{' · admin' if is_admin else ''})"
160
+ ),
161
  )
162
  except HfHubHTTPError as e:
163
  status = e.response.status_code if e.response is not None else 500
 
172
  "stored_as": fname,
173
  "n_videos": n_videos,
174
  "n_scores": n_scores,
175
+ "is_admin": is_admin,
176
  }
177
  )
178
 
179
 
180
+ @app.post("/api/save_progress")
181
+ async def save_progress(req: Request):
182
+ """Write a per-rater in-progress snapshot to the dataset.
183
+
184
+ Used in two situations:
185
+ - Right after registration: page POSTs an empty payload (no ratings yet)
186
+ so the rater appears in `submissions/in_progress/` from the moment
187
+ they sign in. Useful for tracking participation start time and
188
+ identifying drop-offs.
189
+ - Mid-study auto-save (debounced) + manual "Save progress" button:
190
+ the same single per-user file is overwritten with the latest snapshot.
191
+
192
+ Unlike /api/submit, this does NOT require completeness — the payload may
193
+ have any subset of ratings (including none).
194
+ """
195
+ if _api is None:
196
+ raise HTTPException(500, "server missing HF_TOKEN secret")
197
+ try:
198
+ payload = await req.json()
199
+ except Exception as e:
200
+ raise HTTPException(400, f"invalid JSON: {e}")
201
+
202
+ name, email = _validate_rater(payload)
203
+ cases = payload.get("cases") or []
204
+ n_scores = _count_scores(cases)
205
+ is_admin = _is_admin(name)
206
+
207
+ fname = f"submissions/in_progress/{_slug(email)}.json"
208
+ payload["is_admin"] = is_admin
209
+ payload["_server"] = {
210
+ "received_at_utc": dt.datetime.utcnow().isoformat() + "Z",
211
+ "client_ip": req.client.host if req.client else None,
212
+ "n_scores": n_scores,
213
+ "stored_as": fname,
214
+ "status": "in_progress",
215
+ }
216
+ blob = json.dumps(payload, indent=2, ensure_ascii=False).encode("utf-8")
217
+ try:
218
+ _api.upload_file(
219
+ repo_id=DATASET_REPO,
220
+ repo_type="dataset",
221
+ path_or_fileobj=BytesIO(blob),
222
+ path_in_repo=fname,
223
+ commit_message=(
224
+ f"in-progress save from {email} ({n_scores} scores"
225
+ f"{' · admin' if is_admin else ''})"
226
+ ),
227
+ )
228
+ except HfHubHTTPError as e:
229
+ status = e.response.status_code if e.response is not None else 500
230
+ raise HTTPException(
231
+ status_code=502,
232
+ detail=f"failed to write to dataset ({status}): {e}",
233
+ )
234
+
235
+ return JSONResponse({
236
+ "ok": True,
237
+ "stored_as": fname,
238
+ "n_scores": n_scores,
239
+ "is_admin": is_admin,
240
+ })
241
+
242
+
243
  # Static rater UI lives in ./static. Mount last so /api/* takes precedence.
244
  app.mount("/", StaticFiles(directory="static", html=True), name="static")
static/index.html CHANGED
@@ -464,8 +464,12 @@ const STRINGS = {
464
  "submit_ready_title": "post your full rating set to the dataset",
465
  "submit_resubmit_title": "you've already submitted; click again to overwrite",
466
  "submit_enable_hint": "rate every question to enable",
 
 
467
  "export_json": "↓ Export JSON",
468
  "export_title": "save a local backup of your ratings",
 
 
469
  "reset_case": "↺ Reset case",
470
  "reset_all": "✕ Reset all",
471
  "submitted_badge": "✓ submitted",
@@ -543,6 +547,9 @@ const STRINGS = {
543
  "toast_submit_failed_http": "Submit failed (HTTP {0})",
544
  "toast_submit_failed": "Submit failed: {0}",
545
  "toast_exported": "Exported JSON",
 
 
 
546
  "toast_cleared_case": "Cleared ratings for {0}",
547
  "toast_reset_all": "All ratings reset",
548
  "toast_loaded_example": "Loaded cases.example.json — drop a real cases.json to override",
@@ -582,8 +589,12 @@ const STRINGS = {
582
  "submit_ready_title": "将完整评分发送至数据集",
583
  "submit_resubmit_title": "您已提交过;再次点击将覆盖",
584
  "submit_enable_hint": "请完成全部评分后再启用",
 
 
585
  "export_json": "↓ 导出 JSON",
586
  "export_title": "将评分另存为本地备份",
 
 
587
  "reset_case": "↺ 重置当前案例",
588
  "reset_all": "✕ 全部重置",
589
  "submitted_badge": "✓ 已提交",
@@ -661,6 +672,9 @@ const STRINGS = {
661
  "toast_submit_failed_http": "提交失败 (HTTP {0})",
662
  "toast_submit_failed": "提交失败:{0}",
663
  "toast_exported": "已导出 JSON",
 
 
 
664
  "toast_cleared_case": "已清空 {0} 的评分",
665
  "toast_reset_all": "已重置全部评分",
666
  "toast_loaded_example": "已加载 cases.example.json — 请放入真实的 cases.json 以覆盖",
@@ -700,8 +714,12 @@ const STRINGS = {
700
  "submit_ready_title": "изпратете пълния набор от оценки към набора от данни",
701
  "submit_resubmit_title": "вече сте изпратили; щракнете отново, за да презапишете",
702
  "submit_enable_hint": "оценете всеки въпрос, за да активирате",
 
 
703
  "export_json": "↓ Изтегли JSON",
704
  "export_title": "запази локално копие на оценките",
 
 
705
  "reset_case": "↺ Изчисти случая",
706
  "reset_all": "✕ Изчисти всичко",
707
  "submitted_badge": "✓ изпратено",
@@ -779,6 +797,9 @@ const STRINGS = {
779
  "toast_submit_failed_http": "Изпращането се провали (HTTP {0})",
780
  "toast_submit_failed": "Изпращането се провали: {0}",
781
  "toast_exported": "JSON е изтеглен",
 
 
 
782
  "toast_cleared_case": "Оценките за {0} са изчистени",
783
  "toast_reset_all": "Всички оценки са изчистени",
784
  "toast_loaded_example": "Заредено cases.example.json — поставете истински cases.json, за да го заместите",
@@ -921,6 +942,12 @@ let SYNC_STATUS = "idle";
921
  let SYNC_LAST_DETAIL = "";
922
  const API_SUBMIT = "./api/submit";
923
  const API_HEALTH = "./api/health";
 
 
 
 
 
 
924
 
925
  /* =========================================================================
926
  * Storage
@@ -958,19 +985,21 @@ function genRaterId() {
958
  * Shuffling (anonymization)
959
  * ========================================================================= */
960
  function buildShuffle(cases) {
961
- // Deterministic per (rater, case) so refresh keeps the same order.
 
 
 
 
 
962
  for (const c of cases) {
963
  if (SHUFFLE[c.id] && SHUFFLE[c.id].length === c.videos.length) continue;
964
  const indices = c.videos.map((_, i) => i);
965
- if (anonymize) {
966
- // Fisher–Yates seeded by hash of rater_id + case_id
967
- const seed = hashStr(RATER.id + ":" + c.id);
968
- let s = seed;
969
- for (let i = indices.length - 1; i > 0; i--) {
970
- s = (s * 1664525 + 1013904223) >>> 0;
971
- const j = s % (i + 1);
972
- [indices[i], indices[j]] = [indices[j], indices[i]];
973
- }
974
  }
975
  SHUFFLE[c.id] = indices;
976
  }
@@ -1014,6 +1043,8 @@ function setRating(caseId, slotIdx, qkey, score) {
1014
  setSyncStatus(SYNC_STATUS === "local-only" ? "local-only" : "idle",
1015
  t("pill_changed_after_submit"));
1016
  }
 
 
1017
  }
1018
 
1019
  /* =========================================================================
@@ -1119,6 +1150,96 @@ async function submitWholeStudy() {
1119
  }
1120
  }
1121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1122
  function setSyncStatus(state, detail) {
1123
  SYNC_STATUS = state;
1124
  if (detail) SYNC_LAST_DETAIL = detail;
@@ -1286,6 +1407,13 @@ function renderToolbar() {
1286
  }, RATER.email || ""),
1287
  ));
1288
 
 
 
 
 
 
 
 
1289
  if (RATER.submitted_at) {
1290
  tb.appendChild(el("span", { class: "submitted-badge",
1291
  title: t("submitted_badge_title") },
@@ -1320,6 +1448,12 @@ function renderToolbar() {
1320
  title: t("submit_enable_hint"),
1321
  }, t("submit_pending", 0)));
1322
 
 
 
 
 
 
 
1323
  tb.appendChild(el("button", {
1324
  class: "btn ghost",
1325
  onclick: exportJSON,
@@ -1586,15 +1720,14 @@ function renderVideoControls(c) {
1586
  // Per-row shuffle of slot positions. Seeded by (rater, case, q_key) so the
1587
  // order is deterministic across refreshes/devices for the same rater but
1588
  // independent across rows — prevents positional bias on any single question.
 
 
1589
  //
1590
  // LCGs have poor low-order bits, so a naive `s % (i+1)` over 2 slots was
1591
  // returning the same answer for ~90% of q_keys with a shared prefix. We
1592
  // (1) warm up the LCG several steps so similar seeds diverge, then
1593
  // (2) sample from the high bits of the state instead of the low bits.
1594
  function rowSlotOrder(caseId, qKey, slotCount) {
1595
- // Admin "Reveal models" mode short-circuits to the case-level order so the
1596
- // researcher can spot-check.
1597
- if (!anonymize) return Array.from({ length: slotCount }, (_, i) => i);
1598
  const idx = Array.from({ length: slotCount }, (_, i) => i);
1599
  let s = hashStr(RATER.id + ":" + caseId + ":" + qKey);
1600
  for (let k = 0; k < 6; k++) s = (s * 1664525 + 1013904223) >>> 0;
@@ -1772,9 +1905,9 @@ function updateCaseStatus(caseId) {
1772
  function toggleAnon() {
1773
  if (!isAdmin()) return; // gate: non-admins can't reveal models
1774
  anonymize = !anonymize;
1775
- // Re-shuffle (or un-shuffle) since the visual order can change
1776
- SHUFFLE = {};
1777
- buildShuffle(CASES);
1778
  saveState();
1779
  renderShell();
1780
  }
@@ -1856,8 +1989,19 @@ function handleRegistrationSubmit() {
1856
  saveState();
1857
  hideLoginOverlay();
1858
  renderShell();
1859
- probeSyncEndpoint();
1860
- showToast(t("toast_registered_as", name));
 
 
 
 
 
 
 
 
 
 
 
1861
  }
1862
 
1863
  // Sync the registration overlay's static markup to the current LANG so it
@@ -2006,6 +2150,15 @@ document.addEventListener("keydown", e => {
2006
  }
2007
  });
2008
 
 
 
 
 
 
 
 
 
 
2009
  /* =========================================================================
2010
  * Init
2011
  * ========================================================================= */
 
464
  "submit_ready_title": "post your full rating set to the dataset",
465
  "submit_resubmit_title": "you've already submitted; click again to overwrite",
466
  "submit_enable_hint": "rate every question to enable",
467
+ "save_progress": "💾 Save progress",
468
+ "save_progress_title": "upload your current ratings to the dataset under submissions/in_progress",
469
  "export_json": "↓ Export JSON",
470
  "export_title": "save a local backup of your ratings",
471
+ "admin_badge": "⚙ admin",
472
+ "admin_badge_title": "your name matches the admin list — submissions are flagged is_admin=true",
473
  "reset_case": "↺ Reset case",
474
  "reset_all": "✕ Reset all",
475
  "submitted_badge": "✓ submitted",
 
547
  "toast_submit_failed_http": "Submit failed (HTTP {0})",
548
  "toast_submit_failed": "Submit failed: {0}",
549
  "toast_exported": "Exported JSON",
550
+ "toast_progress_saved": "Progress saved ({0} ratings)",
551
+ "toast_progress_save_failed": "Progress save failed: {0}",
552
+ "toast_registered_saved": "Registered as {0} — start time recorded on the server",
553
  "toast_cleared_case": "Cleared ratings for {0}",
554
  "toast_reset_all": "All ratings reset",
555
  "toast_loaded_example": "Loaded cases.example.json — drop a real cases.json to override",
 
589
  "submit_ready_title": "将完整评分发送至数据集",
590
  "submit_resubmit_title": "您已提交过;再次点击将覆盖",
591
  "submit_enable_hint": "请完成全部评分后再启用",
592
+ "save_progress": "💾 保存进度",
593
+ "save_progress_title": "将当前评分上传到数据集的 submissions/in_progress 目录",
594
  "export_json": "↓ 导出 JSON",
595
  "export_title": "将评分另存为本地备份",
596
+ "admin_badge": "⚙ 管理员",
597
+ "admin_badge_title": "您的姓名在管理员列表中 — 提交将标记 is_admin=true",
598
  "reset_case": "↺ 重置当前案例",
599
  "reset_all": "✕ 全部重置",
600
  "submitted_badge": "✓ 已提交",
 
672
  "toast_submit_failed_http": "提交失败 (HTTP {0})",
673
  "toast_submit_failed": "提交失败:{0}",
674
  "toast_exported": "已导出 JSON",
675
+ "toast_progress_saved": "进度已保存({0} 项评分)",
676
+ "toast_progress_save_failed": "保存进度失败:{0}",
677
+ "toast_registered_saved": "已注册为 {0} — 起始时间已记录到服务器",
678
  "toast_cleared_case": "已清空 {0} 的评分",
679
  "toast_reset_all": "已重置全部评分",
680
  "toast_loaded_example": "已加载 cases.example.json — 请放入真实的 cases.json 以覆盖",
 
714
  "submit_ready_title": "изпратете пълния набор от оценки към набора от данни",
715
  "submit_resubmit_title": "вече сте изпратили; щракнете отново, за да презапишете",
716
  "submit_enable_hint": "оценете всеки въпрос, за да активирате",
717
+ "save_progress": "💾 Запази прогрес",
718
+ "save_progress_title": "качи текущите оценки в submissions/in_progress на набора от данни",
719
  "export_json": "↓ Изтегли JSON",
720
  "export_title": "запази локално копие на оценките",
721
+ "admin_badge": "⚙ администратор",
722
+ "admin_badge_title": "името ви е в списъка на администраторите — изпращанията се маркират с is_admin=true",
723
  "reset_case": "↺ Изчисти случая",
724
  "reset_all": "✕ Изчисти всичко",
725
  "submitted_badge": "✓ изпратено",
 
797
  "toast_submit_failed_http": "Изпращането се провали (HTTP {0})",
798
  "toast_submit_failed": "Изпращането се провали: {0}",
799
  "toast_exported": "JSON е изтеглен",
800
+ "toast_progress_saved": "Прогресът е запазен ({0} оценки)",
801
+ "toast_progress_save_failed": "Запазването на прогреса се провали: {0}",
802
+ "toast_registered_saved": "Регистриран(а) като {0} — началният час е записан на сървъра",
803
  "toast_cleared_case": "Оценките за {0} са изчистени",
804
  "toast_reset_all": "Всички оценки са изчистени",
805
  "toast_loaded_example": "Заредено cases.example.json — поставете истински cases.json, за да го заместите",
 
942
  let SYNC_LAST_DETAIL = "";
943
  const API_SUBMIT = "./api/submit";
944
  const API_HEALTH = "./api/health";
945
+ const API_SAVE_PROGRESS = "./api/save_progress";
946
+
947
+ // Debounce window for auto-save after the latest rating change.
948
+ const PROGRESS_DEBOUNCE_MS = 60000;
949
+ let PROGRESS_TIMER = null;
950
+ let LAST_PROGRESS_SAVED_AT = null;
951
 
952
  /* =========================================================================
953
  * Storage
 
985
  * Shuffling (anonymization)
986
  * ========================================================================= */
987
  function buildShuffle(cases) {
988
+ // Deterministic per (rater, case) so refresh keeps the same order, but
989
+ // ALWAYS shuffled — independent of the admin reveal toggle. The toggle
990
+ // only controls whether the model name is rendered next to the slot
991
+ // letter, never the slot order itself. Same LCG entropy fix as
992
+ // rowSlotOrder (warm-up + high-bit sample) so 2-way pairs don't get
993
+ // stuck producing the same order across cases.
994
  for (const c of cases) {
995
  if (SHUFFLE[c.id] && SHUFFLE[c.id].length === c.videos.length) continue;
996
  const indices = c.videos.map((_, i) => i);
997
+ let s = hashStr(RATER.id + ":" + c.id);
998
+ for (let k = 0; k < 6; k++) s = (s * 1664525 + 1013904223) >>> 0;
999
+ for (let i = indices.length - 1; i > 0; i--) {
1000
+ s = (s * 1664525 + 1013904223) >>> 0;
1001
+ const j = (s >>> 16) % (i + 1);
1002
+ [indices[i], indices[j]] = [indices[j], indices[i]];
 
 
 
1003
  }
1004
  SHUFFLE[c.id] = indices;
1005
  }
 
1043
  setSyncStatus(SYNC_STATUS === "local-only" ? "local-only" : "idle",
1044
  t("pill_changed_after_submit"));
1045
  }
1046
+ // Debounced server-side progress save (one file per rater, overwritten).
1047
+ scheduleProgressSave();
1048
  }
1049
 
1050
  /* =========================================================================
 
1150
  }
1151
  }
1152
 
1153
+ /* ----- Mid-study progress save ---------------------------------------- */
1154
+
1155
+ // Returns the same shape as the final-submission payload but tolerates
1156
+ // incomplete ratings. The server writes this to submissions/in_progress/<slug>.json
1157
+ // (one file per rater, overwritten on each save) so progress survives across
1158
+ // sessions even if localStorage is wiped.
1159
+ function buildProgressPayload() {
1160
+ const comp = studyCompleteness();
1161
+ return {
1162
+ rater: RATER,
1163
+ anonymize_used: anonymize,
1164
+ is_admin: isAdmin(),
1165
+ rubric: DIMENSIONS,
1166
+ progress_saved_at: new Date().toISOString(),
1167
+ completeness: {
1168
+ done: comp.done,
1169
+ expected: comp.expected,
1170
+ missing_count: comp.missing.length,
1171
+ },
1172
+ cases: CASES.map(c => {
1173
+ const slots = SHUFFLE[c.id] || c.videos.map((_, i) => i);
1174
+ return {
1175
+ id: c.id,
1176
+ category: c.category || null,
1177
+ prompt: c.prompt,
1178
+ videos: slots.map((origIdx, slotIdx) => ({
1179
+ slot: String.fromCharCode(65 + slotIdx),
1180
+ slot_index: slotIdx,
1181
+ original_index: origIdx,
1182
+ model: c.videos[origIdx].model,
1183
+ path: c.videos[origIdx].path,
1184
+ ratings: (RATINGS[c.id] || {})[slotIdx] || {},
1185
+ })),
1186
+ };
1187
+ }),
1188
+ };
1189
+ }
1190
+
1191
+ async function saveProgress(opts = {}) {
1192
+ // opts: { silent: bool, source: "register" | "auto" | "manual" | "unload" }
1193
+ const silent = !!opts.silent;
1194
+ if (!RATER.email || !RATER.name) return; // no rater yet
1195
+ if (SYNC_STATUS === "local-only" && opts.source !== "manual") return;
1196
+
1197
+ const payload = buildProgressPayload();
1198
+ try {
1199
+ const resp = await fetch(API_SAVE_PROGRESS, {
1200
+ method: "POST",
1201
+ headers: { "Content-Type": "application/json" },
1202
+ body: JSON.stringify(payload),
1203
+ });
1204
+ if (resp.ok) {
1205
+ const body = await resp.json().catch(() => ({}));
1206
+ LAST_PROGRESS_SAVED_AT = new Date().toISOString();
1207
+ if (!silent) showToast(t("toast_progress_saved", body.n_scores ?? 0));
1208
+ } else if (resp.status === 404 || resp.status === 503) {
1209
+ // Server not present (e.g. running against a static host); switch off
1210
+ // auto-save so we don't keep retrying every minute.
1211
+ setSyncStatus("local-only", `save_progress HTTP ${resp.status}`);
1212
+ } else if (!silent) {
1213
+ showToast(t("toast_progress_save_failed", "HTTP " + resp.status), true);
1214
+ }
1215
+ } catch (e) {
1216
+ if (!silent) showToast(t("toast_progress_save_failed", e.message), true);
1217
+ }
1218
+ }
1219
+
1220
+ function scheduleProgressSave() {
1221
+ if (!RATER.email) return;
1222
+ if (SYNC_STATUS === "local-only") return;
1223
+ if (PROGRESS_TIMER) clearTimeout(PROGRESS_TIMER);
1224
+ PROGRESS_TIMER = setTimeout(() => {
1225
+ PROGRESS_TIMER = null;
1226
+ saveProgress({ silent: true, source: "auto" });
1227
+ }, PROGRESS_DEBOUNCE_MS);
1228
+ }
1229
+
1230
+ // Fire-and-forget best-effort save when the tab is closed or navigated away.
1231
+ // `fetch` from beforeunload is unreliable; sendBeacon is designed for this.
1232
+ function beaconProgress() {
1233
+ if (!RATER.email || !RATER.name) return;
1234
+ if (SYNC_STATUS === "local-only") return;
1235
+ try {
1236
+ const blob = new Blob(
1237
+ [JSON.stringify(buildProgressPayload())],
1238
+ { type: "application/json" });
1239
+ navigator.sendBeacon(API_SAVE_PROGRESS, blob);
1240
+ } catch (e) { /* best-effort, ignore */ }
1241
+ }
1242
+
1243
  function setSyncStatus(state, detail) {
1244
  SYNC_STATUS = state;
1245
  if (detail) SYNC_LAST_DETAIL = detail;
 
1407
  }, RATER.email || ""),
1408
  ));
1409
 
1410
+ if (isAdmin()) {
1411
+ tb.appendChild(el("span", { class: "submitted-badge",
1412
+ style: "background:#3a2f60;color:#d9b6ff;border-color:#5a4080",
1413
+ title: t("admin_badge_title") },
1414
+ t("admin_badge")));
1415
+ }
1416
+
1417
  if (RATER.submitted_at) {
1418
  tb.appendChild(el("span", { class: "submitted-badge",
1419
  title: t("submitted_badge_title") },
 
1448
  title: t("submit_enable_hint"),
1449
  }, t("submit_pending", 0)));
1450
 
1451
+ tb.appendChild(el("button", {
1452
+ class: "btn ghost",
1453
+ onclick: () => saveProgress({ silent: false, source: "manual" }),
1454
+ title: t("save_progress_title"),
1455
+ }, t("save_progress")));
1456
+
1457
  tb.appendChild(el("button", {
1458
  class: "btn ghost",
1459
  onclick: exportJSON,
 
1720
  // Per-row shuffle of slot positions. Seeded by (rater, case, q_key) so the
1721
  // order is deterministic across refreshes/devices for the same rater but
1722
  // independent across rows — prevents positional bias on any single question.
1723
+ // Always-on (independent of the admin reveal toggle); the toggle only
1724
+ // controls whether model names are rendered next to slot letters.
1725
  //
1726
  // LCGs have poor low-order bits, so a naive `s % (i+1)` over 2 slots was
1727
  // returning the same answer for ~90% of q_keys with a shared prefix. We
1728
  // (1) warm up the LCG several steps so similar seeds diverge, then
1729
  // (2) sample from the high bits of the state instead of the low bits.
1730
  function rowSlotOrder(caseId, qKey, slotCount) {
 
 
 
1731
  const idx = Array.from({ length: slotCount }, (_, i) => i);
1732
  let s = hashStr(RATER.id + ":" + caseId + ":" + qKey);
1733
  for (let k = 0; k < 6; k++) s = (s * 1664525 + 1013904223) >>> 0;
 
1905
  function toggleAnon() {
1906
  if (!isAdmin()) return; // gate: non-admins can't reveal models
1907
  anonymize = !anonymize;
1908
+ // The shuffle is anonymize-independent now, so we don't wipe SHUFFLE here —
1909
+ // only re-render so the slot labels switch between "Video A" and
1910
+ // "Video A · ours".
1911
  saveState();
1912
  renderShell();
1913
  }
 
1989
  saveState();
1990
  hideLoginOverlay();
1991
  renderShell();
1992
+ // Probe the server, then drop an empty in-progress entry so the rater
1993
+ // appears in submissions/in_progress/ immediately on registration. Saving
1994
+ // happens asynchronously and falls back silently if the server isn't
1995
+ // reachable (local-only mode).
1996
+ (async () => {
1997
+ await probeSyncEndpoint();
1998
+ if (SYNC_STATUS !== "local-only") {
1999
+ await saveProgress({ silent: true, source: "register" });
2000
+ showToast(t("toast_registered_saved", name));
2001
+ } else {
2002
+ showToast(t("toast_registered_as", name));
2003
+ }
2004
+ })();
2005
  }
2006
 
2007
  // Sync the registration overlay's static markup to the current LANG so it
 
2150
  }
2151
  });
2152
 
2153
+ // Best-effort save on tab close / navigation. `fetch` from beforeunload is
2154
+ // unreliable; sendBeacon is built for fire-and-forget on unload.
2155
+ window.addEventListener("beforeunload", beaconProgress);
2156
+ // Some browsers throttle beforeunload but honour visibilitychange='hidden',
2157
+ // which fires on tab close, switch-away, and mobile background.
2158
+ document.addEventListener("visibilitychange", () => {
2159
+ if (document.visibilityState === "hidden") beaconProgress();
2160
+ });
2161
+
2162
  /* =========================================================================
2163
  * Init
2164
  * ========================================================================= */