Spaces:
Running
Running
File size: 3,076 Bytes
d0a4896 | 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 | // decima-pii worker: downloads the model once (Cache API, via decima.js), then tags text off the main thread.
import * as ort from "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.30.0/dist/ort.wasm.min.mjs";
import { Tokenizer } from "https://cdn.jsdelivr.net/npm/@huggingface/tokenizers@0.2.0/dist/tokenizers.min.mjs";
import { fetchFiles, clearCache } from "./decima.js";
import { findPII, onnxTagger } from "./pii-core.js";
ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.30.0/dist/";
ort.env.logLevel = "error";
export const FILES = ["onnx/model_quantized.onnx", "tokenizer.json", "pii_meta.json"];
let m = null; // {tok, labels, tag}
let chain = Promise.resolve(); // one call at a time: an ORT session runs one call at a time
async function load({ url, cacheName, sizes }, progress) {
if (m) return { fromCache: true, bytes: 0, threads: m.threads };
const t0 = performance.now();
let fromCache = true;
const bufs = await fetchFiles(FILES.map((f) => ({ url: url + f, size: sizes[f] })),
(p) => { fromCache = p.cached; progress(p); }, cacheName);
// The Hub counts a model download when the repo's config.json is requested; once per real download.
const root = url.match(/^(.*\/resolve\/[^/]+\/)/)?.[1];
if (!fromCache && root) fetch(root + "config.json", { method: "HEAD", mode: "cors" }).catch(() => {});
progress({ preparing: true });
const dec = new TextDecoder();
const tj = JSON.parse(dec.decode(bufs[1]));
delete tj.truncation; // the file carries a 256-token cut; the text is tagged in windows instead
delete tj.padding;
const tok = new Tokenizer(tj, {});
const labels = JSON.parse(dec.decode(bufs[2])).labels;
// Threads need cross-origin isolation (COOP/COEP), which static hosting usually lacks: then one thread.
const threads = self.crossOriginIsolated ? Math.min(4, navigator.hardwareConcurrency || 1) : 1;
ort.env.wasm.numThreads = threads;
const sess = await ort.InferenceSession.create(new Uint8Array(bufs[0]), { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
const bos = tok.token_to_id("<bos>"), eos = tok.token_to_id("<eos>");
m = { tok, labels, tag: onnxTagger(ort, sess, bos, eos), threads };
return { fromCache, bytes: bufs.reduce((a, b) => a + b.byteLength, 0), threads, ms: performance.now() - t0 };
}
async function handle({ id, op, ...a }) {
const reply = (msg) => postMessage({ id, ...msg });
try {
if (op === "load") reply({ result: await load(a, (p) => reply({ progress: p })) });
else if (op === "find") {
const t0 = performance.now();
const { spans, tokens } = await findPII(m.tok, m.labels, m.tag, a.text);
reply({ result: { spans, tokens, ms: performance.now() - t0 } });
} else if (op === "clearCache") reply({ result: await clearCache(a.cacheName) });
else throw new Error(`unknown op ${op}`);
} catch (e) {
reply({ error: String((e && e.message) || e) });
}
}
onmessage = (e) => { chain = chain.then(() => handle(e.data)); };
|