Spaces:
Running
Running
Download main.js from localangle/cite-demo: direct link, hf CLI and curl.
- Browser
- Download file 9.22 kB
-
https://huggingface.co/spaces/localangle/cite-demo/resolve/main/main.js
- Command line
-
hf download hf://spaces/localangle/cite-demo/main.js
-
curl -L -o main.js https://huggingface.co/spaces/localangle/cite-demo/resolve/main/main.js
9.22 kB
| import { CiteWeb, DEFAULT_MODEL, MODELS, splitParagraphs } from "./lib/cite.js"; | |
| const EXAMPLE = `MILLBROOK — The Millbrook City Council voted 5-2 on Tuesday to approve a $4.2 million renovation of the Harlan Street library, ending a debate that stretched across three budget cycles. | |
| The plan adds a children's wing, replaces the 1970s heating system and makes the building fully accessible, according to library director Dana Ortiz. | |
| Council members Rick Paulsen and Maria Chen voted against the measure. Paulsen said the city should first repair roads on the east side, which residents have complained about for years. | |
| Construction is expected to begin in March and last about 14 months. During that time, the library will operate out of a temporary space in the former Elm Street bank building. | |
| The renovation will be paid for with a mix of state grants and a bond approved by voters in 2024. Ortiz said no new property tax increase will be needed. | |
| The Harlan Street library opened in 1962 and serves roughly 9,000 cardholders. Its last major update was in 1978. | |
| In other business, the council approved a new contract for the city's trash hauler and tabled a proposal to extend downtown parking meter hours.`; | |
| function initialModel() { | |
| const fromUrl = new URLSearchParams(location.search).get("model"); | |
| if (MODELS[fromUrl]) return fromUrl; | |
| try { | |
| const saved = localStorage.getItem("cite-model"); | |
| if (MODELS[saved]) return saved; | |
| } catch { | |
| // storage may be unavailable | |
| } | |
| return DEFAULT_MODEL; | |
| } | |
| let cite = null; | |
| let loadToken = 0; | |
| let history = []; | |
| let viewIndex = 0; | |
| let loading = true; | |
| function esc(value) { | |
| return String(value).replace( | |
| /[&<>"']/g, | |
| (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] | |
| ); | |
| } | |
| function updateCount() { | |
| const count = splitParagraphs(document.getElementById("article").value).length; | |
| document.getElementById("paragraph-count").textContent = | |
| `${count} paragraph${count === 1 ? "" : "s"}`; | |
| } | |
| function pct(p) { | |
| return `${(100 * p).toFixed(1)}%`; | |
| } | |
| const HEAT_FLOOR = 0.25; | |
| /** | |
| * Accent green wash. Heat is relative to the question's top score, with a floor so | |
| * that soft questions (low top score) are stretched while questions where nothing | |
| * scores stay pale. Scores under 1% stay white. Displayed % is always the raw score. | |
| */ | |
| function heatBackground(probability, topProbability) { | |
| const p = Math.max(0, Math.min(1, Number(probability) || 0)); | |
| if (p < 0.01) return "transparent"; | |
| const scale = Math.max(Number(topProbability) || 0, HEAT_FLOOR); | |
| const rel = Math.min(1, p / scale); | |
| // Convex curve: low scores stay near-white, the top score is the darkest. | |
| const alpha = 0.015 + 0.68 * Math.pow(rel, 1.7); | |
| return `rgba(29, 103, 81, ${alpha.toFixed(3)})`; | |
| } | |
| function card(result) { | |
| const cut = result.truncated_paragraphs | |
| ? `<div class="hint error" style="margin-bottom:10px">${result.truncated_paragraphs} paragraph(s) past the ${result.soft_cap}-token soft cap were not scored.</div>` | |
| : ""; | |
| const top = Math.max( | |
| 0, | |
| ...result.paragraphs.filter((p) => p.logit != null).map((p) => p.probability) | |
| ); | |
| const paras = result.paragraphs | |
| .map((p) => { | |
| const cutPara = p.logit == null; | |
| const score = cutPara ? "—" : pct(p.probability); | |
| const bg = cutPara ? "transparent" : heatBackground(p.probability, top); | |
| return `<div class="heat-para${cutPara ? " heat-cut" : ""}" style="background:${bg}"> | |
| <div>${esc(p.text)}</div> | |
| <div class="heat-meta">¶${p.index + 1} · ${score}</div> | |
| </div>`; | |
| }) | |
| .join(""); | |
| return `<div class="result-card"> | |
| <div class="result-head"><div class="question">${esc(result.question)}</div><div class="meta">${result.ms} ms · ${result.tokens} tokens · ${esc(result.model || "")} · WASM</div></div> | |
| <div class="result-main">${cut}${paras}</div> | |
| </div>`; | |
| } | |
| function showOlder() { | |
| if (viewIndex >= history.length - 1) return; | |
| viewIndex += 1; | |
| render(); | |
| } | |
| function showNewer() { | |
| if (viewIndex <= 0) return; | |
| viewIndex -= 1; | |
| render(); | |
| } | |
| function render() { | |
| const target = document.getElementById("results"); | |
| const pager = document.getElementById("pager"); | |
| const label = document.getElementById("pager-label"); | |
| const prev = document.getElementById("pager-prev"); | |
| const next = document.getElementById("pager-next"); | |
| if (!history.length) { | |
| target.innerHTML = `<div class="empty"><div><strong>No questions yet</strong>Paste an article and ask a question.</div></div>`; | |
| document.getElementById("latency").textContent = ""; | |
| pager.classList.remove("visible"); | |
| return; | |
| } | |
| viewIndex = Math.max(0, Math.min(viewIndex, history.length - 1)); | |
| const result = history[viewIndex]; | |
| target.innerHTML = card(result); | |
| target.scrollTop = 0; | |
| document.getElementById("latency").textContent = `${result.ms} ms`; | |
| if (history.length > 1) { | |
| pager.classList.add("visible"); | |
| label.textContent = `${viewIndex + 1} / ${history.length}`; | |
| prev.disabled = viewIndex >= history.length - 1; | |
| next.disabled = viewIndex <= 0; | |
| } else { | |
| pager.classList.remove("visible"); | |
| } | |
| } | |
| window.showOlder = showOlder; | |
| window.showNewer = showNewer; | |
| window.resetExample = function resetExample() { | |
| document.getElementById("article").value = EXAMPLE; | |
| history = []; | |
| viewIndex = 0; | |
| render(); | |
| updateCount(); | |
| }; | |
| window.clearArticle = function clearArticle() { | |
| document.getElementById("article").value = ""; | |
| history = []; | |
| viewIndex = 0; | |
| render(); | |
| updateCount(); | |
| document.getElementById("article").focus(); | |
| }; | |
| window.ask = async function ask() { | |
| const button = document.getElementById("ask"); | |
| const status = document.getElementById("status"); | |
| if (loading) { | |
| status.className = "hint error"; | |
| status.textContent = "Still downloading the model…"; | |
| return; | |
| } | |
| const question = document.getElementById("question").value; | |
| const paragraphs = splitParagraphs(document.getElementById("article").value); | |
| button.disabled = true; | |
| status.className = "hint"; | |
| status.textContent = "Scoring in your browser…"; | |
| try { | |
| if (!paragraphs.length) throw new Error("paste an article first"); | |
| if (!question.trim()) throw new Error("ask a question"); | |
| const out = await cite.predict(question.trim(), paragraphs); | |
| history.unshift({ | |
| question: question.trim(), | |
| paragraphs: out.scores.map((score) => ({ | |
| ...score, | |
| text: paragraphs[score.index], | |
| })), | |
| tokens: out.tokens, | |
| truncated_paragraphs: out.truncated_paragraphs, | |
| soft_cap: out.soft_cap, | |
| ms: out.ms, | |
| model: cite.label, | |
| }); | |
| viewIndex = 0; | |
| render(); | |
| status.textContent = | |
| "Cite scores each paragraph for the question. Shading is relative to the top score."; | |
| document.getElementById("question").select(); | |
| } catch (error) { | |
| status.className = "hint error"; | |
| status.textContent = error.message || String(error); | |
| } finally { | |
| button.disabled = false; | |
| } | |
| }; | |
| document.getElementById("question").addEventListener("keydown", (event) => { | |
| if (event.key === "Enter") window.ask(); | |
| }); | |
| document.getElementById("article").addEventListener("input", () => { | |
| history = []; | |
| viewIndex = 0; | |
| render(); | |
| updateCount(); | |
| }); | |
| window.resetExample(); | |
| const READY_HINT = "Cite scores each paragraph for the question. Shading is relative to the top score."; | |
| function loadModel(key) { | |
| const token = ++loadToken; | |
| const previous = cite; | |
| loading = true; | |
| const select = document.getElementById("model"); | |
| select.value = key; | |
| select.disabled = true; | |
| document.getElementById("ask").disabled = true; | |
| const status = document.getElementById("status"); | |
| status.className = "hint"; | |
| status.textContent = `Downloading Cite ${MODELS[key].label} for the browser…`; | |
| const next = new CiteWeb(key); | |
| const done = () => { | |
| if (token === loadToken) select.disabled = false; | |
| }; | |
| return Promise.resolve(previous ? previous.release() : null) | |
| .then(() => | |
| next.load({ | |
| onProgress(fraction, label) { | |
| if (token !== loadToken) return; | |
| document.getElementById("info").textContent = | |
| `downloading ${label || "model"}… ${Math.round(fraction * 100)}%`; | |
| }, | |
| }) | |
| ) | |
| .then((info) => { | |
| if (token !== loadToken) return; | |
| cite = next; | |
| loading = false; | |
| document.getElementById("ask").disabled = false; | |
| document.getElementById("info").textContent = | |
| `${info.package} · ${info.label} · ${info.sizeMb} MB WASM · soft cap ${info.softCap}`; | |
| status.className = "hint"; | |
| status.textContent = READY_HINT; | |
| try { | |
| localStorage.setItem("cite-model", key); | |
| } catch { | |
| // ignore | |
| } | |
| done(); | |
| }) | |
| .catch((error) => { | |
| if (token !== loadToken) return; | |
| loading = true; | |
| document.getElementById("info").textContent = "load failed"; | |
| status.className = "hint error"; | |
| status.textContent = error.message || String(error); | |
| done(); | |
| }); | |
| } | |
| window.switchModel = function switchModel(key) { | |
| if (!MODELS[key] || (cite && cite.variant === key && !loading)) return; | |
| loadModel(key); | |
| }; | |
| loadModel(initialModel()); | |