To use transformers instead
Browse files
app.py
CHANGED
|
@@ -1,32 +1,36 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import
|
| 3 |
-
from PIL import Image
|
| 4 |
-
import gradio as gr
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|