// decima-pii page: text in, marked text and a redacted copy out. The model runs in a Web Worker (pii-worker.js, // ONNX Runtime Web); pii-core.js is the port of decima_pii.py (offsets, windows, decode, postfilter). import { isCached } from "./decima.js"; import { redact } from "./pii-core.js"; const $ = (s, el = document) => el.querySelector(s); const params = new URLSearchParams(location.search); const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); const mb = (b) => (b / 1e6).toFixed(0); const MODEL = { name: "decima-pii", url: (params.get("model") || "https://huggingface.co/amyrmahdy/decima-pii/resolve/v0.2.1/").replace(/\/?$/, "/"), cache: "decima-pii-model-v0.2", // bump when the files at `url` change: cached files are keyed by URL sizes: { "onnx/model_quantized.onnx": 143051135, "tokenizer.json": 34363286, "pii_meta.json": 1379 }, }; MODEL.bytes = Object.values(MODEL.sizes).reduce((a, b) => a + b, 0); const FILES = Object.keys(MODEL.sizes); const LABELS = { PERSON_NAME: { name: "name", tone: "pi-who" }, PHONE: { name: "phone", tone: "pi-contact" }, EMAIL: { name: "email", tone: "pi-contact" }, IP_ADDRESS: { name: "IP address", tone: "pi-contact" }, NATIONAL_ID: { name: "national ID", tone: "pi-id" }, PASSPORT: { name: "passport", tone: "pi-id" }, IBAN: { name: "IBAN", tone: "pi-id" }, CARD: { name: "card number", tone: "pi-id" }, ADDRESS: { name: "address", tone: "pi-where" }, DATE_OF_BIRTH: { name: "date of birth", tone: "pi-where" }, }; // Written for this page; none is taken from a test set. const EXAMPLES = [ { tag: "Persian", text: "اسم من علی رضایی است و کد ملی من ۰۰۱۲۳۴۵۶۷۸ و شماره موبایلم ۰۹۱۲۳۴۵۶۷۸۹ است." }, { tag: "Arabic", text: "مرحبا، أنا أحمد الكعبي، رقم هاتفي +974 5512 3456 وبريدي ahmed.k@example.qa" }, { tag: "Turkish", text: "Merhaba, ben Ayşe Yılmaz, TC kimlik numaram 10000000146, telefonum 0532 123 45 67." }, { tag: "English", text: "My name is Sara Ahmadi and my card is 5185 5272 2255 5565." }, ]; // ───────────────────────────── worker ───────────────────────────── const worker = new Worker(new URL("./pii-worker.js", import.meta.url), { type: "module" }); let seq = 0; const pending = new Map(); worker.onmessage = ({ data }) => { const p = pending.get(data.id); if (!p) return; if (data.progress) return p.onProgress?.(data.progress); pending.delete(data.id); data.error ? p.reject(new Error(data.error)) : p.resolve(data.result); }; worker.onerror = (e) => { for (const p of pending.values()) p.reject(new Error(e.message || "worker failed")); pending.clear(); }; const call = (op, args = {}, onProgress) => new Promise((resolve, reject) => { const id = ++seq; pending.set(id, { resolve, reject, onProgress }); worker.postMessage({ id, op, ...args }); }); let loading = null; let ready = false; function showLoader(p) { const L = $("#loader"), bar = $("#load-bar"), txt = $("#load-text"), num = $("#load-num"); L.hidden = false; L.classList.remove("is-ready", "is-error"); if (!p || p.preparing || p.cached || (p.total && p.loaded >= p.total)) { bar.classList.add("is-indeterminate"); bar.firstElementChild.style.width = ""; txt.innerHTML = !p ? `Loading ${MODEL.name}` : p.cached && !p.preparing ? `Loading ${MODEL.name} from this device, saved on an earlier visit.` : `Preparing ${MODEL.name} for this browser.`; num.textContent = p?.total ? `${mb(p.total)} MB` : ""; return; } const frac = p.total ? Math.min(1, p.loaded / p.total) : 0; bar.classList.remove("is-indeterminate"); bar.firstElementChild.style.width = `${(frac * 100).toFixed(1)}%`; bar.setAttribute("aria-valuenow", Math.round(frac * 100)); txt.innerHTML = `Downloading ${MODEL.name}, once; after that it is cached on this device.`; num.textContent = `${mb(p.loaded)} / ${mb(p.total)} MB · ${Math.round(frac * 100)}%`; } function ensureModel() { if (ready) return Promise.resolve(); if (loading) return loading; const t0 = performance.now(); showLoader(null); loading = call("load", { url: MODEL.url, cacheName: MODEL.cache, sizes: MODEL.sizes }, showLoader) .then((s) => { ready = true; $("#loader").classList.add("is-ready"); $("#load-text").innerHTML = `${MODEL.name} ready in ${((performance.now() - t0) / 1000).toFixed(1)} s · ${s.fromCache ? "loaded from this device" : `downloaded ${mb(s.bytes)} MB once, now cached`}, running in this tab`; $("#load-num").textContent = s.threads > 1 ? `${s.threads} threads` : ""; }) .catch((e) => { $("#loader").classList.add("is-error"); $("#load-text").innerHTML = `${MODEL.name} could not be loaded. ${esc(e.message)}. Try reloading, or a recent Chrome, Edge, Firefox or Safari.`; throw e; }) .finally(() => { loading = null; }); return loading; } // ───────────────────────────── results ───────────────────────────── /** The text with each span wrapped in a mark and a label chip. Positions are code points (as in Python). */ function markedHtml(cps, spans) { let html = "", at = 0; for (const s of spans) { const L = LABELS[s.label] || { name: s.label, tone: "pi-who" }; html += esc(cps.slice(at, s.start).join("")); html += `${esc(cps.slice(s.start, s.end).join(""))}${esc(s.label)}`; at = s.end; } return html + esc(cps.slice(at).join("")); } function itemsHtml(spans) { return spans.map((s) => { const L = LABELS[s.label] || { name: s.label, tone: "pi-who" }; return `
  • ${esc(s.label)}${esc(s.text)}
  • `; }).join(""); } let runToken = 0; let lastRedacted = ""; async function find() { const text = $("#text").value; const out = $("#out"); if (!text.trim()) { out.innerHTML = `
    Nothing to check

    Paste some text or click an example.

    `; return; } const token = ++runToken; const go = $("#go"); go.setAttribute("aria-busy", "true"); out.innerHTML = `
    ${ready ? "Looking…" : `Loading ${MODEL.name}…`}
    `; try { await ensureModel(); const r = await call("find", { text }); if (token !== runToken) return; const cps = [...text]; lastRedacted = redact(cps, r.spans); const n = r.spans.length; out.innerHTML = `
    ${MODEL.name} · ${r.tokens} tokens${r.tokens > 254 ? " · read in overlapping windows" : ""}
    ${n ? `Found ${n} item${n > 1 ? "s" : ""}` : "Found nothing"}
    ${markedHtml(cps, r.spans)}
    ${n ? `` : ""}
    Redacted
    ${esc(lastRedacted)}
    found in ${Math.round(r.ms)} ms in your browser
    `; } catch (e) { if (token === runToken) out.innerHTML = `
    Could not check

    ${esc(e.message)}

    `; } finally { if (token === runToken) go.removeAttribute("aria-busy"); } } async function copyRedacted(btn) { let ok = false; try { await navigator.clipboard.writeText(lastRedacted); ok = true; } catch { const ta = Object.assign(document.createElement("textarea"), { value: lastRedacted }); ta.style.position = "fixed"; ta.style.opacity = "0"; document.body.append(ta); ta.select(); try { ok = document.execCommand("copy"); } catch {} ta.remove(); } btn.textContent = ok ? "Copied" : "Select and copy it by hand"; setTimeout(() => { btn.textContent = "Copy"; }, 1800); } // ───────────────────────────── start ───────────────────────────── function initTheme() { const root = document.documentElement; $("#theme").addEventListener("click", () => { const dark = !root.classList.contains("dark"); root.classList.toggle("dark", dark); try { localStorage.setItem("dz-theme", dark ? "dark" : "light"); } catch {} }); matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => { let saved = null; try { saved = localStorage.getItem("dz-theme"); } catch {} if (!saved) root.classList.toggle("dark", e.matches); }); } async function main() { initTheme(); $("#examples").innerHTML = EXAMPLES.map((x, i) => ``).join(""); $("#text").value = EXAMPLES[0].text; $("#examples").addEventListener("click", (e) => { const b = e.target.closest("[data-i]"); if (!b) return; $("#text").value = EXAMPLES[+b.dataset.i].text; find(); }); $("#text").addEventListener("keydown", (e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); find(); } }); $("#form").addEventListener("submit", (e) => { e.preventDefault(); find(); }); $("#out").addEventListener("click", (e) => { const b = e.target.closest("#copy"); if (b) copyRedacted(b); }); $("#forget").addEventListener("click", async () => { const ok = await call("clearCache", { cacheName: MODEL.cache }).catch(() => false); $("#forget").textContent = ok ? "Removed. The next run downloads the model again." : "Nothing cached on this device."; }); const cached = await isCached(FILES.map((f) => MODEL.url + f), MODEL.cache); $("#go").title = cached ? "The model is cached on this device" : `The first run downloads ${mb(MODEL.bytes)} MB once`; } // hook for automated checks window.PII = { find, ensureModel, call, MODEL, EXAMPLES, ready: null }; window.PII.ready = main();