Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download leaderboards.py from PrismScienceOrg/PLUG-challenge: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/spaces/PrismScienceOrg/PLUG-challenge/resolve/main/leaderboards.py
- Command line
-
hf download hf://spaces/PrismScienceOrg/PLUG-challenge/leaderboards.py
-
curl -L -o leaderboards.py https://huggingface.co/spaces/PrismScienceOrg/PLUG-challenge/resolve/main/leaderboards.py
11.7 kB
| """The leaderboard tabs: per track, one overall board plus one per benchmark. | |
| All of them are views of a single stored table (``leaderboard/entries.csv`` in | |
| the private repo), split by ``track`` into the supervised and unsupervised | |
| leaderboards. ``load_overall`` ranks one track by the PLUG Score across every | |
| benchmark, and ``load_benchmark`` narrows the same rows to one benchmark's | |
| metric columns and re-ranks by that benchmark's normalised primary metric. | |
| Nothing here recomputes a metric — those were computed once, when the | |
| submission was accepted; only their normalisation is applied on read. | |
| """ | |
| import tempfile | |
| from collections.abc import Callable | |
| from functools import partial | |
| import gradio as gr | |
| import pandas as pd | |
| from gradio_leaderboard import ColumnFilter, Leaderboard | |
| from loguru import logger | |
| from plug_challenge import BENCHMARKS, BenchmarkSpec, aggregate, store | |
| from plug_challenge.benchmarks import TRACK_DESCRIPTIONS, TRACK_LABELS, TRACKS | |
| from utils import make_tag_clickable, make_user_clickable | |
| # A board's data source: called with no arguments for the rendered view, or with | |
| # for_download=True for the CSV export. | |
| BoardLoader = Callable[..., pd.DataFrame] | |
| # How often the tables re-read the stored leaderboard, in seconds. Reads are | |
| # served from store.read_leaderboard's short-lived cache, so several open tabs | |
| # do not multiply into several Hub requests. | |
| REFRESH_SECONDS = 30 | |
| _IDENTITY_DISPLAY = { | |
| "rank": "Rank", | |
| "username": "Entrant", | |
| "submitted_at": "Submitted", | |
| "plug_score": "PLUG Score", | |
| "mean_rank": "Mean Rank", | |
| "benchmarks_scored": "Benchmarks", | |
| "model_report_link": "Method Report", | |
| } | |
| _OVERALL_BASE_COLUMNS = [ | |
| "Rank", | |
| "Entrant", | |
| "PLUG Score", | |
| "Mean Rank", | |
| "Benchmarks", | |
| "Submitted", | |
| "Method Report", | |
| "Proprietary Data", | |
| "Open Code", | |
| ] | |
| def _empty(columns: list[str]) -> pd.DataFrame: | |
| """Build a placeholder table, shown before the first submission or on a read failure.""" | |
| return pd.DataFrame(columns=columns) | |
| def _ranked(track: str) -> pd.DataFrame: | |
| """Read the stored entries and rank one track's. | |
| Parameters | |
| ---------- | |
| track : str | |
| Which leaderboard to build. | |
| Returns | |
| ------- | |
| pd.DataFrame | |
| The output of ``aggregate.build_leaderboard`` — one row per entrant, | |
| ranked — or an empty frame when nothing has been submitted to the track. | |
| """ | |
| raw = store.read_leaderboard() | |
| if raw.empty: | |
| return pd.DataFrame() | |
| ranked = aggregate.build_leaderboard(raw.to_dict(orient="records"), BENCHMARKS, track) | |
| return ranked if not ranked.empty else pd.DataFrame() | |
| def _format_shared(df: pd.DataFrame, for_download: bool) -> pd.DataFrame: | |
| """Apply the formatting every board shares: timestamps, flags, links.""" | |
| df = df.copy() | |
| df["submitted_at"] = pd.to_datetime(df["submitted_at"], utc=True, errors="coerce").dt.strftime( | |
| "%Y-%m-%d %H:%M UTC" | |
| ) | |
| for source, label in ( | |
| ("used_proprietary_data", "Proprietary Data"), | |
| ("open_source_code", "Open Code"), | |
| ): | |
| df[label] = ( | |
| df[source].fillna(False).astype(bool).map({True: "Yes", False: "No"}) | |
| if source in df.columns | |
| else "No" | |
| ) | |
| df = df.drop( | |
| columns=[ | |
| "used_proprietary_data", | |
| "open_source_code", | |
| "safe_username", | |
| "anonymous", | |
| "submission_id", | |
| "track", | |
| ], | |
| errors="ignore", | |
| ) | |
| if not for_download: | |
| df["username"] = df["username"].astype(str).map(make_user_clickable) | |
| df["model_report_link"] = df["model_report_link"].astype(str).map(make_tag_clickable) | |
| return df.rename(columns=_IDENTITY_DISPLAY) | |
| def load_overall(track: str = "supervised", for_download: bool = False) -> pd.DataFrame: | |
| """Build one track's overall leaderboard: PLUG Score plus every benchmark's primary metric. | |
| Parameters | |
| ---------- | |
| track : str | |
| Which leaderboard to build. | |
| for_download : bool | |
| Keep plain text (no HTML links) and full precision for the CSV export. | |
| Returns | |
| ------- | |
| pd.DataFrame | |
| The overall board, best PLUG Score first. | |
| """ | |
| metric_labels = [spec.label for spec in BENCHMARKS] | |
| ranked = _ranked(track) | |
| if ranked.empty: | |
| return _empty(_OVERALL_BASE_COLUMNS + metric_labels) | |
| df = _format_shared(ranked, for_download) | |
| for spec in BENCHMARKS: | |
| source = aggregate.column(spec.name, spec.primary) | |
| df[spec.label] = ( | |
| pd.to_numeric(df[source], errors="coerce") if source in df.columns else pd.NA | |
| ) | |
| for column in ["PLUG Score", "Mean Rank", *metric_labels]: | |
| if column in df.columns and not for_download: | |
| df[column] = pd.to_numeric(df[column], errors="coerce").round(4) | |
| columns = [c for c in _OVERALL_BASE_COLUMNS if c in df.columns] + metric_labels | |
| logger.info("Overall {} leaderboard: {} entrant(s).", track, len(df)) | |
| return df[columns] | |
| def load_benchmark( | |
| spec: BenchmarkSpec, track: str = "supervised", for_download: bool = False | |
| ) -> pd.DataFrame: | |
| """Build one benchmark's leaderboard, ranked by its normalised primary metric. | |
| Ranking on the normalised value rather than the raw one is what puts a | |
| Spearman of -0.9 above one of 0.5: the sign of a correlation is a | |
| convention, not a result. | |
| Parameters | |
| ---------- | |
| spec : BenchmarkSpec | |
| The benchmark to narrow to. | |
| track : str | |
| Which leaderboard to build. | |
| for_download : bool | |
| Keep plain text and full precision for the CSV export. | |
| Returns | |
| ------- | |
| pd.DataFrame | |
| Entrants with a score for this benchmark, best first. Entrants with no | |
| score here are dropped rather than ranked last, so the row count is the | |
| number of methods that actually entered this benchmark. | |
| """ | |
| metric_labels = [metric.label for metric in spec.metrics] | |
| base = [ | |
| "Rank", | |
| "Entrant", | |
| "Score", | |
| *metric_labels, | |
| "Submitted", | |
| "Method Report", | |
| "Proprietary Data", | |
| "Open Code", | |
| ] | |
| ranked = _ranked(track) | |
| score_column = aggregate.score_column(spec.name) | |
| if ranked.empty or score_column not in ranked.columns: | |
| return _empty(base) | |
| df = ranked[pd.to_numeric(ranked[score_column], errors="coerce").notna()].copy() | |
| if df.empty: | |
| return _empty(base) | |
| df = df.sort_values(score_column, ascending=False).reset_index(drop=True) | |
| df["rank"] = range(1, len(df) + 1) | |
| df = _format_shared(df, for_download) | |
| score = pd.to_numeric(df[score_column], errors="coerce") | |
| df["Score"] = score if for_download else score.round(4) | |
| for metric in spec.metrics: | |
| source = aggregate.column(spec.name, metric) | |
| values = ( | |
| pd.to_numeric(df[source], errors="coerce") if source in df.columns else pd.NA | |
| ) | |
| df[metric.label] = ( | |
| values if for_download else pd.to_numeric(values, errors="coerce").round(4) | |
| ) | |
| std_source = aggregate.column(spec.name, metric, "std") | |
| if for_download and std_source in df.columns: | |
| df[f"{metric.label} std"] = pd.to_numeric(df[std_source], errors="coerce") | |
| columns = [c for c in base if c in df.columns] | |
| if for_download: | |
| columns += [f"{m.label} std" for m in spec.metrics if f"{m.label} std" in df.columns] | |
| logger.info("{} {} leaderboard: {} entrant(s).", track, spec.name, len(df)) | |
| return df[columns] | |
| def _download(loader: BoardLoader) -> str: | |
| """Write a board to a temp CSV and return its path.""" | |
| frame = loader(for_download=True) | |
| with tempfile.NamedTemporaryFile( | |
| "w", suffix=".csv", prefix="plug_leaderboard_", delete=False | |
| ) as handle: | |
| frame.to_csv(handle, index=False) | |
| return handle.name | |
| def _table( | |
| loader: BoardLoader, numeric_columns: list[str], search_column: str = "Entrant" | |
| ) -> Leaderboard: | |
| """Render one board: download button, table, and the disclosure filters.""" | |
| download_btn = gr.DownloadButton(label="Download CSV", size="sm") | |
| download_btn.click(fn=partial(_download, loader), outputs=download_btn) | |
| value = loader() | |
| return Leaderboard( | |
| value=value, | |
| select_columns=list(value.columns), | |
| search_columns=[search_column], | |
| filter_columns=[ | |
| ColumnFilter( | |
| "Proprietary Data", | |
| type="checkboxgroup", | |
| label="Proprietary Data", | |
| choices=[("Yes", "Yes"), ("No", "No")], | |
| default=[("Yes", "Yes"), ("No", "No")], | |
| ), | |
| ColumnFilter( | |
| "Open Code", | |
| type="checkboxgroup", | |
| label="Open Code", | |
| choices=[("Yes", "Yes"), ("No", "No")], | |
| default=[("Yes", "Yes"), ("No", "No")], | |
| ), | |
| ], | |
| datatype=[ | |
| "number" | |
| if column in numeric_columns | |
| else ("html" if column in ("Entrant", "Method Report") else "str") | |
| for column in value.columns | |
| ], | |
| ) | |
| def render_leaderboards(phase: int, demo: gr.Blocks) -> None: | |
| """Render every leaderboard tab. | |
| Parameters | |
| ---------- | |
| phase : int | |
| ``config.CURRENT_PHASE``. Phase 0 shows a placeholder; phase 2 labels the | |
| board as the final standings. | |
| demo : gr.Blocks | |
| The app's Blocks instance, used to refresh each table on page load so a | |
| visitor sees current data rather than the snapshot baked in at build | |
| time. | |
| """ | |
| if phase == 0: | |
| gr.Markdown( | |
| "# Leaderboard (coming soon)\n\n" | |
| "The challenge has not started yet. Standings appear here once submissions open." | |
| ) | |
| return | |
| gr.Markdown( | |
| "# Final standings" if phase >= 2 else "# Leaderboard", | |
| elem_id="leaderboard-heading", | |
| ) | |
| gr.Markdown( | |
| "Two leaderboards, one per track. Each is ranked by **PLUG Score** — the mean " | |
| "improvement over random chance across the eleven benchmarks, with each primary " | |
| "metric normalised so that chance is 0 and perfect is 1 (see **About → Scoring**). " | |
| "Each benchmark's own tab re-ranks by that benchmark's normalised score and adds " | |
| "its secondary metrics. Only each entrant's latest submission to a track is shown." | |
| + ("" if phase >= 2 else f" Refreshes every {REFRESH_SECONDS} seconds.") | |
| ) | |
| timer = gr.Timer(value=REFRESH_SECONDS) if phase < 2 else None | |
| tables: list[tuple[Leaderboard, BoardLoader]] = [] | |
| overall_numeric = ["Rank", "PLUG Score", "Mean Rank", "Benchmarks"] + [ | |
| spec.label for spec in BENCHMARKS | |
| ] | |
| with gr.Tabs(): | |
| for track in TRACKS: | |
| with gr.TabItem(TRACK_LABELS[track]): | |
| gr.Markdown(f"*{TRACK_DESCRIPTIONS[track]}*") | |
| with gr.Tabs(): | |
| with gr.TabItem("🏆 Overall"): | |
| overall = partial(load_overall, track) | |
| tables.append((_table(overall, overall_numeric), overall)) | |
| for spec in BENCHMARKS: | |
| with gr.TabItem(spec.label): | |
| gr.Markdown(f"*{spec.description}*") | |
| loader = partial(load_benchmark, spec, track) | |
| numeric = ["Rank", "Score", *[m.label for m in spec.metrics]] | |
| tables.append((_table(loader, numeric), loader)) | |
| triggers = [demo.load] + ([timer.tick] if timer is not None else []) | |
| for table, board_loader in tables: | |
| gr.on(triggers=triggers, fn=board_loader, outputs=[table]) | |