The huggingface/transformers provides DINOv2
Browse files
app.py
CHANGED
|
@@ -1,32 +1,29 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
import torch
|
| 3 |
-
from
|
| 4 |
-
from patchcore.datasets import MVTecDataset
|
| 5 |
from PIL import Image
|
| 6 |
-
import
|
| 7 |
|
| 8 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 9 |
|
| 10 |
-
# Load
|
| 11 |
-
|
| 12 |
-
model =
|
| 13 |
-
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
return result
|
| 29 |
|
| 30 |
gr.Interface(fn=detect_anomaly,
|
| 31 |
inputs=gr.Image(),
|
| 32 |
-
outputs="text").launch()
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
+
from transformers import AutoModel, AutoImageProcessor
|
|
|
|
| 3 |
from PIL import Image
|
| 4 |
+
import gradio as gr
|
| 5 |
|
| 6 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 7 |
|
| 8 |
+
# Load DINOv2 model
|
| 9 |
+
model_name = "facebook/dinov2-base"
|
| 10 |
+
model = AutoModel.from_pretrained(model_name).to(device)
|
| 11 |
+
processor = AutoImageProcessor.from_pretrained(model_name)
|
| 12 |
|
| 13 |
+
# Embed a normal sample (you can do this during inference without storing)
|
| 14 |
+
# You can even hardcode embeddings later if you want
|
| 15 |
|
| 16 |
+
def detect_anomaly(img):
|
| 17 |
+
inputs = processor(images=img, return_tensors="pt").to(device)
|
| 18 |
+
with torch.no_grad():
|
| 19 |
+
features = model(**inputs).last_hidden_state.mean(dim=1)
|
| 20 |
+
|
| 21 |
+
# Fake logic for now (just show feature norm)
|
| 22 |
+
# Later you can compare with normal samples' embeddings
|
| 23 |
+
score = torch.norm(features).item()
|
| 24 |
+
|
| 25 |
+
return f"Feature Norm (use for anomaly logic): {score:.2f}"
|
|
|
|
| 26 |
|
| 27 |
gr.Interface(fn=detect_anomaly,
|
| 28 |
inputs=gr.Image(),
|
| 29 |
+
outputs="text").launch()
|