"""Caption Preference Study v2 — Gradio Space. Participants sign in with first name, last name and UCSB perm number (case-insensitive). On first sign-in the participant's full trial list is generated (one version per scene, the least-shown version of that scene in the participant's group, plus the attention checks, shuffled; first-shown caption balanced half / half) and stored as ``results/.csv`` with empty ``preference`` / ``response_time``. Each choice fills one row. A returning participant continues at their first unanswered trial; nothing is ever regenerated. Groups (by order of first sign-in over the whole study): * participants 1-15: human caption vs aligned-model caption -> RESULTS_REPO_HUMAN * participants 16+: baseline-model caption vs aligned-model caption -> RESULTS_REPO_BASELINE; odd participant numbers get the "describes the image" instruction, even numbers the "what might be happening" instruction. Storage: every write goes to local disk first (atomic replace) and each results repo is synced by one background thread that pushes all changed files in a single commit at most every SYNC_EVERY_S seconds. Concurrent participants therefore never race each other's commits, and the Hub's commit rate stays far below its limits. """ from __future__ import annotations import atexit import html import json import os import random import re import shutil import signal import tarfile import tempfile import threading import time from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path import gradio as gr import pandas as pd from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download, snapshot_download HF_USER = "pmadinei" HF_TOKEN = os.environ.get("HF_TOKEN") IMAGES_REPO = os.environ.get("IMAGES_REPO", f"{HF_USER}/caption-preference-images") ASSETS_REPO = os.environ.get("ASSETS_REPO", f"{HF_USER}/caption-preference-v2-assets") IMAGES_ARCHIVE = "images.tar" RESULTS_REPO_HUMAN = os.environ.get("RESULTS_REPO_HUMAN", f"{HF_USER}/caption-preference-v2-human-vs-aligned") RESULTS_REPO_BASELINE = os.environ.get( "RESULTS_REPO_BASELINE", f"{HF_USER}/caption-preference-v2-baseline-vs-aligned" ) N_HUMAN_GROUP = int(os.environ.get("N_HUMAN_GROUP", "15")) SYNC_EVERY_S = float(os.environ.get("SYNC_EVERY_S", "60")) SYNC_MIN_GAP_S = float(os.environ.get("SYNC_MIN_GAP_S", "15")) RESPONSE_TIME_CAP = 100.0 HERE = Path(__file__).parent STIMULI_CSV = HERE / "stimuli_v2.csv" IMAGE_DIR = Path(os.environ.get("IMAGE_DIR", "/tmp/caption_experiment_images")) def _default_data_root() -> Path: persistent = Path("/data") if persistent.is_dir() and os.access(persistent, os.W_OK): return persistent / "caption_preference_v2" return Path("/tmp/caption_preference_v2") DATA_ROOT = Path(os.environ.get("DATA_ROOT", str(_default_data_root()))) INSTRUCTIONS = { "image": "Click the caption that better describes the image.", "scene": "Click the caption that better describes what might be happening in this scene.", } PERM_RE = re.compile(r"^[a-z0-9]{3,20}$") PARTICIPANT_COLUMNS = [ "participant_number", "perm", "first_name", "last_name", "group", "instruction", "registered_utc", ] api = HfApi(token=HF_TOKEN) def _log(msg: str) -> None: print(f"[{datetime.now(timezone.utc).strftime('%H:%M:%S')}] {msg}", flush=True) # --------------------------------------------------------------------------- # Stimuli and groups # --------------------------------------------------------------------------- STIM = pd.read_csv(STIMULI_CSV, dtype={"image_id": str}, keep_default_na=False) STIM["in_baseline_pool"] = STIM["in_baseline_pool"].astype(str).str.lower() == "true" STIM_BY_FILENAME = {r["filename"]: r for r in STIM.to_dict(orient="records")} TEST_ROWS = [r for r in STIM.to_dict(orient="records") if r["type"] == "test_group"] @dataclass class Group: key: str repo: str first_col: str # output CSV column of caption A second_col: str # output CSV column of caption B first_src: str # stimuli column of caption A second_src: str # stimuli column of caption B labels: tuple # which_caption_first values for A / B codes: tuple # preference codes for A / B pool_mask: pd.Series versions: dict = field(default_factory=dict) # image_id -> [filename, ...] counts: dict = field(default_factory=dict) # filename -> times assigned syncer: "RepoSyncer | None" = None @property def root(self) -> Path: return DATA_ROOT / self.key @property def columns(self) -> list: return ["id", "image_id", "filename", "type", self.first_col, self.second_col, "which_caption_first", "preference", "response_time"] def build_versions(self) -> None: pool = STIM[(STIM["type"] != "test_group") & self.pool_mask] self.versions = {iid: list(g["filename"]) for iid, g in pool.groupby("image_id", sort=True)} self.counts = {fn: 0 for fns in self.versions.values() for fn in fns} GROUPS = { "human": Group("human", RESULTS_REPO_HUMAN, "human_caption", "model_caption", "human_caption", "aligned_caption", ("human", "model"), ("H", "M"), STIM["type"] != "test_group"), "baseline": Group("baseline", RESULTS_REPO_BASELINE, "baseline_caption", "aligned_caption", "baseline_caption", "aligned_caption", ("baseline", "aligned"), ("B", "A"), STIM["in_baseline_pool"]), } for _g in GROUPS.values(): _g.build_versions() N_SCENES = len(GROUPS["human"].versions) TOTAL_TRIALS = N_SCENES + len(TEST_ROWS) _log(f"[startup] {len(STIM)} stimuli, {N_SCENES} scenes, {len(TEST_ROWS)} checks, {TOTAL_TRIALS} trials each; " f"baseline pool {sum(len(v) for v in GROUPS['baseline'].versions.values())} versions") # --------------------------------------------------------------------------- # Local storage + background Hub sync # # Every answer is written to local disk first. One RepoSyncer per results repo commits all changed files at once, # with ``parent_commit`` set to the last head it knows: if anything else committed in between (e.g. the previous # instance flushing its last answers during a restart), the commit is rejected, the remote files are merged into # memory row by row (answers only ever go from empty to filled), and the merged files are pushed next round. # --------------------------------------------------------------------------- READY = False STARTUP_ERROR = "" INSTANCE_ID = os.urandom(4).hex() _REGISTRY_LOCK = threading.Lock() # lock order: syncer push lock -> _REGISTRY_LOCK -> participant lock PARTICIPANTS: dict = {} # perm -> registry record (dict) _FRAMES: dict = {} # perm -> results DataFrame (authoritative in-memory copy) _FRAME_GROUP: dict = {} # perm -> group key _PLOCKS: dict = {} # perm -> threading.Lock _PLOCKS_GUARD = threading.Lock() _SHOWN_AT: dict = {} # perm -> (trial id, time shown) SYNC_STATE_FILE = "sync_state.json" def _plock(perm: str) -> threading.Lock: with _PLOCKS_GUARD: lock = _PLOCKS.get(perm) if lock is None: lock = _PLOCKS[perm] = threading.Lock() return lock def _atomic_write(path: Path, data: bytes) -> None: path.parent.mkdir(parents=True, exist_ok=True) fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".tmp_", suffix=path.suffix + ".part") try: with os.fdopen(fd, "wb") as f: f.write(data) f.flush() os.fsync(f.fileno()) os.replace(tmp, path) except BaseException: if os.path.exists(tmp): os.unlink(tmp) raise def _read_csv(path: Path) -> pd.DataFrame: return pd.read_csv(path, dtype=str, keep_default_na=False) def _answered(frame: pd.DataFrame) -> int: return int((frame["preference"].astype(str).str.strip() != "").sum()) def _results_rel(perm: str) -> str: return f"results/{perm}.csv" def _frame_bytes(group: "Group", frame: pd.DataFrame) -> bytes: return frame[group.columns].to_csv(index=False).encode() def _registry_bytes(group: "Group") -> bytes: recs = sorted((r for r in PARTICIPANTS.values() if r["group"] == group.key), key=lambda r: int(r["participant_number"])) return pd.DataFrame(recs, columns=PARTICIPANT_COLUMNS).to_csv(index=False).encode() def _write_frame(group: "Group", perm: str, frame: pd.DataFrame, soon: bool = False) -> None: _atomic_write(group.root / _results_rel(perm), _frame_bytes(group, frame)) group.syncer.mark(_results_rel(perm), soon=soon) def _recount(group: "Group") -> None: """Times each version was assigned in this group (all generated trial lists, answered or not).""" counts = {fn: 0 for fn in group.counts} for perm, frame in _FRAMES.items(): if _FRAME_GROUP.get(perm) == group.key: for fn in frame["filename"]: if fn in counts: counts[fn] += 1 group.counts = counts def _load_local(group: "Group") -> None: reg = group.root / "participants.csv" if reg.exists(): for rec in _read_csv(reg).to_dict(orient="records"): rec["perm"] = rec["perm"].strip().lower() PARTICIPANTS.setdefault(rec["perm"], rec) for path in sorted((group.root / "results").glob("*.csv")): _FRAMES[path.stem.lower()] = _read_csv(path) _FRAME_GROUP[path.stem.lower()] = group.key def _merge_remote(group: "Group", staging: Path) -> int: """Union of a downloaded snapshot and the in-memory state of ``group``; returns #answers taken from remote.""" taken = 0 with _REGISTRY_LOCK: reg_remote = staging / "participants.csv" if reg_remote.exists(): for rec in _read_csv(reg_remote).to_dict(orient="records"): rec["perm"] = rec["perm"].strip().lower() if rec["perm"] not in PARTICIPANTS: PARTICIPANTS[rec["perm"]] = rec remote_files = {p.stem.lower(): p for p in (staging / "results").glob("*.csv")} \ if (staging / "results").is_dir() else {} perms = set(remote_files) | {p for p, g in _FRAME_GROUP.items() if g == group.key} for perm in sorted(perms): with _plock(perm): remote = _read_csv(remote_files[perm]) if perm in remote_files else None local = _FRAMES.get(perm) if local is None: _FRAMES[perm], _FRAME_GROUP[perm] = remote, group.key _atomic_write(group.root / _results_rel(perm), _frame_bytes(group, remote)) continue if remote is not None and list(remote["id"]) == list(local["id"]): fill = (local["preference"].str.strip() == "") & (remote["preference"].str.strip() != "") if fill.any(): local.loc[fill, ["preference", "response_time"]] = \ remote.loc[fill, ["preference", "response_time"]].values taken += int(fill.sum()) _atomic_write(group.root / _results_rel(perm), _frame_bytes(group, local)) elif remote is not None: _log(f"[merge] WARNING: {group.key}/{perm}: remote trial list differs; keeping local") if remote is None or _frame_bytes(group, local) != remote_files[perm].read_bytes(): group.syncer.mark(_results_rel(perm)) data = _registry_bytes(group) _atomic_write(group.root / "participants.csv", data) if not reg_remote.exists() or reg_remote.read_bytes() != data: group.syncer.mark("participants.csv") _recount(group) return taken class RepoSyncer: """Pushes the changed files of one group to its dataset repo, all of them in one commit per round.""" def __init__(self, group: "Group"): self.group = group self.repo_id = group.repo self.root = group.root self.head: str | None = None self._dirty: set = set() self._lock = threading.Lock() self._push_lock = threading.Lock() self._wake = threading.Event() self._last_push = 0.0 self._failures = 0 self._n_commits = 0 self._thread = threading.Thread(target=self._loop, name=f"sync-{group.key}", daemon=True) def start(self) -> None: self._thread.start() def mark(self, *relpaths: str, soon: bool = False) -> None: with self._lock: self._dirty.update(relpaths) if soon: self._wake.set() def pending(self) -> int: with self._lock: return len(self._dirty) def _remote_head(self) -> str: return api.repo_info(self.repo_id, repo_type="dataset").sha def reconcile(self, head: str | None = None) -> None: """Download the repo at ``head`` and merge it into memory (and local disk).""" head = head or self._remote_head() staging = Path(tempfile.mkdtemp(prefix=f"remote_{self.group.key}_")) try: snapshot_download(repo_id=self.repo_id, repo_type="dataset", revision=head, local_dir=str(staging), token=HF_TOKEN, allow_patterns=["results/*.csv", "participants.csv"]) taken = _merge_remote(self.group, staging) finally: shutil.rmtree(staging, ignore_errors=True) self.head = head _log(f"[sync] {self.repo_id}: merged remote {head[:8]} ({taken} answer(s) taken from remote, " f"{self.pending()} file(s) to push)") def push(self) -> bool: if not HF_TOKEN: return False with self._push_lock: with self._lock: paths = sorted(self._dirty) self._dirty.clear() try: if not paths: head = self._remote_head() if head != self.head: self.reconcile(head) return True ops = [CommitOperationAdd(path_in_repo=p, path_or_fileobj=(self.root / p).read_bytes()) for p in paths if (self.root / p).exists()] state = {"instance": INSTANCE_ID, "commit": self._n_commits + 1, "utc": datetime.now(timezone.utc).isoformat(timespec="seconds"), "participants": sum(g == self.group.key for g in _FRAME_GROUP.values())} ops.append(CommitOperationAdd(path_in_repo=SYNC_STATE_FILE, path_or_fileobj=json.dumps(state).encode())) info = api.create_commit(repo_id=self.repo_id, repo_type="dataset", operations=ops, parent_commit=self.head, commit_message=f"Sync {len(ops) - 1} file(s)") self.head = info.oid self._n_commits += 1 self._last_push = time.time() self._failures = 0 _log(f"[sync] {self.repo_id}: pushed {len(ops) - 1} file(s)") return True except Exception as exc: # noqa: BLE001 with self._lock: self._dirty.update(paths) self._failures += 1 _log(f"[sync] {self.repo_id}: push of {len(paths)} file(s) failed ({exc}); will retry") try: head = self._remote_head() if head != self.head: self.reconcile(head) except Exception as exc2: # noqa: BLE001 _log(f"[sync] {self.repo_id}: could not reconcile ({exc2})") return False def _loop(self) -> None: while True: self._wake.wait(timeout=SYNC_EVERY_S) self._wake.clear() gap = SYNC_MIN_GAP_S - (time.time() - self._last_push) if gap > 0: time.sleep(gap) if not self.push(): time.sleep(min(120.0, 2.0 * 2 ** min(self._failures, 6)) + random.uniform(0, 3)) def _ensure_images() -> None: """Fetch the images as one archive (one file instead of 1,624: the Hub allows 1,000 requests per 5 min).""" IMAGE_DIR.mkdir(parents=True, exist_ok=True) if all((IMAGE_DIR / fn).exists() for fn in STIM["filename"]): return try: _log(f"[startup] downloading {ASSETS_REPO}/{IMAGES_ARCHIVE}") archive = hf_hub_download(repo_id=ASSETS_REPO, repo_type="dataset", filename=IMAGES_ARCHIVE, token=HF_TOKEN) with tarfile.open(archive) as tar: try: tar.extractall(IMAGE_DIR, filter="data") except TypeError: # Python without extraction filters (the archive is our own) tar.extractall(IMAGE_DIR) except Exception as exc: # noqa: BLE001 _log(f"[startup] archive unavailable ({exc}); downloading images one by one from {IMAGES_REPO}") snapshot_download(repo_id=IMAGES_REPO, repo_type="dataset", local_dir=str(IMAGE_DIR), token=HF_TOKEN, max_workers=8) def _startup() -> None: global READY, STARTUP_ERROR if not HF_TOKEN: STARTUP_ERROR = "HF_TOKEN is not set." _log(f"[startup] ERROR: {STARTUP_ERROR}") return try: _ensure_images() missing = [fn for fn in STIM["filename"] if not (IMAGE_DIR / fn).exists()] if missing: raise RuntimeError(f"{len(missing)} images missing, e.g. {missing[:3]}") for group in GROUPS.values(): group.root.mkdir(parents=True, exist_ok=True) _load_local(group) group.syncer = RepoSyncer(group) for attempt in range(6): try: group.syncer.reconcile() break except Exception as exc: # noqa: BLE001 if attempt == 5: raise RuntimeError(f"cannot download {group.repo}: {exc}") from exc time.sleep(2 * 2 ** attempt) group.syncer.start() if group.syncer.pending(): group.syncer.mark(soon=True) by_group = {k: sum(g == k for g in _FRAME_GROUP.values()) for k in GROUPS} _log(f"[startup] participants per group: {by_group}; registry entries: {len(PARTICIPANTS)}") READY = True _log(f"[startup] ready (instance {INSTANCE_ID}, data in {DATA_ROOT})") except Exception as exc: # noqa: BLE001 STARTUP_ERROR = str(exc) _log(f"[startup] ERROR: {exc}") def _flush_all(*_args) -> None: for group in GROUPS.values(): if group.syncer is not None and group.syncer.pending(): for _ in range(3): if group.syncer.push(): break def _on_sigterm(signum, frame) -> None: _log("[shutdown] SIGTERM: flushing results to the Hub") _flush_all() _log("[shutdown] done") os._exit(0) # Gradio's server thread would otherwise keep the process (and its sync threads) alive def _assign_trials(group: Group, rng: random.Random) -> pd.DataFrame: """Least-shown version per scene (ties at random), plus checks, shuffled, first caption balanced.""" chosen = [] for iid in sorted(group.versions): fns = group.versions[iid] low = min(group.counts[fn] for fn in fns) fn = rng.choice([f for f in fns if group.counts[f] == low]) group.counts[fn] += 1 chosen.append(STIM_BY_FILENAME[fn]) def first_labels(n: int) -> list: k = n // 2 if n % 2 == 0 else n // 2 + rng.randint(0, 1) labels = [group.labels[0]] * k + [group.labels[1]] * (n - k) rng.shuffle(labels) return labels rows = [] for stim_rows in (chosen, TEST_ROWS): for r, first in zip(stim_rows, first_labels(len(stim_rows))): rows.append({"id": str(r["id"]), "image_id": r["image_id"], "filename": r["filename"], "type": r["type"], group.first_col: r[group.first_src], group.second_col: r[group.second_src], "which_caption_first": first, "preference": "", "response_time": ""}) rng.shuffle(rows) return pd.DataFrame(rows, columns=group.columns) def _register(perm: str, first: str, last: str) -> dict: with _REGISTRY_LOCK: if perm in PARTICIPANTS: return PARTICIPANTS[perm] number = max((int(r["participant_number"]) for r in PARTICIPANTS.values()), default=0) + 1 if number <= N_HUMAN_GROUP: group_key, instruction = "human", "image" else: group_key, instruction = "baseline", ("image" if number % 2 == 1 else "scene") group = GROUPS[group_key] rng = random.Random(int.from_bytes(os.urandom(8), "big")) frame = _assign_trials(group, rng) rec = {"participant_number": str(number), "perm": perm, "first_name": first, "last_name": last, "group": group_key, "instruction": instruction, "registered_utc": datetime.now(timezone.utc).isoformat(timespec="seconds")} with _plock(perm): PARTICIPANTS[perm] = rec _FRAMES[perm], _FRAME_GROUP[perm] = frame, group_key _atomic_write(group.root / _results_rel(perm), _frame_bytes(group, frame)) _atomic_write(group.root / "participants.csv", _registry_bytes(group)) group.syncer.mark(_results_rel(perm), "participants.csv", soon=True) _log(f"[register] #{number} -> {group_key}/{instruction}") return rec def _next_trial(perm: str) -> dict | None: frame = _FRAMES[perm] todo = frame.index[frame["preference"].astype(str).str.strip() == ""] return None if len(todo) == 0 else frame.loc[todo[0]].to_dict() # --------------------------------------------------------------------------- # Gradio handlers # --------------------------------------------------------------------------- def _html_box(title: str, body: str) -> str: return (f'

{title}

' f'

{body}

') LOGIN_HTML = _html_box( "Caption Preference Study", "Please enter your first name, last name and UCSB perm number. If you have already started the study, use " "the same perm number to continue where you left off.", ) DONE_HTML = _html_box("All done — thank you for participating!", "Your responses are saved. You can close this tab.") def _welcome_html(rec: dict, answered: int) -> str: text = f"You will see images with two captions. {INSTRUCTIONS[rec['instruction']]}" if answered: text = (f"Welcome back, {html.escape(rec['first_name'])}! You have completed " f"{answered} of {TOTAL_TRIALS} trials and will continue where you left off.

" + text) return _html_box("Caption Preference Study", text) def _clean_name(value: str) -> str: return " ".join(str(value or "").split())[:60] def _normalize_perm(value: str) -> str: return re.sub(r"[\s\-]", "", str(value or "")).lower() def _panels(state=None, login=False, confirm=False, welcome=False, error="", confirm_md="", welcome_html="", done_html=""): """Outputs of the sign-in steps (order of ``signin_outputs``).""" return ( state, gr.update(visible=login), gr.update(visible=confirm), gr.update(visible=welcome), gr.update(value=done_html, visible=bool(done_html)), gr.update(value=error, visible=bool(error)), gr.update(value=confirm_md), gr.update(value=welcome_html), ) def _validate(first: str, last: str, perm_raw: str): first, last, perm = _clean_name(first), _clean_name(last), _normalize_perm(perm_raw) if not READY: return None, "The study server is still starting (or could not reach its storage). Please try again in a minute." if not first or not last: return None, "Please enter your **first name** and **last name**." if not PERM_RE.match(perm): return None, "Please enter a valid **perm number** (letters and digits only)." return (first, last, perm), "" def _existing_or_done(perm: str): rec = PARTICIPANTS[perm] if perm not in _FRAMES: _log(f"[sign-in] ERROR: registered participant #{rec['participant_number']} has no results file") return _panels(login=True, error="We could not load your record. Please contact the study organizer.") with _plock(perm): frame = _FRAMES[perm] answered = _answered(frame) done = _next_trial(perm) is None state = {"perm": perm} if done: return _panels(state, done_html=_html_box( "You've already completed this study.", f"Our records show you finished all {TOTAL_TRIALS} trials. Thank you — you can close this tab.")) return _panels(state, welcome=True, welcome_html=_welcome_html(rec, answered)) def sign_in(first: str, last: str, perm_raw: str): values, err = _validate(first, last, perm_raw) if err: return _panels(login=True, error=err) first, last, perm = values if perm in PARTICIPANTS: return _existing_or_done(perm) msg = (f"We have no record of perm number **{perm.upper()}**.\n\n" f"If this is your first time in the study, click **Yes, this is my first time**. If you have " f"participated before, go back and check your perm number so you can continue where you left off.") return _panels({"pending": values}, confirm=True, confirm_md=msg) def confirm_new(state: dict | None): if not state or "pending" not in state: return _panels(login=True, error="Please sign in again.") if not READY: return _panels(login=True, error="The study server is not ready. Please try again in a minute.") first, last, perm = state["pending"] _register(perm, first, last) return _existing_or_done(perm) def go_back(_state): return _panels(login=True) def _display(perm: str, restart_clock: bool): """Image + the two captions (first = left) of the participant's next trial, or None when finished.""" group = GROUPS[_FRAME_GROUP[perm]] with _plock(perm): frame = _FRAMES[perm] trial = _next_trial(perm) answered = _answered(frame) if trial is None: return None prev = _SHOWN_AT.get(perm) if restart_clock or prev is None or prev[0] != trial["id"]: _SHOWN_AT[perm] = (trial["id"], time.time()) a, b = trial[group.first_col], trial[group.second_col] left, right = (a, b) if trial["which_caption_first"] == group.labels[0] else (b, a) return (str(IMAGE_DIR / trial["filename"]), left, right, f"Trial {answered + 1} of {TOTAL_TRIALS}", trial["id"]) def _trial_outputs(state: dict, shown): if shown is None: return (state, gr.update(visible=False), gr.update(visible=False), gr.update(value=DONE_HTML, visible=True), None, gr.update(value=""), gr.update(value=""), "") img, left, right, progress, trial_id = shown state = {"perm": state["perm"], "trial_id": trial_id} return (state, gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), img, gr.update(value=left), gr.update(value=right), progress) EXPIRED_HTML = _html_box("Your session has expired.", "Please reload this page and sign in again with the same perm number to continue.") def _expired(state): return (state, gr.update(visible=False), gr.update(visible=False), gr.update(value=EXPIRED_HTML, visible=True), None, gr.update(value=""), gr.update(value=""), "") def begin(state: dict | None): if not state or state.get("perm") not in _FRAMES: return _expired(state) return _trial_outputs(state, _display(state["perm"], restart_clock=True)) def choose(state: dict | None, side: str): if not state or state.get("perm") not in _FRAMES or "trial_id" not in state: return _expired(state) perm, trial_id = state["perm"], state["trial_id"] group = GROUPS[_FRAME_GROUP[perm]] finished = False with _plock(perm): frame = _FRAMES[perm] idx = frame.index[frame["id"] == trial_id] if len(idx) and frame.at[idx[0], "preference"].strip() == "": i = idx[0] shown = _SHOWN_AT.get(perm) t0 = shown[1] if shown and shown[0] == trial_id else time.time() first_is_a = frame.at[i, "which_caption_first"] == group.labels[0] chose_a = first_is_a if side == "left" else not first_is_a frame.at[i, "preference"] = group.codes[0] if chose_a else group.codes[1] frame.at[i, "response_time"] = f"{min(time.time() - t0, RESPONSE_TIME_CAP):.3f}" finished = _next_trial(perm) is None _write_frame(group, perm, frame, soon=finished) return _trial_outputs(state, _display(perm, restart_clock=False)) # --------------------------------------------------------------------------- # UI # --------------------------------------------------------------------------- custom_css = """ .caption-btn { min-height: 140px !important; font-size: 1.05em !important; white-space: normal !important; line-height: 1.4 !important; padding: 16px !important; text-align: left !important; } .center-img img { max-height: 60vh !important; object-fit: contain !important; } .form-error { color: #b91c1c !important; } #login-panel, #confirm-panel, #welcome-panel { max-width: 640px !important; margin: 32px auto 0 auto !important; } .panel-text { font-size: 1.05em; } """ with gr.Blocks(title="Caption Preference Study", css=custom_css) as demo: state = gr.State() with gr.Column(visible=True, elem_id="login-panel") as login_panel: gr.HTML(LOGIN_HTML) first_in = gr.Textbox(label="First name", max_lines=1) last_in = gr.Textbox(label="Last name", max_lines=1) perm_in = gr.Textbox(label="UCSB perm number", max_lines=1) sign_in_btn = gr.Button("Continue", variant="primary", size="lg") error_md = gr.Markdown("", visible=False, elem_classes=["form-error"]) with gr.Column(visible=False, elem_id="confirm-panel") as confirm_panel: confirm_md = gr.Markdown("", elem_classes=["panel-text"]) confirm_btn = gr.Button("Yes, this is my first time", variant="primary", size="lg") back_btn = gr.Button("Go back") with gr.Column(visible=False, elem_id="welcome-panel") as welcome_panel: welcome_html = gr.HTML("") begin_btn = gr.Button("Start", variant="primary", size="lg") with gr.Column(visible=False) as trial_panel: progress_md = gr.Markdown("") image = gr.Image(label=None, show_label=False, interactive=False, elem_classes=["center-img"], show_download_button=False, show_share_button=False, show_fullscreen_button=False) with gr.Row(): left_btn = gr.Button("", elem_classes=["caption-btn"]) right_btn = gr.Button("", elem_classes=["caption-btn"]) done_panel = gr.HTML(visible=False) signin_outputs = [state, login_panel, confirm_panel, welcome_panel, done_panel, error_md, confirm_md, welcome_html] trial_outputs = [state, welcome_panel, trial_panel, done_panel, image, left_btn, right_btn, progress_md] sign_in_btn.click(sign_in, inputs=[first_in, last_in, perm_in], outputs=signin_outputs, api_name="sign_in") perm_in.submit(sign_in, inputs=[first_in, last_in, perm_in], outputs=signin_outputs, api_name=False) confirm_btn.click(confirm_new, inputs=[state], outputs=signin_outputs, api_name="confirm_new") back_btn.click(go_back, inputs=[state], outputs=signin_outputs, api_name=False) begin_btn.click(begin, inputs=[state], outputs=trial_outputs, api_name="begin") left_btn.click(lambda s: choose(s, "left"), inputs=[state], outputs=trial_outputs, api_name="choose_left") right_btn.click(lambda s: choose(s, "right"), inputs=[state], outputs=trial_outputs, api_name="choose_right") _startup() atexit.register(_flush_all) signal.signal(signal.SIGTERM, _on_sigterm) if __name__ == "__main__": demo.queue(default_concurrency_limit=64, max_size=None).launch( allowed_paths=[str(IMAGE_DIR)], server_name=os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0"), show_api=False, # server-side rendering shows the form before its event handlers are attached; clicks made in that # window are silently dropped ssr_mode=False, )