Soooma commited on
Commit
6437bfa
·
verified ·
1 Parent(s): d749268

Upload the app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -0
app.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()