PLUG-challenge / submission.py
alanclayrichard's picture
lohi splits and supervised and unsupervised tracks
49442cb
Raw History Blame Contribute Delete
16 kB
"""The Submit tab: validate, score and record one submission bundle.
Because PLUG is not blinded, everything happens inside the request β€” the bundle
is validated, scored against the held-back labels, stored, and added to the
leaderboard before the participant's status box updates. There is no queue and
nothing to wait for, so the response can show the participant their own
{n} metrics and their PLUG Score immediately.
The order of operations matters. The bundle is validated *before* anything is
uploaded, so a malformed submission costs the participant nothing and does not
start their cooldown; the bundle and metadata are stored before the leaderboard
is touched, so a failure part-way through leaves a recoverable record rather
than a leaderboard row with no submission behind it.
"""
import re
from datetime import datetime, timedelta
from pathlib import Path
import gradio as gr
import pandas as pd
from loguru import logger
from config import (
BENCHMARK_COUNT,
BOOTSTRAP_SAMPLES,
BUNDLE_TREE_MD,
CURRENT_PHASE,
DATASET_DOWNLOAD_LINK,
HOURS_BETWEEN_SUBMISSIONS,
REQUIRE_COMPLETE_BUNDLE,
SUBMISSION_SCHEMAS_MD,
TUTORIAL_LINK,
)
from models import Submission
from plug_challenge import BENCHMARKS, aggregate, scoring, store
from plug_challenge.benchmarks import TRACK_DESCRIPTIONS, TRACK_LABELS, TRACKS
from plug_challenge.validation import validate_bundle
from utils import (
BANNED_USERNAMES,
safeify_username,
validate_hf_username,
validate_model_details,
)
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
_TRACKS_MD = "\n".join(
f"- **{TRACK_LABELS[track]}** β€” {TRACK_DESCRIPTIONS[track]}" for track in TRACKS
)
_INTRO_MD = f"""New to the challenge? The [PLUG baselines]({TUTORIAL_LINK}) walk through
loading each benchmark and producing predictions. The [challenge dataset]({DATASET_DOWNLOAD_LINK})
holds the row ids and Lo-Hi splits; the labels come from each benchmark's original source.
Every submission enters one of two leaderboards:
{_TRACKS_MD}
A submission is **one `.zip`** containing one file per benchmark
({BENCHMARK_COUNT} files{", all required" if REQUIRE_COMPLETE_BUNDLE else ""}):
{BUNDLE_TREE_MD}
Build the skeleton for your track and check it before uploading:
```bash
pip install "plug-challenge @ git+https://huggingface.co/spaces/PrismScienceOrg/PLUG-challenge"
plug-challenge template ./my_submission --track supervised # every file, ids in place
# ...fill in the prediction columns...
cd my_submission && zip ../plug_submission.zip *.csv && cd ..
plug-challenge validate plug_submission.zip --track supervised # the checks this Space runs
```
<details>
<summary><b>Per-file column reference</b></summary>
{SUBMISSION_SCHEMAS_MD}
</details>
"""
def render_submission_tab(phase: int) -> None:
"""Render the Submit tab for the current challenge phase.
Parameters
----------
phase : int
``config.CURRENT_PHASE``: 0 pre-challenge, 1 open, 2 closed.
"""
if phase == 0:
gr.Markdown(
"# Submission portal (coming soon)\n\n"
"The portal opens when the challenge begins. Please check back then."
)
return
if phase >= 2:
gr.Markdown(
"# Submission portal (closed)\n\n"
"Submissions are closed β€” thank you for taking part. The final standings are "
"on the **Leaderboard** tab."
)
return
gr.Markdown("# Submit your predictions")
gr.Markdown(_INTRO_MD)
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### Leaderboard identity")
track_input = gr.Radio(
choices=[(TRACK_LABELS[track], track) for track in TRACKS],
value="supervised",
label="Track *",
info="Which leaderboard this submission enters.",
)
username_input = gr.Textbox(
label="Hugging Face username *",
placeholder="your-hf-username",
info="Required. Used to track submissions and to rate-limit them.",
)
user_alias = gr.Textbox(
label="Alias (display name for the leaderboard; anonymous by default)",
placeholder="Leakage-Free Learners",
)
anon_checkbox = gr.Checkbox(
label="Submit anonymously (show the alias instead of my username)",
value=True,
)
proprietary_checkbox = gr.Checkbox(
label="I used proprietary (not publicly available) training data",
value=False,
info="Displayed publicly on the leaderboard.",
)
open_code_checkbox = gr.Checkbox(
label="My code is open-source and publicly available",
value=False,
info="Link it as your method report.",
)
model_tag = gr.Textbox(
label="Method report link *",
placeholder="https://...",
info="Required. A report, preprint or repository describing how the "
"predictions were made; shown on the leaderboard. Must start with "
"'https://' and be reachable.",
)
with gr.Column(scale=1):
gr.Markdown("### Contact & publication *(optional, private)*")
participant_name = gr.Textbox(label="Full name", placeholder="Jane Smith")
discord_username = gr.Textbox(label="Discord / contact handle")
email = gr.Textbox(label="Email", placeholder="jane@example.com")
affiliation = gr.Textbox(label="Affiliation", placeholder="University / company")
with gr.Column(scale=1):
gr.Markdown("### Bundle")
file_input = gr.File(label="plug_submission.zip *", file_types=[".zip"])
gr.Markdown(
f"One submission per account per track every "
f"**{HOURS_BETWEEN_SUBMISSIONS} hours**. Only your latest submission to "
"each track is ranked."
)
submit_btn = gr.Button("Validate, score and submit", variant="primary", size="lg")
submit_msg = gr.Markdown(visible=False)
submit_btn.click(
fn=submit_bundle,
inputs=[
username_input,
track_input,
user_alias,
anon_checkbox,
participant_name,
discord_username,
email,
affiliation,
model_tag,
proprietary_checkbox,
open_code_checkbox,
file_input,
],
outputs=[submit_msg],
)
def _error(message: str) -> dict:
"""Format a failure for the status box."""
return gr.update(value=f"### ❌ Submission not accepted\n\n{message}", visible=True)
def _format_cooldown(last_submission: datetime, track: str) -> str:
"""Explain how long is left before this account may submit to a track again."""
next_allowed = last_submission + timedelta(hours=HOURS_BETWEEN_SUBMISSIONS)
remaining = max(0, int((next_allowed - store.now()).total_seconds()))
hours, rest = divmod(remaining, 3600)
minutes, seconds = divmod(rest, 60)
return (
f"You submitted to the {TRACK_LABELS[track].lower()} track on "
f"{last_submission.strftime('%Y-%m-%d %H:%M UTC')}. Please wait "
f"**{hours:02d}:{minutes:02d}:{seconds:02d}** before submitting to it again."
)
def _score_table_md(scores: dict[str, dict[str, float]]) -> str:
"""Render one submission's own scores as a markdown table."""
rows = [
"| Benchmark | Metric | Value | Over chance |",
"| :--- | :--- | ---: | ---: |",
]
for spec in BENCHMARKS:
if spec.name not in scores:
rows.append(f"| {spec.label} | {spec.primary.label} | *not scored* | |")
continue
value = scores[spec.name].get(f"{spec.primary.key}_mean")
if value is None or pd.isna(value):
rows.append(f"| {spec.label} | {spec.primary.label} | β€” | β€” |")
continue
normalised = aggregate.normalise(value, spec.primary)
rows.append(
f"| {spec.label} | {spec.primary.label} | {value:.4f} | {normalised:.4f} |"
)
return "\n".join(rows)
def submit_bundle(
username: str,
track: str,
user_alias: str,
anonymous: bool,
participant_name: str,
discord_username: str,
email: str,
affiliation: str,
model_tag: str,
used_proprietary_data: bool,
open_source_code: bool,
file_input: str | None,
) -> dict:
"""Handle one submission from the Submit tab.
Parameters
----------
username : str
Hugging Face username. Checked against Hugging Face to confirm the
account exists β€” a typo check, not an identity proof.
track : str
``supervised`` or ``unsupervised``: which rows are scored and which
leaderboard the submission enters.
user_alias : str
Display alias, required when submitting anonymously.
anonymous : bool
Show the alias instead of the username on the leaderboard.
participant_name : str
Real name (private).
discord_username : str
Contact handle (private).
email : str
Contact email (private).
affiliation : str
Institutional affiliation (private).
model_tag : str
Method report link. Required, and validated for reachability.
used_proprietary_data : bool
Whether non-public training data was used.
open_source_code : bool
Whether the method's code is public.
file_input : str | None
Path to the uploaded bundle.
Returns
-------
dict
A ``gr.update`` carrying the outcome: either the rejection reasons, or
the submission's own per-benchmark scores and PLUG Score.
"""
if CURRENT_PHASE != 1:
return _error("The submission portal is not open.")
handle = (username or "").strip()
if not handle:
return _error("A Hugging Face username is required.")
if not validate_hf_username(handle):
logger.warning("Unknown Hugging Face username: {!r}", handle)
return _error(f"Hugging Face account `{handle}` could not be found β€” check for typos.")
banned_reason = BANNED_USERNAMES.get(handle.lower())
if banned_reason:
logger.warning("Blocked submission from banned username {!r}", handle)
return _error(
f"Account `{handle}` is blocked. Reason: {banned_reason}. "
"Contact the organisers if you believe this is a mistake."
)
if track not in TRACKS:
return _error("Choose a track: supervised or unsupervised.")
if anonymous and not (user_alias or "").strip():
return _error(
"An alias is required when submitting anonymously β€” either provide one or "
"untick *Submit anonymously*."
)
if email and email.strip() and not EMAIL_RE.match(email.strip()):
return _error("That does not look like a valid email address.")
model_status = validate_model_details(model_tag)
if model_status == "Not submitted":
return _error(
"A method report link is required: a report, preprint or repository "
"describing how the predictions were made."
)
if model_status == "Invalid link":
return _error(
"Could not open the method report link. Check the URL β€” it must start "
"with `https://` and be publicly reachable."
)
if file_input is None:
return _error("Please upload your submission bundle.")
bundle_path = Path(file_input)
if not store.configured():
logger.error("HF_TOKEN is not set on the Space β€” cannot accept submissions.")
return _error(
"Submission storage is not configured on this Space. Please report this to "
"the organisers."
)
safe_username = safeify_username(handle)
last_submission = store.last_submission_at(safe_username, track)
if (
last_submission is not None
and (store.now() - last_submission).total_seconds() < HOURS_BETWEEN_SUBMISSIONS * 3600
):
return _error(_format_cooldown(last_submission, track))
# --- validate before anything is stored ---
truth = store.available_ground_truth(track)
if not truth:
return _error(
"No ground truth is staged for this challenge yet, so nothing can be scored. "
"Please report this to the organisers."
)
result = validate_bundle(
bundle_path,
expected_ids=store.expected_ids(truth),
require_complete=REQUIRE_COMPLETE_BUNDLE,
)
if not result.ok:
return _error(
"Your bundle did not pass validation. Nothing was stored and your "
f"submission cooldown has not started.\n\n{result.report()}\n\n"
"Run `plug-challenge validate` locally to iterate without uploading."
)
# --- score ---
try:
scores = scoring.score_bundle(
result.frames, truth, BENCHMARKS, bootstrap_samples=BOOTSTRAP_SAMPLES
)
except Exception as exc:
logger.exception("Scoring failed for {}: {}", handle, exc)
return _error(
"Your bundle validated but scoring failed unexpectedly. Please report this "
"to the organisers β€” nothing was stored."
)
submission = Submission(
username=handle,
track=track,
user_alias=(user_alias or "").strip(),
anonymous=anonymous,
participant_name=(participant_name or "").strip(),
discord_username=(discord_username or "").strip(),
email=(email or "").strip(),
affiliation=(affiliation or "").strip(),
model_report_link=model_status,
used_proprietary_data=used_proprietary_data,
open_source_code=open_source_code,
filename=bundle_path.name,
)
# --- store: bundle and metadata first, then the derived leaderboard row ---
try:
submission.bundle_path = store.upload_submission(
safe_username=submission.safe_username,
submission_id=submission.submission_id,
bundle_path=bundle_path,
metadata=submission.model_dump(),
)
entry = {
**submission.public_fields(),
"plug_score": aggregate.plug_score(scores),
**aggregate.flatten(scores),
}
store.save_scores(submission.safe_username, submission.submission_id, entry)
store.append_leaderboard_entry(entry)
except Exception as exc:
logger.exception("Storing submission {} failed: {}", submission.submission_id, exc)
return _error(
"Your bundle scored, but storing it failed, so it is not on the leaderboard. "
f"Please report this to the organisers with submission id "
f"`{submission.submission_id}`."
)
logger.info(
"Accepted submission {} from {} β€” PLUG Score {:.4f}",
submission.submission_id,
submission.display_name,
entry["plug_score"],
)
caveat = (
f"\n\n**Note:** {result.report()}\n" if result.warnings else ""
)
return gr.update(
value=(
f"### βœ… Submission accepted{caveat}\n\n"
f"Recorded for **{submission.display_name}** β€” it will appear on the "
f"{TRACK_LABELS[track].lower()} leaderboard within a minute.\n\n"
f"**PLUG Score: {entry['plug_score']:.4f}**\n\n"
f"{_score_table_md(scores)}\n\n"
f"Submission id `{submission.submission_id}`. You may submit to this track "
f"again in {HOURS_BETWEEN_SUBMISSIONS} hours; only your latest submission to "
"each track is ranked."
),
visible=True,
)