Soooma commited on
Commit
d6ecc53
·
verified ·
1 Parent(s): f40ec9e

The huggingface/transformers provides DINOv2

Browse files
Files changed (1) hide show
  1. app.py +19 -22
app.py CHANGED
@@ -1,32 +1,29 @@
1
- import gradio as gr
2
  import torch
3
- from patchcore import patchcore
4
- from patchcore.datasets import MVTecDataset
5
  from PIL import Image
6
- import numpy as np
7
 
8
  device = "cuda" if torch.cuda.is_available() else "cpu"
9
 
10
- # Load pre-trained PatchCore model
11
- # Example: using pretrained model for 'fabric' from MVTec dataset
12
- model = patchcore.PatchCore(device=device)
13
- model.load_from_file("pretrained/patchcore_fabric.pth") # You need to provide the correct model file
14
 
15
- def detect_anomaly(img):
16
- img = np.array(img.convert("RGB"))
17
 
18
- # Preprocess and predict
19
- score, anomaly_map = model.predict(img)
20
-
21
- # Simple threshold
22
- threshold = 0.5 # tune this depending on your dataset
23
- if score > threshold:
24
- result = f"Anomaly Detected | Score: {score:.2f}"
25
- else:
26
- result = f"Normal | Score: {score:.2f}"
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()