WitneyWW commited on
Commit
a333d52
·
1 Parent(s): ee87b42

questionnaire versions A/B/C with separate CSVs

Browse files
Files changed (1) hide show
  1. app.py +104 -46
app.py CHANGED
@@ -42,11 +42,16 @@ if DATASET_REPO and os.environ.get("HF_TOKEN"):
42
  try: # resume from the copy in the dataset
43
  api = HfApi(token=os.environ["HF_TOKEN"])
44
  api.create_repo(DATASET_REPO, repo_type="dataset", private=True, exist_ok=True)
45
- cached = hf_hub_download(DATASET_REPO, "responses.csv", repo_type="dataset", token=os.environ["HF_TOKEN"])
46
- RESP_CSV.write_bytes(Path(cached).read_bytes())
47
- print(f"restored {sum(1 for _ in open(RESP_CSV)) - 1} responses from {DATASET_REPO}")
48
- except Exception as e: # first run: nothing to restore
49
- print("no previous responses restored:", type(e).__name__, str(e)[:120])
 
 
 
 
 
50
  SCHEDULER = CommitScheduler(repo_id=DATASET_REPO, repo_type="dataset", folder_path=RESP_DIR,
51
  path_in_repo=".", every=2, private=True, token=os.environ["HF_TOKEN"],
52
  allow_patterns=["*.csv"])
@@ -55,18 +60,53 @@ ITEMS = json.load(open(MEDIA / "index.json"))
55
  # Narrations are judged one by one. An object has between 0 and NARR_MAX of them, so the
56
  # page holds NARR_MAX radio groups and shows only as many as the current object needs.
57
  NARR_MAX = max(1, max(len(it["events"]["narration"]) for it in ITEMS))
58
- COLUMNS = (["timestamp", "annotator", "video_id", "chunk", "object_id"] + [d[0] for d in DIMENSIONS]
59
  + ["narration_ids"] + [f"narration_{k + 1}" for k in range(NARR_MAX)] + ["comment"])
60
  NO_NARR_Q = ("No narration is linked to this object. Is that right — is there really no narration in this clip "
61
  "about it? (All narrations of the clip are listed in the cross-check panel.)")
62
 
63
- # A responses file written with a different column set (older version of the form) is kept
64
- # under another name instead of being appended to with misaligned columns.
65
- if RESP_CSV.exists():
66
- with open(RESP_CSV, newline="") as _f:
67
- _hdr = next(csv.reader(_f), None)
68
- if _hdr != COLUMNS:
69
- RESP_CSV.rename(RESP_DIR / f"responses_old_{datetime.now():%Y%m%d_%H%M%S}.csv")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
 
72
  def place(anchor):
@@ -208,33 +248,35 @@ def item_key(it):
208
 
209
 
210
  # ---------------------------------------------------------------- csv i/o
211
- def load_done(annotator):
212
  done = set()
213
- if RESP_CSV.exists():
214
- with open(RESP_CSV, newline="") as f:
 
215
  for r in csv.DictReader(f):
216
  if r["annotator"] == annotator:
217
  done.add((r["video_id"], r["chunk"], r["object_id"]))
218
  return done
219
 
220
 
221
- def _write(row):
222
- new = not RESP_CSV.exists()
223
- with open(RESP_CSV, "a", newline="") as f:
 
224
  w = csv.DictWriter(f, fieldnames=COLUMNS)
225
  if new:
226
  w.writeheader()
227
  w.writerow(row)
228
 
229
 
230
- def append_row(row):
231
  RESP_DIR.mkdir(exist_ok=True)
232
  with FileLock(str(LOCK)):
233
  if SCHEDULER is not None:
234
  with SCHEDULER.lock:
235
- _write(row)
236
  else:
237
- _write(row)
238
 
239
 
240
  # ---------------------------------------------------------------- rendering
@@ -310,20 +352,23 @@ def gallery_for(it):
310
  return [(str(MEDIA / k["path"]), f"t={k['t']:.2f}s frame {k['frame']}") for k in it["keyframes"]]
311
 
312
 
313
- def show(idx, annotator):
314
- idx = max(0, min(idx, N - 1))
315
- it = ITEMS[idx]
316
- done = load_done(annotator) if annotator else set()
 
 
317
  status = "✅ answered" if item_key(it) in done else "⬜ not answered"
318
- header = f"### {annotator or '?'} — item {idx + 1} / {N}   {status}   ({len(done)} / {N} done)"
 
319
  return ([idx, header, str(MEDIA / it["clip"]), gallery_for(it), annotation_md(it), crosscheck_md(it)]
320
  + dim_questions(it) + [None] * len(DIMENSIONS) + narration_updates(it) + [""])
321
 
322
 
323
- def first_unanswered(annotator):
324
- done = load_done(annotator)
325
- for i, it in enumerate(ITEMS):
326
- if item_key(it) not in done:
327
  return i
328
  return 0
329
 
@@ -350,10 +395,13 @@ CSS = """
350
  with gr.Blocks(title="Object-centric annotation eval") as demo:
351
  idx_state = gr.State(0)
352
  name_state = gr.State("")
 
353
 
354
  with gr.Column(visible=True) as login_col:
355
  gr.Markdown("# Object-centric annotation evaluation\nEnter your name to start (progress is saved per name).")
356
  name_in = gr.Textbox(label="Your name", placeholder="e.g. alice")
 
 
357
  start_btn = gr.Button("Start", variant="primary")
358
 
359
  with gr.Column(visible=False) as main_col:
@@ -407,38 +455,48 @@ with gr.Blocks(title="Object-centric annotation eval") as demo:
407
 
408
  outputs = [idx_state, header, video, gallery, ann_md, xc_md] + q_mds + radios + narr_mds + narr_radios + [comment]
409
 
410
- def start(name):
411
  name = (name or "").strip()
412
  if not name:
413
  raise gr.Error("Please enter your name.")
414
- i = first_unanswered(name)
415
- return [name, gr.update(visible=False), gr.update(visible=True)] + show(i, name)
 
 
 
 
 
 
 
 
 
 
416
 
417
- start_btn.click(start, [name_in], [name_state, login_col, main_col] + outputs)
418
- name_in.submit(start, [name_in], [name_state, login_col, main_col] + outputs)
419
 
420
- prev_btn.click(lambda i, n: show(i - 1, n), [idx_state, name_state], outputs)
421
- skip_btn.click(lambda i, n: show(i + 1, n), [idx_state, name_state], outputs)
422
 
423
- def submit(i, name, *vals):
424
  answers, narr_ans, cmt = vals[:len(DIMENSIONS)], vals[len(DIMENSIONS):-1], vals[-1]
425
- it = ITEMS[i]
 
426
  ns = narrations_of(it)
427
  need = max(1, len(ns))
428
  if any(a is None for a in answers) or any(a is None for a in narr_ans[:need]):
429
  raise gr.Error(f"Please answer all {len(DIMENSIONS)} questions and all {need} narration question(s) before submitting.")
430
- row = {"timestamp": datetime.now().isoformat(timespec="seconds"), "annotator": name,
431
  "video_id": it["video_id"], "chunk": it["chunk"], "object_id": it["object_id"],
432
  "comment": (cmt or "").strip()}
433
  row.update({d[0]: a for d, a in zip(DIMENSIONS, answers)})
434
  row["narration_ids"] = ";".join(str(e.get("id")) for e in ns) or "(none)"
435
  row.update({f"narration_{k + 1}": (narr_ans[k] if k < need else "") for k in range(NARR_MAX)})
436
- append_row(row)
437
- if i + 1 >= N:
438
- return show(i, name) + [f"**Saved.** That was the last item — all {N} done. Thank you!"]
439
- return show(i + 1, name) + [f"Saved `{it['object_id']}` → {RESP_CSV.name}"]
440
 
441
- submit_btn.click(submit, [idx_state, name_state] + radios + narr_radios + [comment], outputs + [msg])
442
 
443
  if __name__ == "__main__":
444
  ap = argparse.ArgumentParser()
 
42
  try: # resume from the copy in the dataset
43
  api = HfApi(token=os.environ["HF_TOKEN"])
44
  api.create_repo(DATASET_REPO, repo_type="dataset", private=True, exist_ok=True)
45
+ except Exception as e:
46
+ print("could not reach the responses dataset:", type(e).__name__, str(e)[:120])
47
+ for _v in ("A", "B", "C"): # one file per questionnaire version
48
+ try:
49
+ cached = hf_hub_download(DATASET_REPO, f"responses_{_v}.csv", repo_type="dataset",
50
+ token=os.environ["HF_TOKEN"])
51
+ (RESP_DIR / f"responses_{_v}.csv").write_bytes(Path(cached).read_bytes())
52
+ print(f"restored version {_v}: {sum(1 for _ in open(cached)) - 1} responses")
53
+ except Exception as e: # first run: nothing to restore
54
+ print(f"version {_v}: nothing restored ({type(e).__name__})")
55
  SCHEDULER = CommitScheduler(repo_id=DATASET_REPO, repo_type="dataset", folder_path=RESP_DIR,
56
  path_in_repo=".", every=2, private=True, token=os.environ["HF_TOKEN"],
57
  allow_patterns=["*.csv"])
 
60
  # Narrations are judged one by one. An object has between 0 and NARR_MAX of them, so the
61
  # page holds NARR_MAX radio groups and shows only as many as the current object needs.
62
  NARR_MAX = max(1, max(len(it["events"]["narration"]) for it in ITEMS))
63
+ COLUMNS = (["timestamp", "annotator", "version", "video_id", "chunk", "object_id"] + [d[0] for d in DIMENSIONS]
64
  + ["narration_ids"] + [f"narration_{k + 1}" for k in range(NARR_MAX)] + ["comment"])
65
  NO_NARR_Q = ("No narration is linked to this object. Is that right — is there really no narration in this clip "
66
  "about it? (All narrations of the clip are listed in the cross-check panel.)")
67
 
68
+ # ---- three shorter questionnaires --------------------------------------------------------
69
+ # 95 objects is too long for one sitting, so the clips are dealt into versions A / B / C
70
+ # (whole clips, so an annotator judges every object of the clips they watch; balanced by
71
+ # object count and spread over the videos). Each version writes its own CSV.
72
+ VERSIONS = ["A", "B", "C"]
73
+
74
+
75
+ def _split_versions():
76
+ clips = {}
77
+ for i, it in enumerate(ITEMS):
78
+ clips.setdefault((it["video_id"], it["chunk"]), []).append(i)
79
+ load = {v: 0 for v in VERSIONS}
80
+ out = {v: [] for v in VERSIONS}
81
+ by_video = {}
82
+ for key in clips:
83
+ by_video.setdefault(key[0], []).append(key)
84
+ for vid in sorted(by_video): # within a video, biggest clip first -> lightest version
85
+ taken = set()
86
+ for key in sorted(by_video[vid], key=lambda k: (-len(clips[k]), k)):
87
+ cand = [v for v in VERSIONS if v not in taken] or VERSIONS
88
+ v = min(cand, key=lambda x: (load[x], x))
89
+ taken.add(v)
90
+ out[v] += clips[key]
91
+ load[v] += len(clips[key])
92
+ return {v: sorted(ix) for v, ix in out.items()}
93
+
94
+
95
+ VERSION_ITEMS = _split_versions()
96
+
97
+
98
+ def resp_csv(version):
99
+ return RESP_DIR / f"responses_{version}.csv"
100
+
101
+
102
+ # A responses file written with a different column set (older form) is kept under another
103
+ # name instead of being appended to with misaligned columns.
104
+ for _p in [RESP_CSV] + [resp_csv(v) for v in VERSIONS]:
105
+ if _p.exists():
106
+ with open(_p, newline="") as _f:
107
+ _hdr = next(csv.reader(_f), None)
108
+ if _hdr != COLUMNS or _p == RESP_CSV:
109
+ _p.rename(RESP_DIR / f"{_p.stem}_old_{datetime.now():%Y%m%d_%H%M%S}.csv")
110
 
111
 
112
  def place(anchor):
 
248
 
249
 
250
  # ---------------------------------------------------------------- csv i/o
251
+ def load_done(annotator, version):
252
  done = set()
253
+ p = resp_csv(version)
254
+ if p.exists():
255
+ with open(p, newline="") as f:
256
  for r in csv.DictReader(f):
257
  if r["annotator"] == annotator:
258
  done.add((r["video_id"], r["chunk"], r["object_id"]))
259
  return done
260
 
261
 
262
+ def _write(row, version):
263
+ p = resp_csv(version)
264
+ new = not p.exists()
265
+ with open(p, "a", newline="") as f:
266
  w = csv.DictWriter(f, fieldnames=COLUMNS)
267
  if new:
268
  w.writeheader()
269
  w.writerow(row)
270
 
271
 
272
+ def append_row(row, version):
273
  RESP_DIR.mkdir(exist_ok=True)
274
  with FileLock(str(LOCK)):
275
  if SCHEDULER is not None:
276
  with SCHEDULER.lock:
277
+ _write(row, version)
278
  else:
279
+ _write(row, version)
280
 
281
 
282
  # ---------------------------------------------------------------- rendering
 
352
  return [(str(MEDIA / k["path"]), f"t={k['t']:.2f}s frame {k['frame']}") for k in it["keyframes"]]
353
 
354
 
355
+ def show(idx, annotator, version):
356
+ """idx is the position inside the chosen version's item list."""
357
+ ix = VERSION_ITEMS[version]
358
+ idx = max(0, min(idx, len(ix) - 1))
359
+ it = ITEMS[ix[idx]]
360
+ done = load_done(annotator, version) if annotator else set()
361
  status = "✅ answered" if item_key(it) in done else "⬜ not answered"
362
+ header = (f"### {annotator or '?'} · version {version} — item {idx + 1} / {len(ix)} &nbsp; {status} &nbsp; "
363
+ f"({len(done)} / {len(ix)} done)")
364
  return ([idx, header, str(MEDIA / it["clip"]), gallery_for(it), annotation_md(it), crosscheck_md(it)]
365
  + dim_questions(it) + [None] * len(DIMENSIONS) + narration_updates(it) + [""])
366
 
367
 
368
+ def first_unanswered(annotator, version):
369
+ done = load_done(annotator, version)
370
+ for i, k in enumerate(VERSION_ITEMS[version]):
371
+ if item_key(ITEMS[k]) not in done:
372
  return i
373
  return 0
374
 
 
395
  with gr.Blocks(title="Object-centric annotation eval") as demo:
396
  idx_state = gr.State(0)
397
  name_state = gr.State("")
398
+ ver_state = gr.State("A")
399
 
400
  with gr.Column(visible=True) as login_col:
401
  gr.Markdown("# Object-centric annotation evaluation\nEnter your name to start (progress is saved per name).")
402
  name_in = gr.Textbox(label="Your name", placeholder="e.g. alice")
403
+ ver_in = gr.Radio(VERSIONS, value="A", label="Questionnaire version (the one you were assigned)",
404
+ info=" · ".join(f"{v}: {len(VERSION_ITEMS[v])} objects" for v in VERSIONS))
405
  start_btn = gr.Button("Start", variant="primary")
406
 
407
  with gr.Column(visible=False) as main_col:
 
455
 
456
  outputs = [idx_state, header, video, gallery, ann_md, xc_md] + q_mds + radios + narr_mds + narr_radios + [comment]
457
 
458
+ def start(name, version):
459
  name = (name or "").strip()
460
  if not name:
461
  raise gr.Error("Please enter your name.")
462
+ if version not in VERSIONS:
463
+ raise gr.Error("Please choose a questionnaire version.")
464
+ i = first_unanswered(name, version)
465
+ return [name, version, gr.update(visible=False), gr.update(visible=True)] + show(i, name, version)
466
+
467
+ start_btn.click(start, [name_in, ver_in], [name_state, ver_state, login_col, main_col] + outputs)
468
+ name_in.submit(start, [name_in, ver_in], [name_state, ver_state, login_col, main_col] + outputs)
469
+
470
+ def preselect(request: gr.Request):
471
+ """A link like .../?v=B pre-selects that version."""
472
+ v = (request.query_params.get("v") or "").upper() if request else ""
473
+ return gr.update(value=v) if v in VERSIONS else gr.update()
474
 
475
+ demo.load(preselect, None, [ver_in])
 
476
 
477
+ prev_btn.click(lambda i, n, v: show(i - 1, n, v), [idx_state, name_state, ver_state], outputs)
478
+ skip_btn.click(lambda i, n, v: show(i + 1, n, v), [idx_state, name_state, ver_state], outputs)
479
 
480
+ def submit(i, name, version, *vals):
481
  answers, narr_ans, cmt = vals[:len(DIMENSIONS)], vals[len(DIMENSIONS):-1], vals[-1]
482
+ ix = VERSION_ITEMS[version]
483
+ it = ITEMS[ix[i]]
484
  ns = narrations_of(it)
485
  need = max(1, len(ns))
486
  if any(a is None for a in answers) or any(a is None for a in narr_ans[:need]):
487
  raise gr.Error(f"Please answer all {len(DIMENSIONS)} questions and all {need} narration question(s) before submitting.")
488
+ row = {"timestamp": datetime.now().isoformat(timespec="seconds"), "annotator": name, "version": version,
489
  "video_id": it["video_id"], "chunk": it["chunk"], "object_id": it["object_id"],
490
  "comment": (cmt or "").strip()}
491
  row.update({d[0]: a for d, a in zip(DIMENSIONS, answers)})
492
  row["narration_ids"] = ";".join(str(e.get("id")) for e in ns) or "(none)"
493
  row.update({f"narration_{k + 1}": (narr_ans[k] if k < need else "") for k in range(NARR_MAX)})
494
+ append_row(row, version)
495
+ if i + 1 >= len(ix):
496
+ return show(i, name, version) + [f"**Saved.** That was the last item of version {version} — all {len(ix)} done. Thank you!"]
497
+ return show(i + 1, name, version) + [f"Saved `{it['object_id']}` → {resp_csv(version).name}"]
498
 
499
+ submit_btn.click(submit, [idx_state, name_state, ver_state] + radios + narr_radios + [comment], outputs + [msg])
500
 
501
  if __name__ == "__main__":
502
  ap = argparse.ArgumentParser()