""" GRACE Reader Study - expert radiologist annotation app (Gradio / Hugging Face Space). Design goal: annotating one case requires ZERO scrolling and ZERO guessing. Everything needed to judge and score a case is visible at once: - two-column layout, one row per rated item (left = reference CXR, right = the item to score); - every rating control sits directly below the image it refers to; - full scale legends printed inline, subjective definitions in bold red with a worked example; - per-image zoom / brightness / contrast controls (display-only, never touch stored data); - no best/worst ranking asked; rankings are DERIVED in the backend from per-item scores. Auth: readers sign in the FIRST time with a one-time invite credential, then choose their own username + password (stored hashed in the private dataset). After that they log in with their own credentials; closing the tab does not sign them out. Secrets/config come from environment variables (set them as HF Space secrets): HF_TOKEN : HF token with write permission (for the private response/account dataset). RESPONSE_DATASET : private dataset repo id (default DrSyedFaizan/grace-reader-responses). CASES_DATASET : optional private dataset holding cases.json + images (snapshot at boot). READER_CREDENTIALS : JSON {"invite_name": "invite_password", ...} used ONLY for first-time login. APP_SECRET : secret string used to sign resume tokens (defaults derived from HF_TOKEN). NEVER commit Keys.txt or any token into the Space repo (see .gitignore). """ import os import io import json import time import base64 import random import hashlib import hmac import secrets from pathlib import Path import gradio as gr from PIL import Image # ----------------------------------------------------------------------------- config APP_DIR = Path(__file__).parent DATA_DIR = APP_DIR / "data" LOCAL_BACKUP_DIR = APP_DIR / "local_responses" LOCAL_BACKUP_DIR.mkdir(exist_ok=True) HF_TOKEN = os.environ.get("HF_TOKEN", "").strip() RESPONSE_DATASET = os.environ.get("RESPONSE_DATASET", "DrSyedFaizan/grace-reader-responses").strip() CASES_DATASET = os.environ.get("CASES_DATASET", "").strip() APP_SECRET = os.environ.get("APP_SECRET", "").strip() or ("grace-" + hashlib.sha256(HF_TOKEN.encode()).hexdigest()[:16] if HF_TOKEN else "grace-dev-secret") MAX_ITEMS = 6 # max anonymized items rated per case; keep cases small (2-3) to preserve no-scroll DISPLAY_MAX_W = 820 # px, display-copy width cap (does not affect stored data) SCHEMA_VERSION = 1 ACCOUNTS_PATH = "accounts/accounts.json" try: _invite = json.loads(os.environ.get("READER_CREDENTIALS", "").strip() or "{}") except Exception: _invite = {} if not _invite: _invite = {"reader1": "changeme", "reader2": "changeme"} print("[WARN] READER_CREDENTIALS not set - using demo invites. Set the secret before the real study.") INVITES = {str(k): str(v) for k, v in _invite.items()} # one-time first-login credentials # ----------------------------------------------------------------------------- HF api try: from huggingface_hub import HfApi _api = HfApi(token=HF_TOKEN) if HF_TOKEN else None except Exception as e: _api = None print(f"[WARN] huggingface_hub unavailable: {e}") def _ensure_response_dataset(): if not _api: return try: _api.create_repo(RESPONSE_DATASET, repo_type="dataset", private=True, exist_ok=True) except Exception as e: print(f"[WARN] could not ensure response dataset: {e}") # ----------------------------------------------------------------------------- cases def _maybe_pull_cases(): if not CASES_DATASET or not _api: return try: from huggingface_hub import snapshot_download snapshot_download(CASES_DATASET, repo_type="dataset", local_dir=str(DATA_DIR), token=HF_TOKEN, local_dir_use_symlinks=False) print(f"[info] pulled cases from {CASES_DATASET}") except Exception as e: print(f"[WARN] could not pull CASES_DATASET: {e}") def load_cases(): _maybe_pull_cases() cj = DATA_DIR / "cases.json" if not cj.exists(): print("[WARN] no data/cases.json - run build_cases_example.py to generate a demo set.") return [] with open(cj, "r", encoding="utf-8") as f: data = json.load(f) return data.get("cases", []) CASES = load_cases() N_CASES = len(CASES) _IMG_CACHE = {} def img_data_uri(rel_path): if not rel_path: return "" if rel_path in _IMG_CACHE: return _IMG_CACHE[rel_path] p = DATA_DIR / rel_path try: im = Image.open(p).convert("RGB") if im.width > DISPLAY_MAX_W: h = int(im.height * DISPLAY_MAX_W / im.width) im = im.resize((DISPLAY_MAX_W, h)) buf = io.BytesIO() im.save(buf, format="PNG") uri = "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode() except Exception as e: print(f"[WARN] image load failed {p}: {e}") uri = "" _IMG_CACHE[rel_path] = uri return uri # ----------------------------------------------------------------------------- tokens / passwords / accounts def make_token(name): return hmac.new(APP_SECRET.encode(), name.encode(), hashlib.sha256).hexdigest() def valid_token(name, tok): return bool(name) and bool(tok) and hmac.compare_digest(make_token(name), tok) def hash_pw(pw, salt): return hashlib.pbkdf2_hmac("sha256", pw.encode(), bytes.fromhex(salt), 100_000).hex() def verify_pw(pw, rec): try: return hmac.compare_digest(hash_pw(pw, rec["salt"]), rec["hash"]) except Exception: return False def load_accounts(): """Persistent account store: {"accounts": {user: {salt,hash,...}}, "claimed_invites": [...]}.""" default = {"accounts": {}, "claimed_invites": []} if _api: try: from huggingface_hub import hf_hub_download fp = hf_hub_download(RESPONSE_DATASET, ACCOUNTS_PATH, repo_type="dataset", token=HF_TOKEN) with open(fp, "r", encoding="utf-8") as f: d = json.load(f) d.setdefault("accounts", {}); d.setdefault("claimed_invites", []) return d except Exception: pass lb = LOCAL_BACKUP_DIR / "accounts.json" if lb.exists(): with open(lb, "r", encoding="utf-8") as f: return json.load(f) return default def save_accounts(acc): payload = json.dumps(acc, ensure_ascii=False, indent=2) with open(LOCAL_BACKUP_DIR / "accounts.json", "w", encoding="utf-8") as f: f.write(payload) if _api: try: _api.upload_file(path_or_fileobj=payload.encode("utf-8"), path_in_repo=ACCOUNTS_PATH, repo_id=RESPONSE_DATASET, repo_type="dataset", commit_message="update accounts") except Exception as e: print(f"[WARN] account upload failed (kept local): {e}") # ----------------------------------------------------------------------------- storage def _resp_path(annotator): return f"responses/{annotator}.jsonl" def load_existing_responses(annotator): records = [] if _api: try: from huggingface_hub import hf_hub_download fp = hf_hub_download(RESPONSE_DATASET, _resp_path(annotator), repo_type="dataset", token=HF_TOKEN) with open(fp, "r", encoding="utf-8") as f: return [json.loads(l) for l in f if l.strip()] except Exception: pass lb = LOCAL_BACKUP_DIR / f"{annotator}.jsonl" if lb.exists(): with open(lb, "r", encoding="utf-8") as f: records = [json.loads(l) for l in f if l.strip()] return records def completed_case_ids(records): return {r["case_id"] for r in records if r.get("item_id") == "__case__"} def save_records(annotator, new_records): existing = load_existing_responses(annotator) existing.extend(new_records) payload = "\n".join(json.dumps(r, ensure_ascii=False) for r in existing) + "\n" with open(LOCAL_BACKUP_DIR / f"{annotator}.jsonl", "w", encoding="utf-8") as f: f.write(payload) if _api: try: _api.upload_file(path_or_fileobj=payload.encode("utf-8"), path_in_repo=_resp_path(annotator), repo_id=RESPONSE_DATASET, repo_type="dataset", commit_message=f"responses {annotator} {int(time.time())}") except Exception as e: print(f"[WARN] HF upload failed (kept local backup): {e}") return existing # ----------------------------------------------------------------------------- ordering def item_order(annotator, case): items = list(case.get("items", [])) seed = int(hashlib.sha256(f"{annotator}|{case['case_id']}".encode()).hexdigest(), 16) % (2**32) random.Random(seed).shuffle(items) return items def first_unfinished(records): done = completed_case_ids(records) for i, c in enumerate(CASES): if c["case_id"] not in done: return i return N_CASES # ----------------------------------------------------------------------------- UI text def image_html(dom_id, uri): if not uri: return "
{intro}
"), gr.update(value=q), gr.update(value=image_html(f"gtref_{idx}", ref_uri)), gr.update(value=image_html(f"gt_{idx}", img_data_uri(case.get("groundtruth_image", "")))), gr.update(value=None), gr.update(value=progress), gr.update(value="", visible=False), ] ups = head + ref_ups + item_ups + ans_ups + corr_ups + appr_ups + grnd_ups + note_ups + row_ups return ups, order_ids # ---- navigation helpers (all return the SAME ALL_NAV-shaped list) -------------- def _blank_case(): return [gr.update() for _ in CASE_OUTPUTS] def nav_login(msg=""): return ([gr.update(value=""), gr.update(value=""), # tok_out, user_out gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), "", 0, [], "", # states gr.update(value=msg), gr.update(value="")] # login_msg, setup_msg + _blank_case()) def nav_setup(pending_invite, msg=""): return ([gr.update(value=""), gr.update(value=""), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), "", 0, [], pending_invite, gr.update(value=""), gr.update(value=msg)] + _blank_case()) def nav_study(username, token): records = load_existing_responses(username) idx = first_unfinished(records) ups, order_ids = render_case(username, idx, records) return ([gr.update(value=token), gr.update(value=username), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), username, idx, order_ids, "", gr.update(value=""), gr.update(value="")] + ups) ALL_NAV = ([tok_out, user_out, login_col, setup_col, study_col, annotator_state, index_state, order_state, pending_invite_state, login_msg, setup_msg] + CASE_OUTPUTS) # ---- auth handlers ------------------------------------------------------------- def do_login(name, pw): name = (name or "").strip() acc = load_accounts() custom = acc.get("accounts", {}) claimed = set(acc.get("claimed_invites", [])) if name in custom and verify_pw(pw, custom[name]): return nav_study(name, make_token(name)) if name in INVITES and name not in claimed and pw == INVITES[name]: return nav_setup(name) # first-time login -> account setup if name in INVITES and name in claimed: return nav_login("That first-time invite has already been used. Sign in with the username " "and password you created.") return nav_login("Invalid username or password.") def do_setup(new_user, new_pw, confirm, pending_invite): new_user = (new_user or "").strip() if not pending_invite: return nav_login("Session expired. Please sign in again.") if len(new_user) < 3: return nav_setup(pending_invite, "Choose a username of at least 3 characters.") if len(new_pw or "") < 6: return nav_setup(pending_invite, "Choose a password of at least 6 characters.") if new_pw != confirm: return nav_setup(pending_invite, "Passwords do not match.") acc = load_accounts() custom = acc.setdefault("accounts", {}) claimed = acc.setdefault("claimed_invites", []) if new_user in custom or new_user in INVITES: return nav_setup(pending_invite, "That username is taken. Choose another.") salt = secrets.token_hex(8) custom[new_user] = {"salt": salt, "hash": hash_pw(new_pw, salt), "invite": pending_invite, "created_ts": int(time.time())} if pending_invite not in claimed: claimed.append(pending_invite) save_accounts(acc) return nav_study(new_user, make_token(new_user)) def do_auto_login(name, tok): name = (name or "").strip() if not valid_token(name, tok): return nav_login("") if name in load_accounts().get("accounts", {}): return nav_study(name, tok) return nav_login("") login_btn.click(do_login, [name_in, pass_in], ALL_NAV).then( None, [user_out, tok_out], None, js=SET_LS_JS) setup_btn.click(do_setup, [su_user, su_pw, su_confirm, pending_invite_state], ALL_NAV).then( None, [user_out, tok_out], None, js=SET_LS_JS) # ---- save & next --------------------------------------------------------------- def do_save(annotator, idx, order_ids, case_ok, *rating_vals): M = MAX_ITEMS corr, appr, grnd, note = (rating_vals[0:M], rating_vals[M:2*M], rating_vals[2*M:3*M], rating_vals[3*M:4*M]) if idx >= N_CASES: return [idx, order_ids, gr.update(value="Nothing to save.")] + _blank_case() n_items = len(order_ids) missing = [] for i in range(n_items): if not corr[i]: missing.append(f"item {i+1}: correctness") if not appr[i]: missing.append(f"item {i+1}: appropriateness") if not grnd[i]: missing.append(f"item {i+1}: grounding") if not case_ok: missing.append("reference-acceptable question") if missing: msg = "Please complete before saving: " + "; ".join(missing[:6]) + ("..." if len(missing) > 6 else "") return [idx, order_ids, gr.update(value=msg)] + _blank_case() case = CASES[idx] ts = int(time.time()) new_records = [] for i in range(n_items): new_records.append({ "schema_version": SCHEMA_VERSION, "annotator": annotator, "case_id": case["case_id"], "item_id": order_ids[i], "shown_position": i, "dims": {"answer_correctness": corr[i], "decision_appropriateness": appr[i], "grounding_relevance": grnd[i], "note": note[i] or ""}, "ts": ts}) new_records.append({ "schema_version": SCHEMA_VERSION, "annotator": annotator, "case_id": case["case_id"], "item_id": "__case__", "dims": {"reference_acceptable": case_ok}, "shown_order": order_ids, "ts": ts}) records = save_records(annotator, new_records) nxt = first_unfinished(records) ups, new_order = render_case(annotator, nxt, records) return [nxt, new_order, gr.update(value="Saved.")] + ups SAVE_INPUTS = ([annotator_state, index_state, order_state, case_acceptable] + corr_rs + appr_rs + grnd_rs + note_tbs) SAVE_OUTPUTS = [index_state, order_state, status_md] + CASE_OUTPUTS save_btn.click(do_save, SAVE_INPUTS, SAVE_OUTPUTS) # ---- logout -------------------------------------------------------------------- def do_logout(): return (gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), "", 0, [], "") logout_btn.click(do_logout, None, [login_col, setup_col, study_col, annotator_state, index_state, order_state, pending_invite_state]).then(None, None, None, js=CLR_LS_JS) # ---- boot / resume ------------------------------------------------------------- demo.load(None, None, [user_ls, tok_ls], js=GET_LS_JS).then( do_auto_login, [user_ls, tok_ls], ALL_NAV) return demo if __name__ == "__main__": _ensure_response_dataset() build_app().queue().launch(server_name="0.0.0.0", server_port=7860)