File size: 4,605 Bytes
142281f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
"""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"<div style='background:{color};color:white;border-radius:10px;padding:14px 18px;"
             f"font-size:1.5em;font-weight:700;text-align:center'>{verdict} "
             f"<span style='font-weight:400;font-size:0.7em'>(score / seuil = {ratio:.2f})</span></div>")
    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()