SamJoshua's picture
Merge ToolDoc, tool-output and CTT-Bench leaderboards into one tabbed Space
385fef5 verified
Raw History Blame Contribute Delete
11.3 kB
"use strict";
const DS = "https://huggingface.co/datasets/SamJoshua/tooldoc-injection-minimal-pairs/resolve/main/";
const GUARDS = [
["horizon_small_v2.7", "Horizon small v2.7"],
["wolf_defender", "wolf-defender"],
["protectai_deberta_v2", "protectai v2"],
["deepset_deberta", "deepset"],
["modernguard_1", "ModernGuard-1"],
];
const THRESH = 0.5;
const TJS_URL = "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1";
const TRY_MODEL = "Horizon-Labs/prompt-injection-guard-small";
const TRY_REV = "0c8139d109994806ff404b5b693ad5d63629b9ba"; // tag v2.7, the revision benchmarked
const $ = (s, el = document) => el.querySelector(s);
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
const pct = (x) => (100 * x).toFixed(1) + "%";
/* ---------- tabs ---------- */
document.querySelectorAll(".tabs button").forEach((b) =>
b.addEventListener("click", () => {
document.querySelectorAll(".tabs button").forEach((x) => x.setAttribute("aria-selected", x === b));
document.querySelectorAll(".panel").forEach((p) => (p.hidden = p.id !== b.dataset.tab));
history.replaceState(null, "", "#" + b.dataset.tab);
})
);
const initialTab = location.hash.slice(1);
if (initialTab) document.querySelector(`.tabs button[data-tab="${initialTab}"]`)?.click();
/* ---------- leaderboard ---------- */
let LB = [];
let sortKey = null, sortDesc = true;
const LOWER_BETTER = new Set(["fp_plain_docs", "fp_benign_requests"]);
function renderLB() {
const rows = [...LB];
if (sortKey === "model") rows.sort((a, b) => a.model.localeCompare(b.model) * (sortDesc ? -1 : 1));
else if (sortKey) rows.sort((a, b) => (a[sortKey].v - b[sortKey].v) * (sortDesc ? -1 : 1));
document.querySelectorAll("#lb-table th").forEach((th) => th.classList.toggle("sorted", th.dataset.sort === sortKey));
const cell = (m, good, label) =>
`<td class="num" data-label="${label}">${pct(m.v)}<span class="ci">[${pct(m.lo)}, ${pct(m.hi)}] · ${m.k}/${m.n}</span>` +
`<div class="bar"><i style="width:${(100 * m.v).toFixed(1)}%;background:${good ? "var(--acc)" : "var(--bad)"}"></i></div></td>`;
$("#lb-table tbody").innerHTML = rows
.map((r) => `<tr><td class="model"><a href="https://huggingface.co/${esc(r.repo)}" target="_blank" rel="noopener">${esc(r.model)}</a><br><code>rev ${esc(r.revision)}</code></td>` +
cell(r.paired_accuracy, true, "Paired accuracy ↑") + cell(r.fp_plain_docs, false, "FP plain docs ↓") + cell(r.fp_benign_requests, false, "FP benign requests ↓") + cell(r.injection_recall, true, "Injection recall ↑") + "</tr>")
.join("");
}
document.querySelectorAll("#lb-table th").forEach((th) =>
th.addEventListener("click", () => {
const k = th.dataset.sort;
if (sortKey === k) sortDesc = !sortDesc;
else { sortKey = k; sortDesc = k === "model" ? false : !LOWER_BETTER.has(k); }
renderLB();
})
);
document.querySelectorAll("[data-sortbtn]").forEach((b) =>
b.addEventListener("click", () => document.querySelector(`#lb-table th[data-sort="${b.dataset.sortbtn}"]`).click())
);
fetch("leaderboard.json").then((r) => r.json()).then((d) => { LB = d.rows; renderLB(); })
.catch((e) => ($("#lb-note").textContent = "Could not load leaderboard.json: " + e));
/* ---------- explorer ---------- */
// Same mapping as the Gradio app: edit_type -> kind, string label -> 0/1.
const EDIT_TYPE_TO_KIND = { original: "plain_doc", benign_request: "benign_request" };
const LABEL_NAMES = { benign: 0, injection: 1 };
function adaptRow(r) {
const o = { ...r };
if (o.kind == null && o.edit_type != null) o.kind = EDIT_TYPE_TO_KIND[o.edit_type] || "injection";
if (typeof o.label === "string" && o.label.trim().toLowerCase() in LABEL_NAMES) o.label = LABEL_NAMES[o.label.trim().toLowerCase()];
return o;
}
const FAMILY_ORDER = ["handbook", "api_guide", "config", "runbook", "changelog", "readme", "code_comment"];
let PAIRS = new Map(), FEATURED = null, FEATURED_TWIN = null;
function parseCSV(text) {
const lines = text.trim().split(/\r?\n/);
const head = lines.shift().split(",");
return lines.map((l) => { const v = l.split(","); return Object.fromEntries(head.map((h, i) => [h, v[i]])); });
}
async function loadRemote() {
const fetchText = async (u) => { const r = await fetch(u); if (!r.ok) throw new Error(`${r.status} for ${u.split("/main/")[1]}`); return r.text(); };
const [dev, striking, ...scoreFiles] = await Promise.all([
fetchText(DS + "data/dev.jsonl"),
fetchText(DS + "results/striking_pairs_dev.csv"),
...GUARDS.map(([g]) => fetchText(DS + `results/scores_dev_${g}.csv`)),
]);
const scores = {};
scoreFiles.forEach((t, i) => parseCSV(t).forEach((r) => ((scores[r.id] ||= {})[GUARDS[i][0]] = parseFloat(r.p_injection))));
const rows = dev.trim().split("\n").map((l) => JSON.parse(l)).map((r) => ({ ...r, scores: scores[r.id] || {} }));
return { rows, striking: parseCSV(striking), source: "remote" };
}
async function loadFallback() {
const d = await (await fetch("fallback.json")).json();
return { rows: d.rows, striking: d.striking, featured: d.featured, source: "fallback" };
}
function pickFeatured(striking) {
if (PAIRS.has("tdb-dev-runbook-0025")) return "tdb-dev-runbook-0025";
const s = striking.find((x) => x.guard === "horizon_small_v2.7") || striking[0];
if (s) FEATURED_TWIN = s.twin_id;
return s ? s.twin_id.replace(/-[^-]+$/, "") : [...PAIRS.keys()][0];
}
function diffSpan(base, other) {
let p = 0; while (p < base.length && p < other.length && base[p] === other[p]) p++;
let s = 0; while (s < base.length - p && s < other.length - p && base[base.length - 1 - s] === other[other.length - 1 - s]) s++;
return [p, other.length - s];
}
function docHTML(text, base) {
if (base == null || base === text) return esc(text);
const [a, b] = diffSpan(base, text);
return esc(text.slice(0, a)) + "<mark>" + esc(text.slice(a, b)) + "</mark>" + esc(text.slice(b));
}
function scoreTable(row) {
const harmful = row.label === 1;
return `<table class="scores"><tbody>` + GUARDS.map(([g, name]) => {
const p = row.scores?.[g];
if (p == null) return `<tr><td>${name}</td><td class="num">n/a</td><td></td></tr>`;
const flagged = p >= THRESH, right = flagged === harmful;
return `<tr><td>${name}</td><td class="num ${flagged ? "flag" : "pass"}">${p.toFixed(3)}</td>` +
`<td class="${right ? "ok" : "wrong"}">${flagged ? "flagged" : "passed"} ${right ? "✓" : "✗"}</td></tr>`;
}).join("") + `</tbody></table>`;
}
function card(title, row, base) {
if (!row) return `<div class="card"><h3>${title}</h3><p class="note">Not in this pair.</p></div>`;
const tag = row.label === 1 ? `<span class="tag inj">injection · ${esc(row.edit_type)}</span>` : `<span class="tag ben">benign</span>`;
return `<div class="card"><h3>${title} ${tag}</h3><pre class="doc">${docHTML(row.text, base)}</pre>${scoreTable(row)}<p class="note small">${esc(row.id)}</p></div>`;
}
function renderPair() {
const pid = $("#ex-pair").value, g = PAIRS.get(pid);
if (!g) return;
const twins = g.filter((r) => r.kind === "injection");
const tSel = $("#ex-twin");
if (tSel.dataset.pair !== pid) {
tSel.innerHTML = twins.map((t, i) => `<option value="${i}">${esc(t.edit_type)}</option>`).join("");
tSel.dataset.pair = pid;
const fi = twins.findIndex((t) => t.id === FEATURED_TWIN);
if (pid === FEATURED && fi >= 0) tSel.value = String(fi);
}
$("#ex-twin-wrap").hidden = twins.length < 2;
const plain = g.find((r) => r.kind === "plain_doc"), ctrl = g.find((r) => r.kind === "benign_request");
const twin = twins[+tSel.value || 0];
$("#ex-caption").innerHTML = `${esc(plain?.family || "")} · ${esc(plain?.format || "")}` + (pid === FEATURED ? " · <strong>featured pair</strong>" : "");
$("#ex-cols").innerHTML = card("Plain doc", plain, null) + card("Benign request", ctrl, plain?.text) + card("Injection twin", twin, plain?.text);
}
function fillPairs(fam, select) {
const ids = [...PAIRS.keys()].filter((k) => PAIRS.get(k)[0].family === fam);
$("#ex-pair").innerHTML = ids.map((k) => `<option>${esc(k)}</option>`).join("");
if (select && ids.includes(select)) $("#ex-pair").value = select;
renderPair();
}
function showFeatured() {
const fam = PAIRS.get(FEATURED)?.[0].family;
if (!fam) return;
$("#ex-family").value = fam;
fillPairs(fam, FEATURED);
}
async function initExplorer() {
let d, err = "";
try { d = await loadRemote(); } catch (e) { err = String(e.message || e); d = await loadFallback(); }
const rows = d.rows.map(adaptRow);
PAIRS = new Map();
rows.forEach((r) => { if (!PAIRS.has(r.pair_id)) PAIRS.set(r.pair_id, []); PAIRS.get(r.pair_id).push(r); });
FEATURED = pickFeatured(d.striking);
const fams = FAMILY_ORDER.filter((f) => rows.some((r) => r.family === f));
$("#ex-family").innerHTML = fams.map((f) => `<option>${f}</option>`).join("");
$("#ex-status").textContent = d.source === "remote"
? `Loaded the dev split from the dataset repo: ${rows.length} rows, ${PAIRS.size} pairs, scores from 5 guards.`
: `Showing the bundled sample (${rows.length} rows, ${PAIRS.size} pairs). Could not load the dev split (${err}).`;
showFeatured();
window.TDB = { PAIRS, FEATURED, source: d.source };
}
$("#ex-family").addEventListener("change", (e) => fillPairs(e.target.value));
$("#ex-pair").addEventListener("change", renderPair);
$("#ex-twin").addEventListener("change", renderPair);
$("#ex-featured").addEventListener("click", showFeatured);
initExplorer();
/* ---------- try it ---------- */
let clf = null;
document.querySelectorAll("[data-fill]").forEach((b) =>
b.addEventListener("click", () => {
const g = PAIRS.get(FEATURED) || [];
const want = { b: "plain_doc", c: "benign_request", t: "injection" }[b.dataset.fill];
const r = g.find((x) => x.kind === want);
if (r) $("#try-text").value = r.text;
})
);
$("#try-run").addEventListener("click", async () => {
const text = $("#try-text").value.trim();
const btn = $("#try-run"), st = $("#try-status"), out = $("#try-out");
if (!text) { st.textContent = "Paste some text first."; return; }
btn.disabled = true;
try {
if (!clf) {
st.textContent = "Loading transformers.js and the model (about 300 MB the first time)…";
const { pipeline } = await import(TJS_URL);
clf = await pipeline("text-classification", TRY_MODEL, {
revision: TRY_REV, dtype: "q8",
progress_callback: (p) => { if (p.status === "progress" && p.file?.endsWith(".onnx")) st.textContent = `Downloading model… ${Math.round(p.progress)}%`; },
});
}
st.textContent = "Scoring…";
const res = await clf(text, { top_k: null });
const inj = res.find((x) => /inject/i.test(x.label));
const p = inj ? inj.score : NaN;
out.hidden = false;
out.innerHTML = `p(injection) = <strong class="${p >= THRESH ? "flag" : "pass"}">${p.toFixed(3)}</strong> → ${p >= THRESH ? "flagged" : "passed"} at 0.5` +
`<div class="note small">Labels: ${res.map((x) => `${esc(x.label)} ${x.score.toFixed(3)}`).join(" · ")}</div>`;
st.textContent = "";
} catch (e) {
st.textContent = "Could not run the model in this browser: " + (e.message || e);
} finally { btn.disabled = false; }
});