Spaces:
Running
Running
Download main.js from mrfakename/kumo-tabular-webgpu: direct link, hf CLI and curl.
- Browser
- Download file 5.97 kB
-
https://huggingface.co/spaces/mrfakename/kumo-tabular-webgpu/resolve/main/main.js
- Command line
-
hf download hf://spaces/mrfakename/kumo-tabular-webgpu/main.js
-
curl -L -o main.js https://huggingface.co/spaces/mrfakename/kumo-tabular-webgpu/resolve/main/main.js
5.97 kB
| import Papa from "https://cdn.jsdelivr.net/npm/papaparse@5.5.3/+esm"; | |
| const $ = (id) => document.getElementById(id); | |
| const state = { ctx: null, qry: null, result: null }; | |
| const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" }); | |
| const MAX_PREVIEW = 300; | |
| if (!("gpu" in navigator)) { | |
| $("backend").value = "wasm"; | |
| $("backend").querySelector('[value="webgpu"]').textContent = "WebGPU (unavailable)"; | |
| } | |
| function setStatus(msg, err = false) { | |
| $("status").textContent = msg; | |
| $("status").classList.toggle("err", err); | |
| } | |
| function setProgress(p) { | |
| const el = $("progress"); | |
| el.hidden = p == null; | |
| if (p != null) el.firstElementChild.style.width = `${Math.round(p * 100)}%`; | |
| } | |
| function parseCSV(text) { | |
| const res = Papa.parse(text.trim(), { header: true, skipEmptyLines: "greedy", delimitersToGuess: [",", "\t", ";", "|"] }); | |
| const columns = (res.meta.fields || []).map((c) => c.trim()); | |
| const rows = res.data.map((r) => { | |
| const o = {}; | |
| (res.meta.fields || []).forEach((f, i) => { const v = r[f]; o[columns[i]] = v == null ? "" : String(v).trim(); }); | |
| return o; | |
| }); | |
| if (!columns.length || !rows.length) throw new Error("CSV has no header or rows"); | |
| return { columns, rows }; | |
| } | |
| function renderTable(el, columns, rows, opts = {}) { | |
| const head = "<tr>" + columns.map((c) => `<th>${esc(c)}</th>`).join("") + "</tr>"; | |
| const body = rows.slice(0, opts.limit ?? MAX_PREVIEW).map((r) => | |
| "<tr>" + columns.map((c) => { | |
| const cls = opts.cellClass ? opts.cellClass(c, r) : ""; | |
| return `<td${cls ? ` class="${cls}"` : ""}>${esc(fmt(r[c]))}</td>`; | |
| }).join("") + "</tr>").join(""); | |
| el.innerHTML = `<table><thead>${head}</thead><tbody>${body}</tbody></table>`; | |
| } | |
| const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c])); | |
| const fmt = (v) => (typeof v === "number" ? (Number.isInteger(v) ? v : +v.toPrecision(5)) : v); | |
| function refresh() { | |
| if (state.ctx) { | |
| renderTable($("ctxTable"), state.ctx.columns, state.ctx.rows); | |
| $("ctxInfo").textContent = `${state.ctx.rows.length} rows · ${state.ctx.columns.length} columns`; | |
| const sel = $("target"), prev = sel.value; | |
| sel.innerHTML = state.ctx.columns.map((c) => `<option>${esc(c)}</option>`).join(""); | |
| sel.value = state.ctx.columns.includes(prev) ? prev : state.ctx.columns[state.ctx.columns.length - 1]; | |
| } else { | |
| $("ctxTable").innerHTML = ""; $("ctxInfo").textContent = ""; | |
| } | |
| if (state.qry) { | |
| renderTable($("qryTable"), state.qry.columns, state.qry.rows); | |
| $("qryInfo").textContent = `${state.qry.rows.length} rows`; | |
| } else { | |
| $("qryTable").innerHTML = ""; $("qryInfo").textContent = "(none: blank-target context rows are predicted)"; | |
| } | |
| $("run").disabled = !state.ctx; | |
| } | |
| async function loadExamples() { | |
| const list = await (await fetch("examples/index.json")).json(); | |
| for (const ex of list) { | |
| const o = document.createElement("option"); | |
| o.value = ex.id; o.textContent = ex.name; o.dataset.target = ex.target; o.dataset.task = ex.task; | |
| $("example").append(o); | |
| } | |
| } | |
| $("example").addEventListener("change", async (e) => { | |
| const opt = e.target.selectedOptions[0]; | |
| if (!opt.value) return; | |
| const [c, q] = await Promise.all(["context", "query"].map((k) => fetch(`examples/${opt.value}_${k}.csv`).then((r) => r.text()))); | |
| state.ctx = parseCSV(c); state.qry = parseCSV(q); | |
| $("ctxFile").value = ""; $("qryFile").value = ""; | |
| refresh(); | |
| $("target").value = opt.dataset.target; | |
| $("task").value = opt.dataset.task; | |
| setStatus(`Loaded "${opt.textContent}". Press Predict.`); | |
| }); | |
| for (const [id, key] of [["ctxFile", "ctx"], ["qryFile", "qry"]]) { | |
| $(id).addEventListener("change", async (e) => { | |
| const f = e.target.files[0]; | |
| if (!f) { state[key] = null; refresh(); return; } | |
| try { | |
| state[key] = parseCSV(await f.text()); | |
| $("example").value = ""; | |
| refresh(); | |
| setStatus(`Loaded ${f.name}.`); | |
| } catch (err) { setStatus(`Could not read ${f.name}: ${err.message}`, true); } | |
| }); | |
| } | |
| $("run").addEventListener("click", () => { | |
| if (!state.ctx) return; | |
| $("run").disabled = true; | |
| setProgress(0); | |
| setStatus("Starting…"); | |
| worker.postMessage({ | |
| type: "predict", | |
| ctx: state.ctx, qry: state.qry, | |
| target: $("target").value, task: $("task").value, size: $("size").value, | |
| numEstimators: +$("nest").value, backend: $("backend").value, | |
| }); | |
| }); | |
| worker.onmessage = ({ data }) => { | |
| if (data.type === "status") { setStatus(data.message); if (data.progress != null) setProgress(data.progress); } | |
| else if (data.type === "error") { setStatus(data.message, true); setProgress(null); $("run").disabled = !state.ctx; } | |
| else if (data.type === "result") { | |
| setProgress(null); | |
| $("run").disabled = false; | |
| state.result = data; | |
| const predCol = data.columns[0]; | |
| const truthCol = data.columns.find((c) => c.startsWith("true_")); | |
| renderTable($("outTable"), data.columns, data.rows, { | |
| limit: 2000, | |
| cellClass: (c, r) => c === predCol ? (truthCol && r[truthCol] !== "" && data.task === "classification" && String(r[truthCol]) !== String(r[predCol]) ? "pred bad" : "pred") : "", | |
| }); | |
| $("metrics").textContent = data.metrics || ""; | |
| $("results").hidden = false; | |
| setStatus(data.summary); | |
| } | |
| }; | |
| worker.onerror = (e) => { setStatus(`Worker error: ${e.message}`, true); setProgress(null); $("run").disabled = !state.ctx; }; | |
| $("download").addEventListener("click", () => { | |
| const r = state.result; if (!r) return; | |
| const csv = Papa.unparse({ fields: r.columns, data: r.rows.map((row) => r.columns.map((c) => row[c])) }); | |
| const a = document.createElement("a"); | |
| a.href = URL.createObjectURL(new Blob([csv], { type: "text/csv" })); | |
| a.download = "predictions.csv"; a.click(); | |
| setTimeout(() => URL.revokeObjectURL(a.href), 1000); | |
| }); | |
| loadExamples().then(refresh).catch((e) => setStatus(`Failed to load examples: ${e.message}`, true)); | |