import os
from pathlib import Path
def patch_gradio_leaderboard():
"""Patch gradio_leaderboard JS to fix crash on tab switch with Gradio 5.x."""
import gradio_leaderboard
pkg_dir = Path(gradio_leaderboard.__file__).parent
js_file = pkg_dir / "templates" / "component" / "Index-CzS_eGV6.js"
if not js_file.exists():
return
src = js_file.read_text()
patches = [
# Fix 1 & 2: Guard r[39]/a[39] filter callback (undefined during Svelte outro)
(
'r[0].filter(\n /*func*/\n r[39]\n ).map(qd)',
'(r[39] ? r[0].filter(r[39]) : r[0]).map(qd)',
),
(
'a[0].filter(\n /*func*/\n a[39]\n ).map(qd))',
'(a[39] ? a[0].filter(a[39]) : a[0]).map(qd))',
),
# Fix 3: Lx (Boolean) extracted from Rx (globals) which is undefined in Gradio 5
(
'{ Boolean: Lx } = Rx,',
'Lx = (Rx && Rx.Boolean) || Boolean,',
),
]
patched = False
for old, new in patches:
if old in src:
src = src.replace(old, new)
patched = True
if patched:
js_file.write_text(src)
patch_gradio_leaderboard()
import gradio as gr
import pandas as pd
from apscheduler.schedulers.background import BackgroundScheduler
from gradio_leaderboard import ColumnFilter, Leaderboard, SelectColumns
from huggingface_hub import HfApi
from src.analytics import (
MATRIX_METRICS,
RANKING_METRICS,
TRADEOFF_METRICS,
benchmarks_for_category,
coverage_summary,
cross_benchmark_ranking_df,
enrich_analysis_df,
filter_category,
matrix_df,
ranking_df,
)
from src.charts import (
clean_markdown_link,
create_coverage_matrix_plot,
create_leaderboard_benchmark_plot,
create_matrix_plot,
create_performance_vs_resource_plot,
create_ranking_plot,
create_tradeoff_plot,
)
from src.display.text_blocks import (
HOW_TO_USE_TEXT,
INTRODUCTION_TEXT,
LLM_BENCHMARKS_TEXT,
)
from src.leaderboard import (
EFFICIENCY_RESOURCE_METRICS,
get_analysis_df,
get_benchmark_names,
get_benchmark_run_df,
get_efficiency_df,
)
from src.rankings import EXCLUDED_BENCHMARKS, RANK_BY_OPTIONS, load_and_rank
from src.version import __version__
REPO_ID = "red-hat-emerging-technologies/coding-agent-leaderboard"
TOKEN = os.environ.get("HF_TOKEN")
API = HfApi(token=TOKEN)
COLOR_BY_CHOICES = ["Model", "Harness"]
EFFICIENCY_COLOR_BY_CHOICES = ["Model", "Harness"]
COLOR_PALETTE_CHOICES = ["Citrus", "Okabe-Ito", "High contrast", "Rainbow"]
DEFAULT_COLOR_PALETTE = "Citrus"
PLOT_BACKGROUND_CHOICES = ["Dark", "White"]
DEFAULT_PLOT_BACKGROUND = "Dark"
RESPONSIVE_PLOT_MIN_HEIGHT_PX = 420
TABLE_MAX_HEIGHT_PX = 720
RESPONSIVE_PLOT_CSS = f"""
"""
FORCE_DARK_MODE_HEAD = (
"""
"""
+ RESPONSIVE_PLOT_CSS
)
def restart_space():
API.restart_space(repo_id=REPO_ID)
BENCHMARK_NAMES = get_benchmark_names()
DEFAULT_BENCHMARK = BENCHMARK_NAMES[0] if BENCHMARK_NAMES else None
BENCHMARK_RUN_DF = get_benchmark_run_df()
ANALYSIS_DF = get_analysis_df()
PR2_DF = enrich_analysis_df(ANALYSIS_DF)
CODING_BENCHMARKS = benchmarks_for_category(PR2_DF, "Coding")
GENERALIST_BENCHMARKS = benchmarks_for_category(PR2_DF, "Generalist")
def render_leaderboard_benchmark_plot(
benchmark_name,
color_by,
color_palette=DEFAULT_COLOR_PALETTE,
plot_background=DEFAULT_PLOT_BACKGROUND,
):
return create_leaderboard_benchmark_plot(
BENCHMARK_RUN_DF,
benchmark_name=benchmark_name,
color_by=color_by,
palette_name=color_palette,
background_name=plot_background,
)
def render_efficiency(
benchmark_name,
token_metric,
color_by,
x_scale,
show_pareto_frontier,
show_labels,
color_palette=DEFAULT_COLOR_PALETTE,
plot_background=DEFAULT_PLOT_BACKGROUND,
):
plot_df = get_efficiency_df(
benchmark_name=benchmark_name,
resource_metric=token_metric,
analysis_df=ANALYSIS_DF,
)
exclusion_count = plot_df.attrs.get("exclusion_count", 0)
note = (
f"{exclusion_count} runs excluded for this benchmark because "
f"{token_metric.lower()} was missing or non-positive."
)
figure = create_performance_vs_resource_plot(
plot_df,
resource_metric=token_metric,
color_by=color_by,
x_scale=x_scale,
show_pareto_frontier=show_pareto_frontier,
show_labels=show_labels,
palette_name=color_palette,
background_name=plot_background,
)
return figure, note
PAGE_TABLE_COLUMNS = [
"Model",
"Harness",
"Benchmark",
"Score (%)",
"Within-Benchmark Rank",
"Within-Benchmark Percentile",
"Total Tokens Per Task",
"Cost Per Task",
"Total Time Per Task",
"Agent Time Per Task",
"Execution Error Rate (%)",
"Tokens Per Successful Task",
"Cost Per Successful Task",
"Time Per Successful Task",
]
PAGE_TABLE_SORT_COLUMNS = {
"Score": "Score (%)",
"Rank": "Within-Benchmark Rank",
"Percentile": "Within-Benchmark Percentile",
"Total tokens": "Total Tokens Per Task",
"Cost": "Cost Per Task",
"Response time": "Total Time Per Task",
"Agent time": "Agent Time Per Task",
"Execution error rate": "Execution Error Rate (%)",
}
PAGE_TABLE_HIGHER_IS_BETTER = {
"Score": True,
"Rank": False,
"Percentile": True,
"Total tokens": False,
"Cost": False,
"Response time": False,
"Agent time": False,
"Execution error rate": False,
}
def render_page_table(benchmark, sort_metric="Score", sort_order="Best first"):
"""One compact table per page with all metrics relevant to ranking/trade-off views."""
data = PR2_DF.copy()
if benchmark and benchmark != "All benchmarks":
data = data[data["Benchmark"] == benchmark].copy()
columns = [column for column in PAGE_TABLE_COLUMNS if column in data.columns]
data = data[columns].copy()
if data.empty:
return data
data["_agent"] = data["Model"].astype(str) + " / " + data["Harness"].astype(str)
if sort_order == "Alphabetical (A–Z)":
data = data.sort_values(["_agent", "Benchmark"], ascending=[True, True], kind="mergesort")
elif sort_order == "Alphabetical (Z–A)":
data = data.sort_values(["_agent", "Benchmark"], ascending=[False, True], kind="mergesort")
else:
sort_column = PAGE_TABLE_SORT_COLUMNS.get(sort_metric, "Score (%)")
values = pd.to_numeric(data.get(sort_column), errors="coerce")
data["_sort_value"] = values
if sort_order == "Best first":
ascending = not PAGE_TABLE_HIGHER_IS_BETTER.get(sort_metric, True)
elif sort_order == "Best last":
ascending = PAGE_TABLE_HIGHER_IS_BETTER.get(sort_metric, True)
else:
ascending = sort_order == "Lowest value first"
data = data.sort_values(
["_sort_value", "_agent", "Benchmark"],
ascending=[ascending, True, True],
na_position="last",
kind="mergesort",
).drop(columns="_sort_value")
data = data.drop(columns="_agent").reset_index(drop=True)
# Metrics displayed to 2 decimal places
decimal_columns = [
"Score (%)",
"Within-Benchmark Percentile",
"Execution Error Rate (%)",
"Cost Per Successful Task",
]
for column in decimal_columns:
if column in data.columns:
data[column] = pd.to_numeric(data[column], errors="coerce").round(2)
# Token and time metrics displayed as whole numbers
whole_number_columns = [
"Total Tokens Per Task",
"Total Time Per Task",
"Agent Time Per Task",
"Tokens Per Successful Task",
"Time Per Successful Task",
]
for column in whole_number_columns:
if column in data.columns:
data[column] = pd.to_numeric(data[column], errors="coerce").round(0)
return data
def render_ranking(
metric,
benchmark,
color_by="Model",
color_palette=DEFAULT_COLOR_PALETTE,
plot_background=DEFAULT_PLOT_BACKGROUND,
sort_order="Best first",
):
def sort_table(table, metric_column, higher_is_better):
if table is None or table.empty:
return table
work = table.copy()
work["_agent"] = work["Model"].astype(str) + " / " + work["Harness"].astype(str)
if sort_order == "Alphabetical (A–Z)":
work = work.sort_values("_agent", ascending=True, kind="mergesort")
elif sort_order == "Alphabetical (Z–A)":
work = work.sort_values("_agent", ascending=False, kind="mergesort")
elif sort_order in {"Best first", "Best last"}:
ascending = not higher_is_better
if sort_order == "Best last":
ascending = not ascending
work = work.sort_values(
[metric_column, "_agent"],
ascending=[ascending, True],
kind="mergesort",
)
elif sort_order == "Lowest value first":
work = work.sort_values(
[metric_column, "_agent"],
ascending=[True, True],
kind="mergesort",
)
else:
work = work.sort_values(
[metric_column, "_agent"],
ascending=[False, True],
kind="mergesort",
)
return work.drop(columns="_agent").reset_index(drop=True)
table = ranking_df(PR2_DF, metric, benchmark=benchmark)
spec = RANKING_METRICS[metric]
table = sort_table(table, spec.column, spec.higher_is_better)
figure = create_ranking_plot(
table,
spec.column,
spec.label,
spec.higher_is_better,
color_by=color_by,
palette_name=color_palette,
background_name=plot_background,
sort_order=sort_order,
)
return figure, table
TRADEOFF_PAIRS = {
"Score vs cost": ("Cost Per Task", "Score (%)", "Cost per task (USD)", "Score (%)", True, True),
"Score vs tokens": ("Total Tokens Per Task", "Score (%)", "Total tokens per task", "Score (%)", True, True),
"Score vs total time": ("Total Time Per Task", "Score (%)", "Total time per task (seconds)", "Score (%)", True, True),
"Score vs agent time": ("Agent Time Per Task", "Score (%)", "Agent time per task (seconds)", "Score (%)", True, True),
"Score vs execution error rate": (
"Execution Error Rate (%)", "Score (%)", "Execution error rate (%)", "Score (%)", True, True
),
"Tokens vs cost": ("Total Tokens Per Task", "Cost Per Task", "Total tokens per task", "Cost per task (USD)", True, False),
"Cost vs total time": ("Cost Per Task", "Total Time Per Task", "Cost per task (USD)", "Total time per task (seconds)", True, False),
}
def render_tradeoff(
pair,
benchmark,
color_by,
show_labels,
x_scale,
show_pareto,
color_palette,
plot_background,
):
x_column, y_column, x_label, y_label, lower_x, higher_y = TRADEOFF_PAIRS[pair]
data = PR2_DF[PR2_DF["Benchmark"] == benchmark].copy()
figure = create_tradeoff_plot(
data,
x_column=x_column,
y_column=y_column,
x_label=x_label,
y_label=y_label,
color_by=color_by,
show_labels=show_labels,
x_scale=x_scale,
show_pareto_frontier=show_pareto,
lower_x_is_better=lower_x,
higher_y_is_better=higher_y,
palette_name=color_palette,
background_name=plot_background,
)
valid = data[[x_column, y_column]].apply(pd.to_numeric, errors="coerce").dropna()
note = f"{len(valid)} comparable runs shown for {benchmark}; missing metrics are omitted, not treated as zero."
return figure, note
def render_matrix(
metric,
category,
include_incomplete,
sort_by,
show_values,
reverse_scale,
plot_background,
):
category_filter = None if category == "All" else category
matrix = matrix_df(
PR2_DF,
metric,
category=category_filter,
include_incomplete=include_incomplete,
sort_by=sort_by,
)
if metric == "Coverage":
return create_coverage_matrix_plot(matrix, plot_background)
spec = MATRIX_METRICS[metric]
display_matrix = None
display_metric_label = None
if metric == "Within-benchmark percentile":
display_matrix = matrix_df(
PR2_DF,
"Score",
category=category_filter,
include_incomplete=include_incomplete,
sort_by=sort_by,
).reindex(index=matrix.index, columns=matrix.columns)
display_metric_label = "Benchmark score (%)"
return create_matrix_plot(
matrix,
f"{metric} matrix",
spec.label,
higher_is_better=spec.higher_is_better,
show_values=show_values,
reverse_scale=reverse_scale,
background_name=plot_background,
display_matrix=display_matrix,
display_metric_label=display_metric_label,
)
def category_leaderboard(category):
data = filter_category(PR2_DF, category)
if data.empty:
return pd.DataFrame()
normalized = cross_benchmark_ranking_df(data, minimum_coverage=0)
return normalized
def render_category_tradeoff(category, benchmark, metric, color_by, show_labels, plot_background):
data = filter_category(PR2_DF, category)
data = data[data["Benchmark"] == benchmark]
spec = TRADEOFF_METRICS[metric]
return create_tradeoff_plot(
data,
x_column=spec.column,
y_column="Score (%)",
x_label=spec.label,
y_label="Score (%)",
color_by=color_by,
show_labels=show_labels,
show_pareto_frontier=metric != "Execution error rate",
lower_x_is_better=True,
higher_y_is_better=True,
background_name=plot_background,
)
def render_category_matrix(category, metric, show_values, plot_background):
matrix = matrix_df(PR2_DF, metric, category=category, include_incomplete=True)
if metric == "Coverage":
return create_coverage_matrix_plot(matrix, plot_background)
spec = MATRIX_METRICS[metric]
display_matrix = None
display_metric_label = None
if metric == "Within-benchmark percentile":
display_matrix = matrix_df(
PR2_DF, "Score", category=category, include_incomplete=True
).reindex(index=matrix.index, columns=matrix.columns)
display_metric_label = "Benchmark score (%)"
return create_matrix_plot(
matrix,
f"{category} — {metric}",
spec.label,
higher_is_better=spec.higher_is_better,
show_values=show_values,
background_name=plot_background,
display_matrix=display_matrix,
display_metric_label=display_metric_label,
)
def build_header_html(df):
summary = coverage_summary(PR2_DF)
return f"""
Performance, efficiency, coverage, and reliability across coding-agent benchmarks. Each result is one model + harness run on one benchmark.
Cross-benchmark ordering uses within-benchmark percentiles rather than averaging incompatible raw score scales. Missing metrics remain missing and reduce coverage; they are never converted to zero.