File size: 15,931 Bytes
b78ff28
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
 
49442cb
 
b78ff28
49442cb
 
 
 
 
 
 
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
 
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
 
 
 
 
 
 
b78ff28
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
 
b78ff28
 
 
49442cb
b78ff28
 
 
 
 
49442cb
 
 
b78ff28
 
 
 
 
 
 
 
 
 
 
49442cb
 
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
 
b78ff28
 
49442cb
 
 
b78ff28
 
 
 
 
 
49442cb
 
b78ff28
 
 
 
49442cb
b78ff28
 
 
 
 
 
 
49442cb
b78ff28
49442cb
b78ff28
49442cb
b78ff28
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
49442cb
 
b78ff28
 
 
49442cb
 
b78ff28
 
 
 
 
 
49442cb
 
b78ff28
 
 
 
 
49442cb
b78ff28
49442cb
 
 
b78ff28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
"""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/<benchmark>.parquet        every row's label and Lo-Hi split; never published
    submissions/<user>/<submission_id>/metadata.json
    submissions/<user>/<submission_id>/bundle.zip
    scores/<user>/<submission_id>/scores.json
    leaderboard/entries.csv                 one row per submission, incl. private fields

``PUBLIC_REPO`` (public dataset) — what participants download::

    <benchmark>/manifest.parquet            datapoint_id, row_index, protein id(s), split
    <benchmark>/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 ``<local_dir>/<benchmark>/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