PatchCore CPU: code, 15 models, results
Browse filesFiles changed (7)
- README.md+3-2
- export_onnx.pyAdded+123
- make_readme.py+3-2
- requirements-lock.txt+2
- requirements.txt+2
- web/app.jsAdded+239
- web/index.htmlAdded+90
17 unmodified lines1819202122232476 unmodified lines10110210310410510610717 unmodified lines# PatchCore sur CPU — détection et localisation de défauts industriels (MVTec AD)Projet de vision par ordinateur avancée (3e année cycle ingénieur en informatique).**Démo en ligne :** https://huggingface.co/spaces/salimamri9/patchcore-defect-detectionLe modèle n'apprend que sur des **pièces conformes**. Pour une nouvelle image, il renvoieun **score d'anomalie** (pièce OK / défectueuse) et une **carte d'anomalie** qui localise le défaut.76 unmodified lines| `patchcore/metrics.py` | AUROC image/pixel, AU-PRO, F1 || `run.py` | fit + calibration + évaluation d'une configuration || `threshold_study.py` | comparaison des règles de seuil || `app.py` | démo Gradio || `models/<catégorie>/` | banque mémoire (safetensors fp16) + config (seuils, métriques) || `results/` | métriques et scores par image de chaque expérience || `logs/`, `docs/difficulties.md` | journaux d'exécution, difficultés rencontrées |17 unmodified lines1819202122232476 unmodified lines10110210310410510610710817 unmodified lines# PatchCore sur CPU — détection et localisation de défauts industriels (MVTec AD)Projet de vision par ordinateur avancée (3e année cycle ingénieur en informatique).**Démo en ligne :** https://huggingface.co/spaces/salimamri9/patchcore-defect-detection (inférence dans le navigateur, export ONNX)Le modèle n'apprend que sur des **pièces conformes**. Pour une nouvelle image, il renvoieun **score d'anomalie** (pièce OK / défectueuse) et une **carte d'anomalie** qui localise le défaut.76 unmodified lines| `patchcore/metrics.py` | AUROC image/pixel, AU-PRO, F1 || `run.py` | fit + calibration + évaluation d'une configuration || `threshold_study.py` | comparaison des règles de seuil || `app.py` | démo Gradio (locale) || `export_onnx.py`, `web/` | export ONNX du pipeline complet + démo statique du Space (onnxruntime-web) || `models/<catégorie>/` | banque mémoire (safetensors fp16) + config (seuils, métriques) || `results/` | métriques et scores par image de chaque expérience || `logs/`, `docs/difficulties.md` | journaux d'exécution, difficultés rencontrées |
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123"""Exports the PatchCore pipeline to ONNX for the static (in-browser) Hugging Face Space.
One graph for every category: (image 1x3x224x224, memory bank Nx1024) -> (anomaly map 224x224, image score) backbone WRN-50-2 -> layer2/layer3 -> avg-pool 3x3 -> concat -> 1536->1024 pooling -> k-NN -> bilinear -> blurThe adaptive 1-D average pooling (1536 -> 1024) is written as a constant matrix product (exact, export-friendly).
Output folder web/ : patchcore_wrn50.onnx, banks/<cat>.bin (fp16, row-major), banks/<cat>.json, examples/Checks the ONNX output against the PyTorch model on the example images."""import jsonimport shutilfrom pathlib import Path
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom PIL import Image
from patchcore.data import CATEGORIES, image_transformfrom patchcore.model import FeatureExtractor, PatchCore
OUT = Path("web")torch.set_num_threads(12)
def pool_matrix(c_in: int, c_out: int) -> torch.Tensor: """Matrix M (c_in, c_out) such that x @ M == adaptive_avg_pool1d(x, c_out).""" eye = torch.eye(c_in).unsqueeze(1) # (c_in, 1, c_in) return F.adaptive_avg_pool1d(eye, c_out).squeeze(1) # row i = pooling of basis vector i
def blur_kernel(sigma: float) -> torch.Tensor: r = int(4 * sigma + 0.5) k = torch.arange(-r, r + 1, dtype=torch.float32) k = torch.exp(-(k ** 2) / (2 * sigma ** 2)) return k / k.sum()
class ExportedPatchCore(nn.Module): def __init__(self, ext: FeatureExtractor, c_in=1536, d=1024, sigma=4.0, size=224): super().__init__() self.ext = ext self.register_buffer("P", pool_matrix(c_in, d)) k = blur_kernel(sigma) self.r = (len(k) - 1) // 2 self.register_buffer("kx", k.view(1, 1, 1, -1)) self.register_buffer("ky", k.view(1, 1, -1, 1)) self.size = size
def forward(self, x, bank): x = self.ext.layer1(self.ext.stem(x)) f2 = self.ext.layer2(x) f3 = self.ext.layer3(f2) f2 = F.avg_pool2d(f2, 3, 1, 1) f3 = F.avg_pool2d(f3, 3, 1, 1) f3 = F.interpolate(f3, size=(28, 28), mode="bilinear", align_corners=False) f = torch.cat([f2, f3], 1) # 1 x 1536 x 28 x 28 f = f.permute(0, 2, 3, 1).reshape(784, 1536) @ self.P # 784 x 1024 d2 = (f * f).sum(1, keepdim=True) + (bank * bank).sum(1)[None] - 2.0 * (f @ bank.T) s = d2.min(1).values.clamp_min(0).sqrt().reshape(1, 1, 28, 28) score = s.max() m = F.interpolate(s, size=(self.size, self.size), mode="bilinear", align_corners=False) m = F.conv2d(F.pad(m, (self.r, self.r, 0, 0), mode="reflect"), self.kx) m = F.conv2d(F.pad(m, (0, 0, self.r, self.r), mode="reflect"), self.ky) return m[0, 0], score
def main(): OUT.mkdir(exist_ok=True) (OUT / "banks").mkdir(exist_ok=True) ext = FeatureExtractor("wide_resnet50_2") net = ExportedPatchCore(ext).eval() onnx_path = OUT / "patchcore_wrn50.onnx" torch.onnx.export( net, (torch.randn(1, 3, 224, 224), torch.randn(1500, 1024)), str(onnx_path), input_names=["image", "bank"], output_names=["anomaly_map", "score"], dynamic_axes={"bank": {0: "n"}}, opset_version=17, dynamo=False) # keep everything in one file (no external .data) so the browser fetches a single URL import onnx mdl = onnx.load(str(onnx_path)) onnx.save(mdl, str(onnx_path), save_as_external_data=False) for extra in OUT.glob("*.onnx.data"): extra.unlink() print("onnx:", onnx_path, onnx_path.stat().st_size // 2**20, "MB")
index = [] for cat in CATEGORIES: m = PatchCore.load(f"models/{cat}", extractor=ext) m.bank.half().numpy().tofile(OUT / "banks" / f"{cat}.bin") met = m.config.get("metrics", {}) meta = { "category": cat, "n": int(m.bank.shape[0]), "d": int(m.bank.shape[1]), "image_threshold": m.image_threshold, "pixel_threshold": m.pixel_threshold, "resize": m.config.get("resize", 256), "crop": m.config.get("crop", 224), "image_auroc": met.get("image_auroc"), "pixel_auroc": met.get("pixel_auroc"), } (OUT / "banks" / f"{cat}.json").write_text(json.dumps(meta, indent=1)) index.append(meta)
shutil.copytree("examples", OUT / "examples", dirs_exist_ok=True) ex = [] for p in sorted((OUT / "examples").glob("*.png")): cat = next(c for c in sorted(CATEGORIES, key=len, reverse=True) if p.stem.startswith(c)) ex.append({"file": f"examples/{p.name}", "category": cat, "label": p.stem[len(cat) + 1:]}) (OUT / "index.json").write_text(json.dumps({"categories": CATEGORIES, "examples": ex}, indent=1))
# ---- check ONNX == PyTorch on every example import onnxruntime as ort sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"]) for e in ex: m = PatchCore.load(f"models/{e['category']}", extractor=ext) x = image_transform(m.config.get("resize", 256), m.config.get("crop", 224))( Image.open(OUT / e["file"]).convert("RGB"))[None] s_t, m_t = m.predict(x) bank = np.fromfile(OUT / "banks" / f"{e['category']}.bin", dtype=np.float16).reshape(-1, 1024).astype(np.float32) m_o, s_o = sess.run(None, {"image": x.numpy(), "bank": bank}) print(f"{e['file']:40s} torch {s_t.item():.4f} onnx {float(s_o):.4f} " f"max|map diff| {np.abs(m_o - m_t[0].numpy()).max():.2e}")
if __name__ == "__main__": main()41 unmodified lines4243444546474862 unmodified lines11111211311411511611741 unmodified lines# PatchCore sur CPU — détection et localisation de défauts industriels (MVTec AD)Projet de vision par ordinateur avancée (3e année cycle ingénieur en informatique).**Démo en ligne :** https://huggingface.co/spaces/{SPACE}Le modèle n'apprend que sur des **pièces conformes**. Pour une nouvelle image, il renvoieun **score d'anomalie** (pièce OK / défectueuse) et une **carte d'anomalie** qui localise le défaut.62 unmodified lines| `patchcore/metrics.py` | AUROC image/pixel, AU-PRO, F1 || `run.py` | fit + calibration + évaluation d'une configuration || `threshold_study.py` | comparaison des règles de seuil || `app.py` | démo Gradio || `models/<catégorie>/` | banque mémoire (safetensors fp16) + config (seuils, métriques) || `results/` | métriques et scores par image de chaque expérience || `logs/`, `docs/difficulties.md` | journaux d'exécution, difficultés rencontrées |41 unmodified lines4243444546474862 unmodified lines11111211311411511611711841 unmodified lines# PatchCore sur CPU — détection et localisation de défauts industriels (MVTec AD)Projet de vision par ordinateur avancée (3e année cycle ingénieur en informatique).**Démo en ligne :** https://huggingface.co/spaces/{SPACE} (inférence dans le navigateur, export ONNX)Le modèle n'apprend que sur des **pièces conformes**. Pour une nouvelle image, il renvoieun **score d'anomalie** (pièce OK / défectueuse) et une **carte d'anomalie** qui localise le défaut.62 unmodified lines| `patchcore/metrics.py` | AUROC image/pixel, AU-PRO, F1 || `run.py` | fit + calibration + évaluation d'une configuration || `threshold_study.py` | comparaison des règles de seuil || `app.py` | démo Gradio (locale) || `export_onnx.py`, `web/` | export ONNX du pipeline complet + démo statique du Space (onnxruntime-web) || `models/<catégorie>/` | banque mémoire (safetensors fp16) + config (seuils, métriques) || `results/` | métriques et scores par image de chaque expérience || `logs/`, `docs/difficulties.md` | journaux d'exécution, difficultés rencontrées |
9 unmodified lines1011129 unmodified linesscipy==1.18.1torch==2.15.0+cputorchvision==0.29.2+cpu9 unmodified lines10111213149 unmodified linesscipy==1.18.1torch==2.15.0+cputorchvision==0.29.2+cpuonnx==1.23.2onnxruntime==1.32.0
10 unmodified lines11121310 unmodified lineshuggingface_hub>=0.25gradio>=5.0# exact versions used for the reported results: see requirements-lock.txt10 unmodified lines111213141510 unmodified lineshuggingface_hub>=0.25gradio>=5.0# exact versions used for the reported results: see requirements-lock.txtonnxonnxruntime
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239// 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 nullasync 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 = () => { window.scrollTo({ top: 0, behavior: "smooth" }); setImage(e.file, 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); });123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990<!DOCTYPE html><html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>PatchCore – détection de défauts industriels</title><style> :root { --navy:#0B3C49; --teal:#0F7B73; --orange:#E8A33D; --red:#C8501E; --card:#E8F0F2; --ink:#1c2b30; } * { box-sizing: border-box; } body { margin:0; font-family: Calibri, "Segoe UI", system-ui, sans-serif; color:var(--ink); background:#f5f8f9; } header { background:var(--navy); color:white; padding:22px 32px 18px; } header h1 { margin:0 0 6px; font-family: Cambria, Georgia, serif; font-size:1.7em; font-weight:700; } header p { margin:0; opacity:.88; max-width:980px; line-height:1.45; } header a { color:var(--orange); } main { display:grid; grid-template-columns: minmax(300px, 1fr) 2fr; gap:24px; padding:24px 32px; max-width:1400px; } @media (max-width: 900px) { main { grid-template-columns: 1fr; padding:16px; } } .panel { background:white; border-radius:12px; padding:18px; box-shadow:0 1px 3px rgba(0,0,0,.08); } h2 { font-family: Cambria, Georgia, serif; color:var(--navy); font-size:1.1em; margin:0 0 10px; } #drop { border:2px dashed #9bb7bd; border-radius:10px; min-height:230px; display:flex; align-items:center; justify-content:center; text-align:center; cursor:pointer; color:#5b7378; background:var(--card); overflow:hidden; } #drop.over { border-color:var(--teal); background:#d6ebe8; } #drop img { max-width:100%; max-height:300px; display:block; } label { display:block; font-weight:600; margin:14px 0 6px; } select { width:100%; padding:9px; font-size:1em; border-radius:8px; border:1px solid #b9cbd0; } button#run { margin-top:14px; width:100%; padding:12px; font-size:1.1em; font-weight:700; border:0; border-radius:8px; background:var(--orange); color:var(--navy); cursor:pointer; } button#run:disabled { opacity:.5; cursor:wait; } #examples { display:grid; grid-template-columns: repeat(4, 1fr); gap:8px; } #examples figure { margin:0; cursor:pointer; border-radius:8px; overflow:hidden; border:2px solid transparent; background:var(--card); } #examples figure:hover { border-color:var(--teal); } #examples img { width:100%; display:block; aspect-ratio:1; object-fit:cover; } #examples figcaption { font-size:.72em; padding:3px 5px; color:#36505a; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } #status { font-size:.9em; color:#4d6a70; margin-top:10px; min-height:1.3em; } .bar { height:6px; background:#dbe6e8; border-radius:3px; overflow:hidden; margin-top:6px; display:none; } .bar > div { height:100%; width:0; background:var(--teal); transition:width .2s; } #verdict { border-radius:10px; padding:14px 18px; font-size:1.5em; font-weight:700; text-align:center; color:white; background:#9fb3b8; } #verdict small { font-weight:400; font-size:.65em; } .outs { display:grid; grid-template-columns:1fr 1fr; gap:16px; margin-top:16px; } .outs figure { margin:0; } .outs figcaption { font-weight:600; color:var(--navy); margin-bottom:6px; } .outs canvas { width:100%; aspect-ratio:1; border-radius:8px; background:var(--card); image-rendering:auto; } #info { margin-top:14px; line-height:1.6; } .scale { display:flex; align-items:center; gap:8px; font-size:.8em; color:#4d6a70; margin-top:4px; } .scale span.g { flex:1; height:10px; border-radius:5px; background:linear-gradient(90deg,#00007f,#0000ff,#007fff,#00ffff,#7fff7f,#ffff00,#ff7f00,#ff0000,#7f0000); } footer { padding:0 32px 28px; font-size:.85em; color:#5b7378; max-width:1400px; }</style></head><body><header> <h1>Détection et localisation de défauts industriels — PatchCore</h1> <p>Le modèle n'a vu <b>que des pièces conformes</b> pendant l'apprentissage. Chaque patch de l'image est comparé à une banque mémoire de patchs normaux ; les patchs trop éloignés sont signalés comme anomalies. L'inférence tourne <b>entièrement dans votre navigateur</b> (ONNX Runtime Web, aucun serveur). Code, modèles et résultats : <a id="repo" href="https://huggingface.co/salimamri9/patchcore-mvtec-cpu" target="_blank">salimamri9/patchcore-mvtec-cpu</a></p></header><main> <section class="panel"> <h2>1. Image d'entrée</h2> <div id="drop" tabindex="0">Déposez une image ici<br>ou cliquez pour en choisir une</div> <input type="file" id="file" accept="image/*" hidden> <label for="cat">2. Catégorie (modèle)</label> <select id="cat"></select> <button id="run" disabled>Analyser</button> <div id="status">Chargement…</div> <div class="bar" id="bar"><div></div></div> <h2 style="margin-top:20px">Exemples (MVTec AD, jeu de test)</h2> <div id="examples"></div> </section> <section class="panel"> <div id="verdict">En attente d'une image</div> <div class="outs"> <figure><figcaption>Carte d'anomalie</figcaption><canvas id="heat" width="224" height="224"></canvas> <div class="scale">0.5 × seuil <span class="g"></span> 1.5 × seuil</div></figure> <figure><figcaption>Défaut segmenté</figcaption><canvas id="seg" width="224" height="224"></canvas></figure> </div> <div id="info"></div> </section></main><footer> Données : MVTec AD (Bergmann et al.), licence CC BY-NC-SA 4.0. Méthode : Roth et al., <i>Towards Total Recall in Industrial Anomaly Detection</i>, CVPR 2022 — réimplémentation, calibration du seuil et export ONNX par le groupe. Extracteur Wide-ResNet-50-2 (ImageNet), coreset 1 %. Premier chargement : ~100 Mo (mis en cache ensuite).</footer>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.min.js"></script><script src="app.js"></script></body></html>README.md+3-2
export_onnx.pyAdded+123
make_readme.py+3-2
requirements-lock.txt+2
requirements.txt+2
web/app.jsAdded+239
web/index.htmlAdded+90