"""Gradio demo: industrial defect detection & localisation with PatchCore (CPU).""" from __future__ import annotations import json import os import time from pathlib import Path import gradio as gr import numpy as np import torch from patchcore.data import CATEGORIES, image_transform, load_rgb, to_display from patchcore.model import FeatureExtractor, PatchCore from patchcore.viz import draw_contours, heat_overlay torch.set_num_threads(max(1, os.cpu_count() or 1)) MODEL_REPO = os.environ.get("MODEL_REPO", "") ROOT = Path(__file__).parent def models_dir() -> Path: local = ROOT / "models" if local.exists() and any(local.iterdir()): return local from huggingface_hub import snapshot_download return Path(snapshot_download(MODEL_REPO, allow_patterns=["models/*"])) / "models" MODELS_DIR = models_dir() EXTRACTOR = FeatureExtractor("wide_resnet50_2") _cache: dict[str, PatchCore] = {} def get_model(cat: str) -> PatchCore: if cat not in _cache: _cache[cat] = PatchCore.load(MODELS_DIR / cat, extractor=EXTRACTOR) return _cache[cat] def analyse(image, category): if image is None: raise gr.Error("Chargez une image ou choisissez un exemple.") m = get_model(category) tf = image_transform(m.config.get("resize", 256), m.config.get("crop", 224)) x = tf(image.convert("RGB")).unsqueeze(0) t0 = time.time() score, amap = m.predict(x) dt = (time.time() - t0) * 1000 score, amap = float(score[0]), amap[0].numpy() img = to_display(x[0]) ratio = score / m.image_threshold mask = amap >= m.pixel_threshold heat = heat_overlay(img, amap, m.pixel_threshold) seg = draw_contours(img, mask) if ratio >= 1 else img bad = ratio >= 1 color = "#C8501E" if bad else "#0F7B73" verdict = "DÉFAUT DÉTECTÉ" if bad else "PIÈCE CONFORME" label = (f"
{verdict} " f"(score / seuil = {ratio:.2f})
") met = m.config.get("metrics", {}) info = ( f"**Score d'anomalie** : {score:.3f} (seuil calibré {m.image_threshold:.3f} → ratio **{ratio:.2f}**) \n" f"**Surface anormale** : {100 * mask.mean():.2f} % de l'image \n" f"**Temps d'inférence (CPU)** : {dt:.0f} ms \n" f"Modèle `{category}` : banque mémoire de {m.bank.shape[0]:,} patchs × {m.bank.shape[1]} — " f"AUROC image {met.get('image_auroc', float('nan')):.3f}, " f"AUROC pixel {met.get('pixel_auroc', float('nan')):.3f} sur le test MVTec AD" ) return label, heat, seg, info def examples(): ex = [] d = ROOT / "examples" if d.exists(): for p in sorted(d.glob("*.png")): cat = next((c for c in sorted(CATEGORIES, key=len, reverse=True) if p.stem.startswith(c)), None) if cat: ex.append([str(p), cat]) return ex with gr.Blocks(title="PatchCore – détection de défauts industriels") as demo: gr.Markdown( "# Détection et localisation de défauts industriels — PatchCore (CPU)\n" "Le modèle n'a vu **que des pièces conformes** 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.\n\n" "Choisissez la catégorie de l'objet, puis chargez une image (ou cliquez sur un exemple)." ) with gr.Row(): with gr.Column(scale=1): inp = gr.Image(type="pil", label="Image d'entrée") cat = gr.Dropdown(CATEGORIES, value="bottle", label="Catégorie (modèle)") btn = gr.Button("Analyser", variant="primary") ex = examples() if ex: gr.Examples(ex, inputs=[inp, cat], examples_per_page=6, label="Exemples (MVTec AD, jeu de test)") with gr.Column(scale=2): out_label = gr.HTML() with gr.Row(): out_heat = gr.Image(label="Carte d'anomalie") out_seg = gr.Image(label="Défaut segmenté") out_info = gr.Markdown() btn.click(analyse, [inp, cat], [out_label, out_heat, out_seg, out_info]) gr.Markdown( "Données : MVTec AD (CC BY-NC-SA 4.0). Méthode : Roth et al., *Towards Total Recall in " "Industrial Anomaly Detection*, CVPR 2022 — réimplémentation et calibration du seuil par le groupe." ) if __name__ == "__main__": demo.launch()