Soooma commited on
Commit
0bd8596
·
verified ·
1 Parent(s): 23ec696

To use transformers instead

Browse files
Files changed (1) hide show
  1. app.py +36 -32
app.py CHANGED
@@ -1,32 +1,36 @@
1
- import torch
2
- import clip
3
- from PIL import Image
4
- import gradio as gr
5
-
6
- # Load model
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
8
- model, preprocess = clip.load("ViT-B/32", device=device)
9
-
10
- # Load normal class image embeddings
11
- # For real use, you should create multiple embeddings and average them
12
- normal_image = preprocess(Image.open("normal_sample.jpg")).unsqueeze(0).to(device)
13
- with torch.no_grad():
14
- normal_embedding = model.encode_image(normal_image)
15
- normal_embedding /= normal_embedding.norm()
16
-
17
- def detect_anomaly(img):
18
- img = preprocess(img).unsqueeze(0).to(device)
19
- with torch.no_grad():
20
- test_embedding = model.encode_image(img)
21
- test_embedding /= test_embedding.norm()
22
- similarity = (test_embedding @ normal_embedding.T).item()
23
-
24
- if similarity < 0.8: # example threshold
25
- result = "Anomaly Detected"
26
- else:
27
- result = "Normal"
28
- return f"Similarity: {similarity:.2f} | {result}"
29
-
30
- gr.Interface(fn=detect_anomaly,
31
- inputs=gr.Image(),
32
- outputs="text").launch()
 
 
 
 
 
1
+ import torch
2
+ from transformers import CLIPProcessor, CLIPModel
3
+ from PIL import Image
4
+ import gradio as gr
5
+
6
+ device = "cuda" if torch.cuda.is_available() else "cpu"
7
+
8
+ # Load the model
9
+ model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(device)
10
+ processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
11
+
12
+ # Load normal image for reference
13
+ normal_image = Image.open("normal_sample.jpg")
14
+
15
+ with torch.no_grad():
16
+ inputs = processor(images=normal_image, return_tensors="pt").to(device)
17
+ normal_features = model.get_image_features(**inputs)
18
+ normal_features = normal_features / normal_features.norm(p=2, dim=-1, keepdim=True)
19
+
20
+ def detect_anomaly(img):
21
+ with torch.no_grad():
22
+ inputs = processor(images=img, return_tensors="pt").to(device)
23
+ test_features = model.get_image_features(**inputs)
24
+ test_features = test_features / test_features.norm(p=2, dim=-1, keepdim=True)
25
+
26
+ similarity = (test_features @ normal_features.T).item()
27
+
28
+ if similarity < 0.8: # threshold example
29
+ result = "Anomaly Detected"
30
+ else:
31
+ result = "Normal"
32
+ return f"Similarity: {similarity:.2f} | {result}"
33
+
34
+ gr.Interface(fn=detect_anomaly,
35
+ inputs=gr.Image(),
36
+ outputs="text").launch()