Approach 2 is working
Browse files
app.py
CHANGED
|
@@ -1,28 +1,35 @@
|
|
| 1 |
import torch
|
| 2 |
-
from transformers import
|
| 3 |
from PIL import Image
|
| 4 |
import gradio as gr
|
| 5 |
|
| 6 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 7 |
|
| 8 |
-
# Load
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
processor = AutoImageProcessor.from_pretrained(model_name)
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
def detect_anomaly(img):
|
| 17 |
-
inputs = processor(images=img, return_tensors="pt").to(device)
|
| 18 |
with torch.no_grad():
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
gr.Interface(fn=detect_anomaly,
|
| 28 |
inputs=gr.Image(),
|
|
|
|
| 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(),
|