File size: 9,674 Bytes
03696ac | 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 | import { client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
const state = {
api: null,
payload: null,
rows: [],
sort: { key: "Average ⬆️", direction: "desc" },
};
let columns = [];
function configureColumns(benchmarks = []) {
columns = [
{ key: "rank", label: "Rank" },
{ key: "Model", label: "Model" },
{ key: "Average ⬆️", label: "Average", score: true },
...benchmarks.map((benchmark) => ({ key: benchmark, label: benchmark, score: true })),
{ key: "Type", label: "Type" },
{ key: "Precision", label: "Precision" },
{ key: "#Params (B)", label: "Params (B)", score: true },
{ key: "Hub License", label: "License" },
{ key: "Hub ❤️", label: "Likes", score: true },
{ key: "Available on the hub", label: "Hub" },
];
}
const $ = (selector) => document.querySelector(selector);
const $$ = (selector) => [...document.querySelectorAll(selector)];
const escapeHtml = (value) => String(value ?? "").replace(/[&<>'"]/g, (char) => ({ "&": "&", "<": "<", ">": ">", "'": "'", '"': """ })[char]);
const safeModelId = (value) => /^[\w.-]+\/[\w.-]+$/.test(String(value || "")) ? value : "";
const formatScore = (value) => value == null || Number.isNaN(Number(value)) ? "—" : Number(value).toFixed(2);
const firstData = (response) => Array.isArray(response.data) ? response.data[0] : response.data;
function markdown(source = "") {
let text = escapeHtml(source.trim());
text = text.replace(/```(?:[a-zA-Z0-9_+-]+)?\n([\s\S]*?)```/g, (_, code) => `<pre><code>${code.trim()}</code></pre>`);
text = text.replace(/^### (.+)$/gm, "<h3>$1</h3>").replace(/^## (.+)$/gm, "<h2>$1</h2>");
text = text.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g, '<a href="$2" target="_blank" rel="noreferrer">$1</a>');
text = text.replace(/`([^`]+)`/g, "<code>$1</code>");
return text.split(/\n{2,}/).map((block) => /^<(h2|h3|pre)/.test(block) ? block : `<p>${block.replace(/\n/g, "<br>")}</p>`).join("");
}
function renderHead() {
$("#leaderboard-head").innerHTML = `<tr>${columns.map((column) => {
const sortable = column.score || column.key === "Model";
const active = state.sort.key === column.key;
const arrow = active ? (state.sort.direction === "asc" ? " ↑" : " ↓") : "";
return `<th class="${sortable ? "sortable" : ""} ${active ? "active-sort" : ""}" data-key="${escapeHtml(column.key)}">${column.label}${arrow}</th>`;
}).join("")}</tr>`;
$$("th.sortable").forEach((header) => header.addEventListener("click", () => {
const key = header.dataset.key;
state.sort = { key, direction: state.sort.key === key && state.sort.direction === "desc" ? "asc" : "desc" };
renderHead();
renderRows();
}));
}
function filteredRows() {
const query = $("#search").value.trim().toLowerCase();
const type = $("#type-filter").value;
const precision = $("#precision-filter").value;
const available = $("#available-filter").checked;
const rows = state.rows.filter((row) => {
const haystack = `${row.Model || ""} ${row["Hub License"] || ""}`.toLowerCase();
return (!query || haystack.includes(query)) && (!type || row.Type === type) && (!precision || row.Precision === precision) && (!available || row["Available on the hub"] === true);
});
const multiplier = state.sort.direction === "asc" ? 1 : -1;
return rows.sort((a, b) => {
const av = a[state.sort.key];
const bv = b[state.sort.key];
if (typeof av === "number" && typeof bv === "number") return (av - bv) * multiplier;
return String(av ?? "").localeCompare(String(bv ?? "")) * multiplier;
});
}
function cell(row, column, rank) {
const value = row[column.key];
if (column.key === "rank") return `<td class="rank ${rank < 3 ? "top" : ""}">${String(rank + 1).padStart(2, "0")}</td>`;
if (column.key === "Model") {
const id = safeModelId(value);
return `<td class="model-cell">${id ? `<a href="https://huggingface.co/${encodeURI(id)}" target="_blank" rel="noreferrer">${escapeHtml(id)}</a>` : escapeHtml(value)}</td>`;
}
if (column.key === "Available on the hub") return `<td><span class="availability ${value === true ? "yes" : ""}" title="${value === true ? "Available" : "Unavailable"}"></span></td>`;
if (["Type", "Precision", "Hub License"].includes(column.key)) return `<td><span class="pill">${escapeHtml(value || "—")}</span></td>`;
if (column.score) return `<td class="score ${column.key === "Average ⬆️" ? "primary" : ""}">${formatScore(value)}</td>`;
return `<td>${escapeHtml(value ?? "—")}</td>`;
}
function renderRows() {
const rows = filteredRows();
$("#leaderboard-body").innerHTML = rows.map((row, rank) => `<tr>${columns.map((column) => cell(row, column, rank)).join("")}</tr>`).join("");
$(".table-shell").classList.toggle("is-empty", rows.length === 0);
$("#empty-state").classList.toggle("hidden", rows.length > 0);
$("#result-count").textContent = `${rows.length} model${rows.length === 1 ? "" : "s"} shown`;
}
function populateSelect(selector, values, selected = "") {
const select = $(selector);
const existing = select.querySelector("option")?.outerHTML || "";
select.innerHTML = existing + values.map((value) => `<option value="${escapeHtml(value)}" ${value === selected ? "selected" : ""}>${escapeHtml(value)}</option>`).join("");
}
function renderQueues(queues) {
const definitions = [
["finished", "Finished", "Recently completed"],
["running", "Running", "Evaluations in progress"],
["pending", "Pending", "Waiting to be evaluated"],
];
$("#queue-grid").innerHTML = definitions.map(([key, label, help]) => {
const rows = queues[key] || [];
const latest = rows[0]?.model ? `Latest: ${escapeHtml(rows[0].model)}` : help;
return `<article class="queue-card ${key}"><header><h3>${label}</h3><strong>${rows.length}</strong></header><p>${latest}</p></article>`;
}).join("");
}
function applyPayload(payload) {
state.payload = payload;
state.rows = payload.rows || [];
configureColumns(payload.benchmarks);
document.title = payload.copy?.title || "Open Leaderboard";
$("#leaderboard-name").textContent = payload.copy?.title || "Open Leaderboard";
$("#updated-at").textContent = `Updated ${new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" }).format(new Date(payload.updated_at))}`;
$("#data-warning").textContent = payload.error || "";
$("#data-warning").classList.toggle("hidden", !payload.error);
const types = [...new Set(state.rows.map((row) => row.Type).filter(Boolean))];
const precisions = [...new Set(state.rows.map((row) => row.Precision).filter(Boolean))];
populateSelect("#type-filter", types);
populateSelect("#precision-filter", precisions);
populateSelect('[name="model_type"]', payload.model_types || []);
populateSelect('[name="precision"]', payload.precisions || [], "float16");
populateSelect('[name="weight_type"]', payload.weight_types || [], "Original");
renderHead();
renderRows();
renderQueues(payload.queues || {});
$("#submission-copy").innerHTML = markdown(payload.copy?.submission);
$("#about-copy").innerHTML = markdown(payload.copy?.about);
if (payload.copy?.citation) {
$("#citation-card").classList.remove("hidden");
$("#citation-label").textContent = payload.copy.citation_label;
$("#citation").textContent = payload.copy.citation;
}
}
async function loadData() {
try {
state.api = await client(location.origin);
const response = await state.api.predict("/leaderboard_data", {});
applyPayload(firstData(response));
} catch (error) {
$("#leaderboard-body").innerHTML = "";
$(".table-shell").classList.add("is-empty");
$("#data-warning").textContent = `The leaderboard could not be loaded: ${error.message}`;
$("#data-warning").classList.remove("hidden");
$("#empty-state").classList.remove("hidden");
}
}
$$('.tab').forEach((tab) => tab.addEventListener("click", () => {
$$('.tab').forEach((item) => item.classList.toggle("active", item === tab));
$$('.panel').forEach((panel) => panel.classList.toggle("active", panel.id === `panel-${tab.dataset.tab}`));
history.replaceState(null, "", `#${tab.dataset.tab}`);
}));
[$("#search"), $("#type-filter"), $("#precision-filter"), $("#available-filter")].forEach((control) => control.addEventListener("input", renderRows));
$("#submit-form").addEventListener("submit", async (event) => {
event.preventDefault();
const button = event.currentTarget.querySelector("button[type=submit]");
const result = $("#submission-result");
const values = Object.fromEntries(new FormData(event.currentTarget));
button.disabled = true;
button.firstElementChild.textContent = "Validating model…";
result.className = "notice hidden";
try {
const response = await state.api.predict("/submit_model", values);
const data = firstData(response);
result.textContent = data.message;
result.className = `notice ${data.status}`;
if (data.status === "success") event.currentTarget.reset();
} catch (error) {
result.textContent = `Submission failed: ${error.message}`;
result.className = "notice error";
} finally {
button.disabled = false;
button.firstElementChild.textContent = "Submit evaluation";
}
});
$("#copy-citation").addEventListener("click", async () => {
await navigator.clipboard.writeText(state.payload.copy.citation);
$("#copy-citation").textContent = "Copied";
setTimeout(() => $("#copy-citation").textContent = "Copy citation", 1600);
});
const initialTab = location.hash.slice(1);
if (["submit", "about"].includes(initialTab)) $(`.tab[data-tab="${initialTab}"]`).click();
loadData();
|