"""Persistence for the PLUG challenge, on the Hugging Face Hub. The OpenADMET template this challenge is modelled on keeps submissions, scores and leaderboards in S3 and scores them from a scheduled Lambda. PLUG is not blinded, so scoring can run synchronously inside the Space the moment a bundle is uploaded — which removes the queue, the container image and the whole AWS account. What is left is a storage layer, and two Hub dataset repos cover it: ``PRIVATE_REPO`` (private dataset) — everything the organisers hold:: ground_truth/.parquet every row's label and Lo-Hi split; never published submissions///metadata.json submissions///bundle.zip scores///scores.json leaderboard/entries.csv one row per submission, incl. private fields ``PUBLIC_REPO`` (public dataset) — what participants download:: /manifest.parquet datapoint_id, row_index, protein id(s), split /proteins.csv protein id -> Lo-Hi split Identifiers and splits only: no labels, sequences, mutations or ligands, because not every benchmark's licence allows redistributing them. Participants fetch the data itself from its original sources through plug's loaders, whose row order the ``row_index`` follows. The Space authenticates to both with a single ``HF_TOKEN`` secret. Labels live only in ``PRIVATE_REPO``, so a leaderboard number cannot be self-reported. """ import json import os import tempfile import time from datetime import UTC, datetime from functools import cache from pathlib import Path import pandas as pd from huggingface_hub import HfApi, hf_hub_download from huggingface_hub.errors import EntryNotFoundError, RepositoryNotFoundError from loguru import logger from .benchmarks import BENCHMARKS, ID_COLUMN, select_track # Dataset repos. Overridable by Space variables so a staging Space can point at # throwaway repos without a code change. PRIVATE_REPO: str = os.environ.get("PLUG_PRIVATE_REPO", "PrismScienceOrg/plug-challenge-private") PUBLIC_REPO: str = os.environ.get("PLUG_PUBLIC_REPO", "PrismScienceOrg/plug-challenge-data") HF_TOKEN: str | None = os.environ.get("HF_TOKEN") or None GROUND_TRUTH_PREFIX = "ground_truth" SUBMISSIONS_PREFIX = "submissions" SCORES_PREFIX = "scores" LEADERBOARD_PATH = "leaderboard/entries.csv" # Seconds a fetched leaderboard is reused before the Hub is asked again. The # Space refreshes its tables on a 30 s timer and on every page load, so without # this a handful of open tabs would re-download the same file continuously. LEADERBOARD_CACHE_TTL = 20.0 _leaderboard_cache: tuple[float, pd.DataFrame] | None = None def api() -> HfApi: """Return an ``HfApi`` client carrying the Space's token. Returns ------- HfApi Client for both dataset repos. """ return HfApi(token=HF_TOKEN) def configured() -> bool: """Report whether a token is available, i.e. the Space can read and write the repos. Returns ------- bool False in a local checkout with no ``HF_TOKEN``, which the Space surfaces as a "storage not configured" message rather than a traceback. """ return HF_TOKEN is not None @cache def load_ground_truth(benchmark: str) -> pd.DataFrame: """Download and cache one benchmark's ground truth, every row of it. Cached for the lifetime of the process: the labels do not change while a Space is running, and re-reading them per submission would add seconds to every upload. Parameters ---------- benchmark : str Benchmark name. Returns ------- pd.DataFrame Every row's labels and ``split``, with ``datapoint_id`` as a string column. ``select_track`` narrows it to what one track is scored on. Raises ------ FileNotFoundError If the benchmark has no ground-truth file in ``PRIVATE_REPO`` — i.e. it has not been staged yet. """ path = f"{GROUND_TRUTH_PREFIX}/{benchmark}.parquet" try: local = hf_hub_download( repo_id=PRIVATE_REPO, filename=path, repo_type="dataset", token=HF_TOKEN ) except (EntryNotFoundError, RepositoryNotFoundError) as exc: raise FileNotFoundError( f"No ground truth for {benchmark!r} at {PRIVATE_REPO}:{path}" ) from exc frame = pd.read_parquet(local) frame[ID_COLUMN] = frame[ID_COLUMN].astype(str) logger.info("Loaded ground truth for {}: {} rows.", benchmark, len(frame)) return frame def available_ground_truth(track: str) -> dict[str, pd.DataFrame]: """Load one track's ground truth for every benchmark that has been staged. Parameters ---------- track : str One of ``TRACKS``: the Lo-Hi test rows, or every row. Returns ------- dict[str, pd.DataFrame] Benchmark name -> ground truth, skipping benchmarks whose labels are not in ``PRIVATE_REPO`` yet. An empty dict means nothing can be scored. """ truth: dict[str, pd.DataFrame] = {} for spec in BENCHMARKS: try: truth[spec.name] = select_track(load_ground_truth(spec.name), track) except FileNotFoundError: logger.warning("Ground truth not staged for {} — skipping.", spec.name) return truth def expected_ids(truth: dict[str, pd.DataFrame]) -> dict[str, set[str]]: """Extract the set of ``datapoint_id`` values a submission must cover, per benchmark. Parameters ---------- truth : dict[str, pd.DataFrame] Per-benchmark ground truth. Returns ------- dict[str, set[str]] Benchmark name -> the ids a submission must cover. """ return {name: set(frame[ID_COLUMN].astype(str)) for name, frame in truth.items()} def upload_submission( safe_username: str, submission_id: str, bundle_path: Path, metadata: dict ) -> str: """Store one submission's bundle and metadata in the private repo. Parameters ---------- safe_username : str Path-safe Hugging Face username (see ``utils._safeify_username``). submission_id : str The submission's UUID. bundle_path : Path Local path to the uploaded ``.zip``. metadata : dict The serialised ``Submission`` model. Returns ------- str The repo path the bundle was stored at. """ prefix = f"{SUBMISSIONS_PREFIX}/{safe_username}/{submission_id}" client = api() client.upload_file( path_or_fileobj=str(bundle_path), path_in_repo=f"{prefix}/bundle.zip", repo_id=PRIVATE_REPO, repo_type="dataset", commit_message=f"submission {submission_id} bundle", ) client.upload_file( path_or_fileobj=json.dumps(metadata, indent=2, default=str).encode(), path_in_repo=f"{prefix}/metadata.json", repo_id=PRIVATE_REPO, repo_type="dataset", commit_message=f"submission {submission_id} metadata", ) logger.info("Stored submission {} for {}.", submission_id, safe_username) return f"{prefix}/bundle.zip" def save_scores(safe_username: str, submission_id: str, scores: dict) -> None: """Store one submission's scores, the per-submission source of truth. The leaderboard CSV is a derived, rewritten-in-place file; these per- submission JSONs are append-only and never overwritten, so ``rebuild_leaderboard`` can always reconstruct the board from them. Parameters ---------- safe_username : str Path-safe Hugging Face username. submission_id : str The submission's UUID. scores : dict Everything needed to rebuild one leaderboard row: the identity fields and the flattened per-benchmark metrics. """ api().upload_file( path_or_fileobj=json.dumps(scores, indent=2, default=str).encode(), path_in_repo=f"{SCORES_PREFIX}/{safe_username}/{submission_id}/scores.json", repo_id=PRIVATE_REPO, repo_type="dataset", commit_message=f"scores for submission {submission_id}", ) def read_leaderboard(use_cache: bool = True) -> pd.DataFrame: """Read the stored leaderboard entries. Parameters ---------- use_cache : bool Reuse a copy fetched within ``LEADERBOARD_CACHE_TTL`` seconds. Writers pass False so a read-modify-write never appends onto a stale table. Returns ------- pd.DataFrame One row per submission, or an empty frame when no leaderboard file exists yet (a fresh challenge) or the repo is unreachable. """ global _leaderboard_cache now = time.monotonic() if use_cache and _leaderboard_cache is not None: fetched_at, cached = _leaderboard_cache if now - fetched_at < LEADERBOARD_CACHE_TTL: return cached.copy() try: local = hf_hub_download( repo_id=PRIVATE_REPO, filename=LEADERBOARD_PATH, repo_type="dataset", token=HF_TOKEN, ) frame = pd.read_csv(local) except (EntryNotFoundError, RepositoryNotFoundError): logger.info("No leaderboard file yet at {}:{}.", PRIVATE_REPO, LEADERBOARD_PATH) frame = pd.DataFrame() except Exception as exc: logger.warning("Could not read the leaderboard: {}", exc) frame = pd.DataFrame() _leaderboard_cache = (now, frame) return frame.copy() def append_leaderboard_entry(entry: dict) -> None: """Add one scored submission to the leaderboard file. A read-modify-write, which can lose an entry if two submissions land in the same instant. The per-submission ``scores/`` JSONs are what make that recoverable — ``plug-challenge rebuild`` reconstructs the file from them. Parameters ---------- entry : dict The row to append. """ existing = read_leaderboard(use_cache=False) combined = ( pd.concat([existing, pd.DataFrame([entry])], ignore_index=True) if not existing.empty else pd.DataFrame([entry]) ) _upload_leaderboard(combined) def write_leaderboard(frame: pd.DataFrame) -> None: """Replace the leaderboard file wholesale (used by ``rebuild``). Parameters ---------- frame : pd.DataFrame The complete set of entries. """ _upload_leaderboard(frame) def _upload_leaderboard(frame: pd.DataFrame) -> None: """Serialise and upload the leaderboard entries, invalidating the read cache.""" global _leaderboard_cache with tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as handle: frame.to_csv(handle, index=False) path = handle.name api().upload_file( path_or_fileobj=path, path_in_repo=LEADERBOARD_PATH, repo_id=PRIVATE_REPO, repo_type="dataset", commit_message=f"leaderboard: {len(frame)} entries", ) Path(path).unlink(missing_ok=True) _leaderboard_cache = None logger.info("Wrote leaderboard with {} entries.", len(frame)) def all_scores() -> list[dict]: """Read every per-submission score file in the private repo. Parameters ---------- None Returns ------- list[dict] One dict per scored submission. Used by ``rebuild_leaderboard``; it is one request per submission, so it is a maintenance path rather than something a page load ever triggers. """ client = api() files = client.list_repo_files(repo_id=PRIVATE_REPO, repo_type="dataset") score_files = [f for f in files if f.startswith(f"{SCORES_PREFIX}/") and f.endswith(".json")] entries = [] for path in score_files: local = hf_hub_download( repo_id=PRIVATE_REPO, filename=path, repo_type="dataset", token=HF_TOKEN ) entries.append(json.loads(Path(local).read_text())) logger.info("Read {} score file(s).", len(entries)) return entries def last_submission_at(safe_username: str, track: str) -> datetime | None: """When this user last submitted to a track, for the submission cooldown. Read from the leaderboard file rather than by listing the repo, so a rejected-but-uploaded bundle does not count and the check is one request. Each track has its own cooldown, so entering both does not cost a day. Parameters ---------- safe_username : str Path-safe Hugging Face username. track : str The track being submitted to. An entry stored before tracks existed counts as ``supervised``. Returns ------- datetime | None UTC timestamp of the most recent scored submission, or None if there is none. """ frame = read_leaderboard() if frame.empty or "safe_username" not in frame.columns: return None tracks = frame["track"].fillna("supervised") if "track" in frame.columns else "supervised" mine = frame[(frame["safe_username"].astype(str) == safe_username) & (tracks == track)] if mine.empty: return None stamps = pd.to_datetime(mine["submitted_at"], utc=True, errors="coerce").dropna() if stamps.empty: return None return stamps.max().to_pydatetime().astimezone(UTC) def now() -> datetime: """Return the current UTC time, as one place for the tests to patch. Returns ------- datetime Timezone-aware UTC now. """ return datetime.now(UTC) def load_manifest(benchmark: str, local_dir: Path | None = None) -> pd.DataFrame: """Load one benchmark's public manifest. The manifest is the unlabelled counterpart of the ground truth — the same ``datapoint_id`` values and splits, the protein identifiers, no labels. It is what lets a participant validate a bundle locally (``plug-challenge validate``) without the organisers' token. Parameters ---------- benchmark : str Benchmark name. local_dir : Path | None Read ``//manifest.parquet`` instead of the Hub, for offline use and for the data build. Returns ------- pd.DataFrame Every row of the benchmark, with ``datapoint_id`` as a string column. Raises ------ FileNotFoundError If the manifest is neither on disk nor in ``PUBLIC_REPO``. """ path = f"{benchmark}/manifest.parquet" if local_dir is not None: candidate = local_dir / benchmark / "manifest.parquet" if not candidate.exists(): raise FileNotFoundError(f"No manifest at {candidate}") frame = pd.read_parquet(candidate) else: try: local = hf_hub_download( repo_id=PUBLIC_REPO, filename=path, repo_type="dataset", token=HF_TOKEN ) except (EntryNotFoundError, RepositoryNotFoundError) as exc: raise FileNotFoundError( f"No manifest for {benchmark!r} at {PUBLIC_REPO}:{path}" ) from exc frame = pd.read_parquet(local) frame[ID_COLUMN] = frame[ID_COLUMN].astype(str) return frame def manifest_ids(track: str, local_dir: Path | None = None) -> dict[str, set[str]]: """Collect the ``datapoint_id`` sets one track must cover, from the public manifests. Parameters ---------- track : str One of ``TRACKS``. local_dir : Path | None Read manifests from this directory instead of the Hub. Returns ------- dict[str, set[str]] Benchmark name -> its ids in this track, skipping benchmarks with no manifest. """ ids: dict[str, set[str]] = {} for spec in BENCHMARKS: try: manifest = load_manifest(spec.name, local_dir=local_dir) except FileNotFoundError: logger.warning("No manifest for {} — skipping.", spec.name) continue ids[spec.name] = set(select_track(manifest, track)[ID_COLUMN]) return ids