Spaces:
Runtime error
Runtime error
Commit
Β·
ea3ca19
1
Parent(s):
b469fbd
added app
Browse files- README.md +1 -1
- app.py +48 -0
- requirements.txt +3 -0
README.md
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
---
|
2 |
title: Clip Explorer
|
3 |
-
emoji:
|
4 |
colorFrom: pink
|
5 |
colorTo: red
|
6 |
sdk: gradio
|
|
|
1 |
---
|
2 |
title: Clip Explorer
|
3 |
+
emoji: π
|
4 |
colorFrom: pink
|
5 |
colorTo: red
|
6 |
sdk: gradio
|
app.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import gradio as gr
|
3 |
+
from transformers import CLIPProcessor, CLIPModel
|
4 |
+
|
5 |
+
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
6 |
+
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
7 |
+
|
8 |
+
|
9 |
+
def similarity(image, text, threshold, order):
|
10 |
+
lines = list(map(str.strip, text.splitlines()))
|
11 |
+
if len(lines) == 0:
|
12 |
+
return "", ""
|
13 |
+
inputs = processor(text=lines, images=image, return_tensors="pt", padding=True)
|
14 |
+
with torch.no_grad():
|
15 |
+
outputs = model(**inputs)
|
16 |
+
similarities = outputs.logits_per_image.view(-1)
|
17 |
+
|
18 |
+
# convert to plain list of floats for display
|
19 |
+
similarities = [s.item() for s in similarities]
|
20 |
+
|
21 |
+
if order:
|
22 |
+
tfm = lambda xs: sorted(xs, reverse=True)
|
23 |
+
else:
|
24 |
+
tfm = lambda xs: xs
|
25 |
+
|
26 |
+
detections = [(f"{line}: {similarity:0.2f}", "yes" if similarity > threshold else "no") for similarity, line in tfm(zip(similarities, lines))]
|
27 |
+
|
28 |
+
return detections
|
29 |
+
|
30 |
+
|
31 |
+
demo = gr.Interface(
|
32 |
+
title="CLIP Explorer",
|
33 |
+
description="Input an image and lines of text then press submit to output the image-text similarity scores.",
|
34 |
+
fn=similarity,
|
35 |
+
inputs=[
|
36 |
+
gr.Image(label="Image"),
|
37 |
+
gr.TextArea(label="Text descriptions"),
|
38 |
+
gr.Slider(0, 40, 26, label="Similarity threshold"),
|
39 |
+
gr.Checkbox(value=True, label="Order by similarity score?"),
|
40 |
+
],
|
41 |
+
outputs=gr.HighlightedText(label="Image-text similarity scores", color_map={
|
42 |
+
"yes": "green",
|
43 |
+
"no": "red",
|
44 |
+
}),
|
45 |
+
)
|
46 |
+
|
47 |
+
if __name__ == "__main__":
|
48 |
+
demo.launch()
|
requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
transformers
|
2 |
+
torch
|
3 |
+
gradio
|