Spaces:
Build error
Build error
Commit
·
186f723
1
Parent(s):
550b53d
Add application file
Browse files- localfile.py +41 -0
- requirements.txt +1 -0
localfile.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import clip
|
2 |
+
import torch
|
3 |
+
import gradio as gr
|
4 |
+
import torchvision.transforms as T
|
5 |
+
from PIL import Image
|
6 |
+
try:
|
7 |
+
from torchvision.transforms import InterpolationMode
|
8 |
+
BICUBIC = InterpolationMode.BICUBIC
|
9 |
+
except ImportError:
|
10 |
+
BICUBIC = Image.BICUBIC
|
11 |
+
import warnings
|
12 |
+
warnings.filterwarnings("ignore")
|
13 |
+
|
14 |
+
#MODEL_PATH = '/media/delta/S/clipmodel.pth' #CHANGE THIS IF YOU WANT TO CHANGE THE MODEL PATH
|
15 |
+
MODEL_PATH ='/media/delta/S/clipmodel_large.pth' #CHANGE THIS IF YOU WANT TO CHANGE THE MODEL PATH
|
16 |
+
|
17 |
+
|
18 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
19 |
+
model = clip.model.build_model(torch.load(MODEL_PATH)).to(device)
|
20 |
+
preprocess = clip.clip._transform(model.visual.input_resolution)
|
21 |
+
|
22 |
+
def zeroshot_detection(Press_Clear_Dont_Stack_Image):
|
23 |
+
inp = Press_Clear_Dont_Stack_Image
|
24 |
+
|
25 |
+
captions = "photo of a guardrail, no guardrail in the photo" #CHANGE THIS IF YOU WANT TO CHANGE THE PREDICTION: separate by commas
|
26 |
+
|
27 |
+
captions = captions.split(',')
|
28 |
+
caption = clip.tokenize(captions).to(device)
|
29 |
+
image = preprocess(inp).unsqueeze(0).to(device)
|
30 |
+
with torch.no_grad():
|
31 |
+
image_features = model.encode_image(image)
|
32 |
+
text_features = model.encode_text(caption)
|
33 |
+
image_features /= image_features.norm(dim=-1, keepdim=True)
|
34 |
+
text_features /= text_features.norm(dim=-1, keepdim=True)
|
35 |
+
similarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)
|
36 |
+
values, indices = similarity[0].topk(len(captions))
|
37 |
+
return {captions[indices[i].item()]: float(values[i].item()) for i in range(len(values))}
|
38 |
+
|
39 |
+
gr.Interface(fn=zeroshot_detection,
|
40 |
+
inputs=[gr.Image(type="pil")],
|
41 |
+
outputs=gr.Label(num_top_classes=1)).launch()
|
requirements.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
git+https://github.com/openai/CLIP.git
|