Spaces:
Paused
Paused
File size: 22,333 Bytes
cf17f6c | 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 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Policy linting — Liquid AI</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<script>
// Private Space auth: HF signs the embedded iframe URL with ?__sign=<token>.
// Incognito / Safari block the third-party .hf.space cookie, so that token is
// the only credential — carry it on same-origin API requests, else /api/*
// returns 404 and the model-ready poll hangs.
(() => {
const sign = new URLSearchParams(location.search).get("__sign");
if (!sign) return;
const orig = self.fetch.bind(self);
self.fetch = (input, init) => {
try {
const u = new URL(typeof input === "string" ? input : input.url, location.href);
if (u.origin === location.origin && !u.searchParams.has("__sign")) {
u.searchParams.set("__sign", sign);
input = u.toString();
}
} catch (e) { /* non-URL input: pass through */ }
return orig(input, init);
};
})();
</script>
</head>
<body>
<div class="wrap">
<header class="site-intro">
<h1>Zero-shot <em>policy linting</em></h1>
<p class="sub">Lint text against <strong>customizable company rules</strong>, highlighting risky spans in one bidirectional pass.</p>
</header>
<section class="model-strip is-loading" id="model-strip" aria-label="Model status">
<span class="model-logo-frame" aria-hidden="true">
<img id="model-logo" class="model-logo" width="56" height="59" alt="" src="lliquid.gif">
</span>
<div class="model-copy">
<div class="model-name-row">
<a href="https://huggingface.co/LiquidAI/LFM2.5-Encoder-350M-Policy-Linter" target="_blank" rel="noopener">LFM2.5 Encoder</a>
<span class="model-variant">350M parameters</span>
</div>
</div>
<div class="load-block">
<div class="load-meta">
<span id="status" role="status" aria-live="polite">Connecting to server…</span>
<span id="load-percent">0%</span>
</div>
<div class="load-track" role="progressbar" aria-label="Model loading" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><span id="load-progress"></span></div>
</div>
</section>
<main>
<div class="lint-workspace" id="lint-workspace">
<section class="workspace-card policy-panel">
<div class="panel-header">
<div><h2>Linting policies</h2><p>Add, edit, or remove rules.</p></div>
<span class="policy-count" id="policy-count">4 rules</span>
</div>
<div id="policies" class="policy-list" aria-label="Linting policies"></div>
<button type="button" class="add-policy" id="add-policy"><span aria-hidden="true">+</span> Add policy</button>
</section>
<section class="workspace-card text-panel">
<div class="panel-header text-heading">
<div><h2>Text to lint</h2><p>Risky spans are highlighted as you edit.</p></div>
<div class="activity-pill is-idle" id="activity"><span class="activity-dot" aria-hidden="true"></span><span id="activity-label">Waiting for model</span></div>
</div>
<div class="editor-stage">
<div id="text" class="lint-editor" contenteditable="true" role="textbox" aria-label="Text to lint" aria-multiline="true" spellcheck="true">Dr. Sarah Johnson is the Chief Technology Officer at Northwind Systems, where she leads the engineering team. Her colleague Michael Chen works as a senior data analyst and reports to the marketing director, Emily Rodriguez. You can reach them at sarah.johnson@northwind.example or michael.chen@northwind.example. The head office is at 1200 Market Street, Suite 400, Springfield, and the regional branch sits at 45 Elm Avenue, Riverside. Next quarter, David Thompson from Globex Corporation will join as a product manager.</div>
<div class="editor-scan" aria-hidden="true"></div>
</div>
<div class="lint-controls">
<div class="threshold-control">
<div class="threshold-copy"><label for="thr">Sensitivity threshold</label><output id="thrv" for="thr">0.50</output></div>
<input id="thr" type="range" min="0.2" max="0.9" step="0.05" value="0.5">
<div class="threshold-scale"><span>More flags</span><span>Higher confidence</span></div>
</div>
<div class="stats-grid" aria-live="polite">
<div class="stat-card stat-result"><span>Result</span><strong id="stat-result">—</strong></div>
<div class="stat-card"><span>Latency</span><strong id="stat-latency">—</strong></div>
<div class="stat-card"><span>Tokens</span><strong id="stat-tokens">—</strong></div>
<div class="stat-card"><span>Policies</span><strong id="stat-policies">4</strong></div>
</div>
<div id="perf" class="sr-only"></div>
</div>
</section>
</div>
<section class="examples-panel" aria-label="Examples">
<span class="examples-label">Examples</span>
<div class="example-list" id="examples">
<button type="button" class="ex active" data-rules='["Filter all person names","Filter company names","Filter e-mail addresses","Filter addresses","Filter job roles"]' data-t="Dr. Sarah Johnson is the Chief Technology Officer at Northwind Systems, where she leads the engineering team. Her colleague Michael Chen works as a senior data analyst and reports to the marketing director, Emily Rodriguez. You can reach them at sarah.johnson@northwind.example or michael.chen@northwind.example. The head office is at 1200 Market Street, Suite 400, Springfield, and the regional branch sits at 45 Elm Avenue, Riverside. Next quarter, David Thompson from Globex Corporation will join as a product manager.">PII / personal data</button>
<button type="button" class="ex" data-rules='["Do not make unconditional delivery guarantees.","Do not disclose internal project codenames externally.","Flag mentions of competitor companies.","Avoid aggressive or threatening wording."]' data-t="We guarantee the migration will be done in two weeks — faster than Salesforce ever could. This builds on Project Zephyr, which is unannounced.">Mixed risks</button>
<button type="button" class="ex" data-rules='["Do not make unconditional delivery guarantees.","Do not disclose internal project codenames externally.","Flag mentions of competitor companies.","Avoid aggressive or threatening wording."]' data-t="Pay immediately or face the consequences.">Aggressive</button>
<button type="button" class="ex" data-rules='["Do not make unconditional delivery guarantees.","Do not disclose internal project codenames externally.","Flag mentions of competitor companies.","Avoid aggressive or threatening wording."]' data-t="We guarantee Maria's migration will be complete by Friday, with no exceptions.">Customer promise</button>
<button type="button" class="ex" data-rules='["Do not make unconditional delivery guarantees.","Do not disclose internal project codenames externally.","Flag mentions of competitor companies.","Avoid aggressive or threatening wording."]' data-t="Project Northstar is still confidential, so please do not mention it outside the launch team.">Confidential</button>
<button type="button" class="ex" data-rules='["Do not make unconditional delivery guarantees.","Do not disclose internal project codenames externally.","Flag mentions of competitor companies.","Avoid aggressive or threatening wording."]' data-t="Unlike Salesforce, our platform always migrates every customer in under fourteen days.">Competitor claim</button>
<button type="button" class="ex" data-rules='["Do not make unconditional delivery guarantees.","Do not disclose internal project codenames externally.","Flag mentions of competitor companies.","Avoid aggressive or threatening wording."]' data-t="We expect the migration to be completed within approximately two weeks, subject to final validation.">Compliant</button>
<button type="button" class="ex" data-rules='["Do not make unconditional delivery guarantees.","Do not disclose internal project codenames externally.","Flag mentions of competitor companies.","Avoid aggressive or threatening wording."]' data-t="Tell the client that Project Zephyr will launch next quarter.">Internal codename</button>
</div>
</section>
</main>
</div>
<script>
window.addEventListener("error", e => {
const el = document.getElementById("status");
if (el) el.textContent = "· ERROR: " + (e.message || (e.target && (e.target.src || e.target.href)) || "resource failed");
}, true);
</script>
<script type="module">
// The linter runs on the server (CPU, f32). This script drives the UI and asks
// /api/lint for per-token, per-rule probabilities; word grouping, the threshold,
// and highlighting are done here. Nothing is downloaded to the client.
const $ = (id) => document.getElementById(id);
function setStatus(message, tone = "loading") {
$("status").textContent = message;
const strip = $("model-strip");
strip.classList.remove("is-loading", "is-preparing", "is-ready", "is-error");
strip.classList.add(`is-${tone}`);
}
function setLoadProgress(value) {
const pct = Math.max(0, Math.min(100, Number(value) || 0));
$("load-progress").style.width = `${pct}%`;
$("load-percent").textContent = `${Math.round(pct)}%`;
document.querySelector(".load-track").setAttribute("aria-valuenow", String(Math.round(pct)));
}
function setActivity(state, label) {
$("activity").className = `activity-pill is-${state}`;
$("activity-label").textContent = label;
}
function updateRangeFill(el) {
const pct = ((+el.value - +el.min) / (+el.max - +el.min)) * 100;
el.style.setProperty("--pct", `${pct}%`);
}
// Threshold is a pure post-processing step — re-highlight locally, no server call.
$("thr").addEventListener("input", () => { updateRangeFill($("thr")); $("thrv").textContent = (+$("thr").value).toFixed(2); applyThreshold(); });
updateRangeFill($("thr"));
let READY = false;
let timer = null, lintVersion = 0, completionTimer = null;
let lastSegments = null, lastRules = [], lastNtokens = 0, lastMs = 0;
const RPROJ = 256;
const INITIAL_RULES = [
"Filter all person names",
"Filter company names",
"Filter e-mail addresses",
"Filter addresses",
"Filter job roles",
];
function escapeHtml(value) {
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
}
function appendScoredPiece(segments, piece, probabilities) {
for (const chunk of piece.match(/\s+|[^\s]+/g) || []) {
if (/^\s+$/.test(chunk)) {
segments.push({ text: chunk, kind: "space" });
continue;
}
const previous = segments[segments.length - 1];
const word = previous?.kind === "word"
? previous
: { text: "", kind: "word", probabilities: new Float32Array(probabilities.length), best: -1 };
if (word !== previous) segments.push(word);
word.text += chunk;
for (let r = 0; r < probabilities.length; r++) {
word.probabilities[r] = Math.max(word.probabilities[r], probabilities[r]);
}
}
}
function renderHighlightSegments(segments, rules, instant) {
let highlightIndex = 0;
return segments.map(segment => {
const esc = escapeHtml(segment.text);
if (segment.kind !== "word" || segment.best < 0) return esc;
const rule = segment.best;
const tip = escapeHtml(rules[rule]).replace(/"/g, """).replace(/'/g, "'");
const animated = instant ? "" : " is-animated";
return `<span class="hl${animated}" title="${tip}" style="--policy-color:var(--r${rule % 8});--highlight-index:${highlightIndex++}">${esc}</span>`;
});
}
function resizePolicyInput(input) {
input.style.height = "auto";
input.style.height = `${input.scrollHeight}px`;
}
function policyRow(rule, index) {
const row = document.createElement("div");
row.className = "policy-row";
row.style.setProperty("--policy-color", `var(--r${index % 8})`);
row.style.setProperty("--row-index", index);
const swatch = document.createElement("span");
swatch.className = "policy-swatch";
swatch.setAttribute("aria-hidden", "true");
const input = document.createElement("textarea");
input.className = "policy-input";
input.rows = 1;
input.value = rule;
input.setAttribute("aria-label", `Policy ${index + 1}`);
input.addEventListener("input", () => {
resizePolicyInput(input);
resetPolicyScores();
lintSoon();
});
const result = document.createElement("div");
result.className = "policy-result";
result.innerHTML = '<div class="policy-score-track"><span></span></div><output class="policy-score">—</output>';
const remove = document.createElement("button");
remove.className = "remove-policy";
remove.type = "button";
remove.title = "Delete policy";
remove.setAttribute("aria-label", `Delete policy ${index + 1}`);
remove.innerHTML = '<span aria-hidden="true">×</span>';
remove.addEventListener("click", () => {
row.remove();
refreshPolicyRows();
lintSoon();
});
row.append(swatch, input, result, remove);
requestAnimationFrame(() => resizePolicyInput(input));
return row;
}
function refreshPolicyRows() {
[...$("policies").children].forEach((row, index) => {
row.style.setProperty("--policy-color", `var(--r${index % 8})`);
row.style.setProperty("--row-index", index);
const input = row.querySelector(".policy-input");
const remove = row.querySelector(".remove-policy");
input.setAttribute("aria-label", `Policy ${index + 1}`);
remove.setAttribute("aria-label", `Delete policy ${index + 1}`);
});
const count = $("policies").children.length;
$("policy-count").textContent = `${count} ${count === 1 ? "rule" : "rules"}`;
$("stat-policies").textContent = count;
}
function resetPolicyScores() {
document.querySelectorAll(".policy-row").forEach(row => {
row.querySelector(".policy-score-track span").style.width = "0%";
row.querySelector(".policy-score").textContent = "—";
});
}
function getRules() {
return [...$("policies").querySelectorAll(".policy-input")].map(input => input.value.trim()).filter(Boolean);
}
for (const [index, rule] of INITIAL_RULES.entries()) $("policies").append(policyRow(rule, index));
refreshPolicyRows();
$("add-policy").addEventListener("click", () => {
const index = $("policies").children.length;
const row = policyRow("", index);
$("policies").append(row);
refreshPolicyRows();
row.querySelector(".policy-input").focus();
});
$("text").addEventListener("input", lintSoon);
$("text").addEventListener("paste", event => {
event.preventDefault();
const plain = event.clipboardData.getData("text/plain");
document.execCommand("insertText", false, plain);
});
$("examples").addEventListener("click", event => {
const button = event.target.closest(".ex");
if (!button) return;
$("examples").querySelectorAll(".ex").forEach(item => item.classList.toggle("active", item === button));
if (button.dataset.rules) {
const rules = JSON.parse(button.dataset.rules);
$("policies").innerHTML = "";
rules.forEach((rule, index) => $("policies").append(policyRow(rule, index)));
refreshPolicyRows();
}
$("text").textContent = button.dataset.t;
resetPolicyScores();
lintSoon(60);
});
function getCaretOffset(root) {
const selection = getSelection();
if (!selection || !selection.rangeCount || !root.contains(selection.anchorNode)) return root.innerText.length;
const range = selection.getRangeAt(0).cloneRange();
range.selectNodeContents(root);
range.setEnd(selection.anchorNode, selection.anchorOffset);
return range.toString().length;
}
function setCaretOffset(root, offset) {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
let remaining = offset;
let node;
while ((node = walker.nextNode())) {
if (remaining <= node.data.length) {
const range = document.createRange();
range.setStart(node, remaining);
range.collapse(true);
const selection = getSelection();
selection.removeAllRanges();
selection.addRange(range);
return;
}
remaining -= node.data.length;
}
}
// ---- apply the threshold to the last server result (no re-encode) ----
function applyThreshold(instant = false) {
if (!lastSegments) return;
const rules = lastRules;
const R = rules.length;
const thr = +$("thr").value;
const ruleMax = new Float32Array(R);
const ruleHits = new Uint16Array(R);
let nRisk = 0;
for (const segment of lastSegments) {
if (segment.kind !== "word") continue;
segment.best = -1;
let bestP = thr;
for (let r = 0; r < R; r++) {
const p = segment.probabilities[r];
if (p > ruleMax[r]) ruleMax[r] = p;
if (p > thr) ruleHits[r]++;
if (p > bestP) { segment.best = r; bestP = p; }
}
if (segment.best >= 0) nRisk++;
}
const editor = $("text");
const frag = renderHighlightSegments(lastSegments, rules, instant);
const caret = editor === document.activeElement ? getCaretOffset(editor) : null;
editor.innerHTML = frag.join("") || "";
if (caret !== null) setCaretOffset(editor, caret);
$("perf").textContent = `${lastMs} ms · ${lastNtokens} tokens · ${R} rules · ${nRisk ? nRisk + " highlighted span(s)" : "clean"}`;
$("stat-result").textContent = nRisk ? `${nRisk} ${nRisk === 1 ? "flag" : "flags"}` : "Clean";
document.querySelector(".stat-result").classList.toggle("is-clean", !nRisk);
$("stat-latency").textContent = `${lastMs} ms`;
$("stat-tokens").textContent = lastNtokens;
$("stat-policies").textContent = R;
const stats = document.querySelector(".stats-grid");
stats.classList.remove("has-result");
void stats.offsetWidth;
stats.classList.add("has-result");
const activeRows = [...document.querySelectorAll(".policy-row")].filter(row => row.querySelector(".policy-input").value.trim());
requestAnimationFrame(() => activeRows.forEach((row, index) => {
const probability = (ruleMax[index] || 0) * 100;
row.querySelector(".policy-score-track span").style.width = `${probability.toFixed(1)}%`;
row.querySelector(".policy-score").textContent = ruleHits[index] ? `${Math.round(probability)}% · ${ruleHits[index]}` : `${Math.round(probability)}%`;
}));
return nRisk;
}
async function lint({ instant = false } = {}) {
if (!READY) return;
const runVersion = lintVersion;
const editor = $("text");
const text = editor.innerText.replace(/\r/g, "");
const rules = getRules();
if (!text.trim() || !rules.length) {
editor.textContent = text;
lastSegments = null;
$("perf").textContent = !rules.length ? "Add a policy to begin linting." : "";
$("stat-result").textContent = !rules.length ? "Add a rule" : "No text";
$("stat-latency").textContent = "—";
$("stat-tokens").textContent = "—";
setActivity("idle", "Ready");
return;
}
const workspace = $("lint-workspace");
workspace.classList.remove("is-complete");
const animationStarted = performance.now();
if (!instant) {
workspace.classList.add("is-linting");
setActivity("running", "Linting…");
resetPolicyScores();
}
let data;
try {
const resp = await fetch("api/lint", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text, rules }),
});
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
data = await resp.json();
} catch (e) {
workspace.classList.remove("is-linting");
setActivity("idle", "Lint failed");
return;
}
if (runVersion !== lintVersion) return;
// build word/space segments from the per-token pieces + probabilities
const segments = [];
for (const { piece, probs } of data.tokens) appendScoredPiece(segments, piece, Float32Array.from(probs));
lastSegments = segments;
lastRules = rules;
lastNtokens = data.ntokens;
lastMs = data.ms;
if (!instant) {
const remaining = 480 - (performance.now() - animationStarted);
if (remaining > 0) await new Promise(resolve => setTimeout(resolve, remaining));
if (runVersion !== lintVersion) return;
}
const nRisk = applyThreshold(instant);
workspace.classList.remove("is-linting");
if (!instant) {
workspace.classList.add("is-complete");
setActivity("done", nRisk ? "Processed · risks found" : "Processed · clean");
clearTimeout(completionTimer);
completionTimer = setTimeout(() => workspace.classList.remove("is-complete"), 700);
} else {
setActivity("done", "Processed");
}
}
function lintSoon(delay = 300) {
lintVersion++;
clearTimeout(timer);
timer = setTimeout(() => lint().catch(error => {
$("lint-workspace").classList.remove("is-linting");
setActivity("idle", "Lint failed");
console.error(error);
}), delay);
}
// ---------- wait for the server-side model, then run the first lint ----------
async function waitForServer() {
setStatus("Connecting to server…", "loading");
setLoadProgress(12);
for (let attempt = 0; attempt < 900; attempt++) {
try {
const r = await fetch("api/ready", { cache: "no-store" });
if (r.ok && (await r.json()).ready) return true;
} catch (e) { /* server still starting */ }
setStatus("Warming up model on the server…", "preparing");
setLoadProgress(Math.min(92, 12 + attempt * 4));
await new Promise((r) => setTimeout(r, 1000));
}
return false;
}
(async () => {
const ok = await waitForServer();
if (!ok) { setStatus("Model unavailable", "error"); setLoadProgress(100); $("load-percent").textContent = "Error"; setActivity("idle", "Model unavailable"); return; }
READY = true;
setLoadProgress(100);
setStatus("Model ready", "ready");
await lint({ instant: true });
window.__LINT_READY = true;
})();
</script>
</body>
</html>
|