salimamri9's picture
web demo: load examples as blobs
26b4192 verified
Raw History Blame Contribute Delete
10.9 kB
// PatchCore in the browser: one ONNX graph (WRN-50-2 + k-NN + bilinear + blur) + per-category memory banks.
const MODEL_URL = "patchcore_wrn50.onnx";
const CACHE = "patchcore-v1";
const MEAN = [0.485, 0.456, 0.406], STD = [0.229, 0.224, 0.225];
const $ = (id) => document.getElementById(id);
ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/";
ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(8, navigator.hardwareConcurrency || 4) : 1;
let session = null, current = null, index = null;
const banks = {};
function status(msg, frac) {
$("status").textContent = msg;
$("bar").style.display = frac == null ? "none" : "block";
if (frac != null) $("bar").firstElementChild.style.width = `${Math.round(frac * 100)}%`;
}
async function fetchCached(url, onProgress) {
let cache = null;
try { cache = await caches.open(CACHE); const hit = await cache.match(url); if (hit) return await hit.arrayBuffer(); } catch (e) {}
const res = await fetch(url);
if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`);
const total = +res.headers.get("content-length") || 0;
const reader = res.body.getReader();
const chunks = []; let got = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value); got += value.length;
if (onProgress && total) onProgress(got / total);
}
const buf = new Uint8Array(got); let o = 0;
for (const c of chunks) { buf.set(c, o); o += c.length; }
try { if (cache) await cache.put(url, new Response(buf)); } catch (e) {}
return buf.buffer;
}
function halfToFloat(u16) {
const out = new Float32Array(u16.length);
for (let i = 0; i < u16.length; i++) {
const h = u16[i], s = h & 0x8000 ? -1 : 1, e = (h >> 10) & 0x1f, f = h & 0x3ff;
out[i] = e === 0 ? s * f * 2 ** -24 : e === 31 ? (f ? NaN : s * Infinity) : s * (1 + f / 1024) * 2 ** (e - 15);
}
return out;
}
async function getBank(cat) {
if (!banks[cat]) {
const meta = await (await fetch(`banks/${cat}.json`)).json();
const raw = await fetchCached(`banks/${cat}.bin`);
banks[cat] = { meta, tensor: new ort.Tensor("float32", halfToFloat(new Uint16Array(raw)), [meta.n, meta.d]) };
}
return banks[cat];
}
// PIL Image.resize(BILINEAR) with antialiasing (Resample.c): separable triangle filter whose support grows
// with the downscaling factor; horizontal pass then vertical pass, rounded to uint8 in between.
function coeffs(inSize, outSize) {
const scale = inSize / outSize, fs = Math.max(scale, 1), support = fs, out = [];
for (let i = 0; i < outSize; i++) {
const center = (i + 0.5) * scale;
const xmin = Math.max(Math.trunc(center - support + 0.5), 0);
const xmax = Math.min(Math.trunc(center + support + 0.5), inSize);
const w = [];
let sum = 0;
for (let x = xmin; x < xmax; x++) {
const t = Math.abs((x - center + 0.5) / fs);
const v = t < 1 ? 1 - t : 0;
w.push(v); sum += v;
}
out.push({ xmin, w: w.map((v) => (sum ? v / sum : 0)) });
}
return out;
}
function resizePIL(src, w, h, ow, oh) {
const clip = (v) => (v < 0 ? 0 : v > 255 ? 255 : Math.round(v));
let tmp = src, tw = w;
if (ow !== w) {
const cx = coeffs(w, ow);
tmp = new Uint8ClampedArray(ow * h * 4); tw = ow;
for (let y = 0; y < h; y++) for (let x = 0; x < ow; x++) {
const { xmin, w: k } = cx[x];
for (let c = 0; c < 3; c++) {
let s = 0;
for (let j = 0; j < k.length; j++) s += k[j] * src[4 * (y * w + xmin + j) + c];
tmp[4 * (y * ow + x) + c] = clip(s);
}
tmp[4 * (y * ow + x) + 3] = 255;
}
}
if (oh === h) return tmp;
const cy = coeffs(h, oh), out = new Uint8ClampedArray(tw * oh * 4);
for (let y = 0; y < oh; y++) {
const { xmin, w: k } = cy[y];
for (let x = 0; x < tw; x++) {
for (let c = 0; c < 3; c++) {
let s = 0;
for (let j = 0; j < k.length; j++) s += k[j] * tmp[4 * ((xmin + j) * tw + x) + c];
out[4 * (y * tw + x) + c] = clip(s);
}
out[4 * (y * tw + x) + 3] = 255;
}
}
return out;
}
// torchvision: Resize(256) (shorter side) + CenterCrop(224), or Resize((224,224)) when crop is null
async function preprocess(img, meta) {
const w = img.naturalWidth || img.width, h = img.naturalHeight || img.height;
let rw, rh;
if (meta.crop == null) { rw = rh = meta.resize; }
else if (w <= h) { rw = meta.resize; rh = Math.floor(meta.resize * h / w); }
else { rh = meta.resize; rw = Math.floor(meta.resize * w / h); }
const full = new OffscreenCanvas(w, h).getContext("2d");
full.drawImage(img, 0, 0);
const resized = resizePIL(full.getImageData(0, 0, w, h).data, w, h, rw, rh);
const S = meta.crop ?? meta.resize;
const top = Math.round((rh - S) / 2), left = Math.round((rw - S) / 2);
const px = new Uint8ClampedArray(S * S * 4);
for (let y = 0; y < S; y++)
px.set(resized.subarray(4 * ((y + top) * rw + left), 4 * ((y + top) * rw + left + S)), 4 * y * S);
const x = new Float32Array(3 * S * S);
for (let i = 0; i < S * S; i++)
for (let c = 0; c < 3; c++) x[c * S * S + i] = (px[4 * i + c] / 255 - MEAN[c]) / STD[c];
return { tensor: new ort.Tensor("float32", x, [1, 3, S, S]), rgba: px, S };
}
const jet = (v) => { // OpenCV COLORMAP_JET
const c = (t) => Math.max(0, Math.min(1, 1.5 - Math.abs(4 * v - t)));
return [c(3) * 255, c(2) * 255, c(1) * 255];
};
function render(rgba, map, S, pthr, bad) {
const heat = new ImageData(S, S), seg = new ImageData(S, S);
const mask = new Uint8Array(S * S);
for (let i = 0; i < S * S; i++) {
const v = Math.max(0, Math.min(1, (map[i] - 0.5 * pthr) / pthr));
const [r, g, b] = jet(Math.floor(v * 255) / 255);
heat.data[4 * i] = 0.45 * r + 0.55 * rgba[4 * i];
heat.data[4 * i + 1] = 0.45 * g + 0.55 * rgba[4 * i + 1];
heat.data[4 * i + 2] = 0.45 * b + 0.55 * rgba[4 * i + 2];
heat.data[4 * i + 3] = 255;
for (let c = 0; c < 4; c++) seg.data[4 * i + c] = rgba[4 * i + c];
mask[i] = map[i] >= pthr ? 1 : 0;
}
let area = 0;
for (let i = 0; i < S * S; i++) area += mask[i];
if (bad) { // contour = mask pixels with a 4-neighbour outside the mask, drawn 2 px thick
const edge = new Uint8Array(S * S);
for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) {
const i = y * S + x;
if (!mask[i]) continue;
if (x === 0 || y === 0 || x === S - 1 || y === S - 1 || !mask[i - 1] || !mask[i + 1] || !mask[i - S] || !mask[i + S]) edge[i] = 1;
}
for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) {
const i = y * S + x;
if (edge[i] || (x > 0 && edge[i - 1]) || (y > 0 && edge[i - S])) {
seg.data[4 * i] = 255; seg.data[4 * i + 1] = 40; seg.data[4 * i + 2] = 40;
}
}
}
for (const [id, im] of [["heat", heat], ["seg", seg]]) {
const c = $(id); c.width = S; c.height = S; c.getContext("2d").putImageData(im, 0, 0);
}
return area / (S * S);
}
async function analyse() {
if (!current) { status("Chargez une image ou choisissez un exemple."); return; }
$("run").disabled = true;
try {
const cat = $("cat").value;
status(`Chargement de la banque mémoire « ${cat} »…`);
const { meta, tensor: bank } = await getBank(cat);
const { tensor, rgba, S } = await preprocess(current, meta);
status("Analyse en cours…");
await new Promise((r) => setTimeout(r, 20));
const t0 = performance.now();
const out = await session.run({ image: tensor, bank });
const dt = performance.now() - t0;
const score = out.score.data[0], map = out.anomaly_map.data;
const ratio = score / meta.image_threshold, bad = ratio >= 1;
const area = render(rgba, map, S, meta.pixel_threshold, bad);
const v = $("verdict");
v.style.background = bad ? "var(--red)" : "var(--teal)";
v.innerHTML = `${bad ? "DÉFAUT DÉTECTÉ" : "PIÈCE CONFORME"} <small>(score / seuil = ${ratio.toFixed(2)})</small>`;
$("info").innerHTML =
`<b>Score d'anomalie</b> : ${score.toFixed(3)} (seuil calibré ${meta.image_threshold.toFixed(3)} → ratio <b>${ratio.toFixed(2)}</b>)<br>` +
`<b>Surface anormale</b> : ${(100 * area).toFixed(2)} % de l'image<br>` +
`<b>Temps d'inférence (navigateur, ${ort.env.wasm.numThreads} thread${ort.env.wasm.numThreads > 1 ? "s" : ""})</b> : ${dt.toFixed(0)} ms<br>` +
`Modèle <code>${cat}</code> : banque mémoire de ${meta.n.toLocaleString("fr-FR")} patchs × ${meta.d}` +
(meta.image_auroc != null ? ` — AUROC image ${meta.image_auroc.toFixed(3)}, AUROC pixel ${meta.pixel_auroc.toFixed(3)} sur le test MVTec AD` : "") +
(meta.crop == null ? "<br><i>Prétraitement sans recadrage central (défauts en bordure).</i>" : "");
status("Terminé.");
} catch (e) {
console.error(e); status("Erreur : " + e.message);
} finally { $("run").disabled = !session; }
}
function setImage(src, cat) {
const img = new Image();
img.onload = () => {
current = img;
$("drop").innerHTML = ""; $("drop").appendChild(img);
if (cat) $("cat").value = cat;
if (cat && session) analyse();
};
img.src = src;
}
async function init() {
index = await (await fetch("index.json")).json();
for (const c of index.categories) $("cat").add(new Option(c, c));
for (const e of index.examples) {
const f = document.createElement("figure");
f.innerHTML = `<img src="${e.file}" alt="${e.category} ${e.label}" loading="lazy"><figcaption>${e.category} · ${e.label}</figcaption>`;
f.onclick = async () => { // fetch -> blob URL: LFS files are served from a CDN origin (would taint the canvas)
window.scrollTo({ top: 0, behavior: "smooth" });
const blob = await (await fetch(e.file)).blob();
setImage(URL.createObjectURL(blob), e.category);
};
$("examples").appendChild(f);
}
const drop = $("drop"), file = $("file");
drop.onclick = () => file.click();
file.onchange = () => file.files[0] && setImage(URL.createObjectURL(file.files[0]));
drop.ondragover = (ev) => { ev.preventDefault(); drop.classList.add("over"); };
drop.ondragleave = () => drop.classList.remove("over");
drop.ondrop = (ev) => { ev.preventDefault(); drop.classList.remove("over"); if (ev.dataTransfer.files[0]) setImage(URL.createObjectURL(ev.dataTransfer.files[0])); };
$("run").onclick = analyse;
status("Téléchargement du modèle Wide-ResNet-50-2 (~100 Mo, une seule fois)…", 0);
const buf = await fetchCached(MODEL_URL, (p) => status(`Téléchargement du modèle (~100 Mo, une seule fois)… ${Math.round(p * 100)} %`, p));
status("Initialisation d'ONNX Runtime…");
session = await ort.InferenceSession.create(buf, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
$("run").disabled = false;
status("Modèle prêt. Choisissez un exemple ou chargez une image.");
if (current) analyse();
}
init().catch((e) => { console.error(e); status("Erreur de chargement : " + e.message); });