amyrmahdy's picture
decima-pii page: v0.2.1 (decoder v2.1 default: numbers after phone words such as جوالي; model pinned to resolve/v0.2.1)
3bbcdfe verified
Raw History Blame Contribute Delete
10.6 kB
// 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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;" }[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 ? `<b>Loading ${MODEL.name}</b>` : p.cached && !p.preparing
? `<b>Loading ${MODEL.name} from this device</b>, saved on an earlier visit.` : `<b>Preparing ${MODEL.name}</b> 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 = `<b>Downloading ${MODEL.name}</b>, 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 = `<b>${MODEL.name} ready</b> 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 = `<b>${MODEL.name} could not be loaded.</b> ${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 += `<mark class="pi-span ${L.tone}" title="${esc(L.name)}"><span class="pi-val" dir="auto">${esc(cps.slice(s.start, s.end).join(""))}</span><span class="pi-chip" dir="ltr">${esc(s.label)}</span></mark>`;
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 `<li><span class="pi-chip ${L.tone}" dir="ltr">${esc(s.label)}</span><span class="pi-item" dir="auto">${esc(s.text)}</span></li>`;
}).join("");
}
let runToken = 0;
let lastRedacted = "";
async function find() {
const text = $("#text").value;
const out = $("#out");
if (!text.trim()) { out.innerHTML = `<div class="dz-card dz-result dz-msg"><div class="dz-eyebrow">Nothing to check</div><p>Paste some text or click an example.</p></div>`; return; }
const token = ++runToken;
const go = $("#go");
go.setAttribute("aria-busy", "true");
out.innerHTML = `<div class="dz-card dz-result dz-msg"><span class="dz-busy">${ready ? "Looking…" : `Loading ${MODEL.name}…`}</span></div>`;
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 = `
<div class="dz-card dz-result pi-result">
<div class="dz-eyebrow">${MODEL.name} · ${r.tokens} tokens${r.tokens > 254 ? " · read in overlapping windows" : ""}</div>
<div class="pi-count">${n ? `Found <b>${n}</b> item${n > 1 ? "s" : ""}` : "Found nothing"}</div>
<div class="pi-text" dir="auto">${markedHtml(cps, r.spans)}</div>
${n ? `<ul class="pi-items">${itemsHtml(r.spans)}</ul>` : ""}
<div class="pi-red-head"><span class="dz-eyebrow">Redacted</span><button class="pi-copy" id="copy" type="button">Copy</button></div>
<div class="pi-text pi-redacted" id="redacted" dir="auto">${esc(lastRedacted)}</div>
<div class="dz-meta pi-meta"><span class="dz-time">found in <b>${Math.round(r.ms)} ms</b> in your browser</span></div>
</div>`;
} catch (e) {
if (token === runToken) out.innerHTML = `<div class="dz-card dz-result dz-msg"><div class="dz-eyebrow">Could not check</div><p>${esc(e.message)}</p></div>`;
} 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) => `<button type="button" class="gd-ex" data-i="${i}">${esc(x.tag)}</button>`).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();