Spaces:
Running
Running
Upload 4 files
Browse files- .gitattributes +1 -0
- app.py +153 -0
- cat.jpg +3 -0
- cat_dfclor.jpg +0 -0
- requirements.txt +9 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
cat.jpg filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import io
|
5 |
+
from PIL import Image
|
6 |
+
from transformers import (
|
7 |
+
AutoImageProcessor,
|
8 |
+
AutoTokenizer,
|
9 |
+
AutoModelForCausalLM,
|
10 |
+
)
|
11 |
+
import numpy as np
|
12 |
+
model_root = "qihoo360/fg-clip-base"
|
13 |
+
|
14 |
+
model = AutoModelForCausalLM.from_pretrained(model_root,trust_remote_code=True)
|
15 |
+
device = model.device
|
16 |
+
tokenizer = AutoTokenizer.from_pretrained(model_root)
|
17 |
+
image_processor = AutoImageProcessor.from_pretrained(model_root)
|
18 |
+
|
19 |
+
import math
|
20 |
+
import matplotlib
|
21 |
+
matplotlib.use('Agg')
|
22 |
+
import matplotlib.pyplot as plt
|
23 |
+
|
24 |
+
def postprocess_result(probs, labels):
|
25 |
+
pro_output = {labels[i]: probs[i] for i in range(len(labels))}
|
26 |
+
|
27 |
+
return pro_output
|
28 |
+
|
29 |
+
|
30 |
+
def Retrieval(image, candidate_labels):
|
31 |
+
"""
|
32 |
+
Takes an image and a comma-separated string of candidate labels,
|
33 |
+
and returns the classification scores.
|
34 |
+
"""
|
35 |
+
image_size=224
|
36 |
+
image = image.convert("RGB")
|
37 |
+
image = image.resize((image_size,image_size))
|
38 |
+
image_input = image_processor.preprocess(image, return_tensors='pt')['pixel_values'].to(device)
|
39 |
+
walk_short_pos = True
|
40 |
+
|
41 |
+
caption_input = torch.tensor(tokenizer(candidate_labels, max_length=77, padding="max_length", truncation=True).input_ids, dtype=torch.long, device=device)
|
42 |
+
|
43 |
+
with torch.no_grad():
|
44 |
+
image_feature = model.get_image_features(image_input)
|
45 |
+
text_feature = model.get_text_features(caption_input,walk_short_pos=walk_short_pos)
|
46 |
+
image_feature = image_feature / image_feature.norm(p=2, dim=-1, keepdim=True)
|
47 |
+
text_feature = text_feature / text_feature.norm(p=2, dim=-1, keepdim=True)
|
48 |
+
|
49 |
+
logits_per_image = image_feature @ text_feature.T
|
50 |
+
logits_per_image = model.logit_scale.exp() * logits_per_image
|
51 |
+
probs = logits_per_image.softmax(dim=1)
|
52 |
+
results = probs[0].tolist()
|
53 |
+
return results
|
54 |
+
|
55 |
+
|
56 |
+
def Get_Densefeature(image, candidate_labels):
|
57 |
+
"""
|
58 |
+
Takes an image and a comma-separated string of candidate labels,
|
59 |
+
and returns the classification scores.
|
60 |
+
"""
|
61 |
+
candidate_labels = [label.lstrip(" ") for label in candidate_labels.split(",") if label !=""]
|
62 |
+
# print(candidate_labels)
|
63 |
+
|
64 |
+
image_size=224
|
65 |
+
image = image.convert("RGB")
|
66 |
+
image = image.resize((image_size,image_size))
|
67 |
+
image_input = image_processor.preprocess(image, return_tensors='pt')['pixel_values'].to(device)
|
68 |
+
|
69 |
+
with torch.no_grad():
|
70 |
+
dense_image_feature = model.get_image_dense_features(image_input)
|
71 |
+
captions = candidate_labels
|
72 |
+
caption_input = torch.tensor(tokenizer(captions, max_length=77, padding="max_length", truncation=True).input_ids, dtype=torch.long, device=device)
|
73 |
+
text_feature = model.get_text_features(caption_input,walk_short_pos=True)
|
74 |
+
text_feature = text_feature / text_feature.norm(p=2, dim=-1, keepdim=True)
|
75 |
+
dense_image_feature = dense_image_feature / dense_image_feature.norm(p=2, dim=-1, keepdim=True)
|
76 |
+
|
77 |
+
similarity = dense_image_feature.squeeze() @ text_feature.squeeze().T
|
78 |
+
similarity = similarity.cpu().numpy()
|
79 |
+
patch_size = int(math.sqrt(similarity.shape[0]))
|
80 |
+
|
81 |
+
|
82 |
+
original_shape = (patch_size, patch_size)
|
83 |
+
show_image = similarity.reshape(original_shape)
|
84 |
+
# normalized = (show_image - show_image.min()) / (show_image.max() - show_image.min())
|
85 |
+
|
86 |
+
# def viridis_colormap(x):
|
87 |
+
|
88 |
+
# r = np.clip(1.1746 * x - 0.1776, 0, 1)
|
89 |
+
# g = np.clip(2.0 * x - 0.7, 0, 1)
|
90 |
+
# b = np.clip(-2.0 * x + 1.7, 0, 1)
|
91 |
+
# return np.stack([r, g, b], axis=-1)
|
92 |
+
|
93 |
+
# color_mapped = viridis_colormap(normalized)
|
94 |
+
|
95 |
+
# color_mapped_uint8 = (color_mapped * 255).astype(np.uint8)
|
96 |
+
|
97 |
+
# pil_img = Image.fromarray(color_mapped_uint8)
|
98 |
+
# pil_img = pil_img.resize((512,512))
|
99 |
+
|
100 |
+
fig = plt.figure(figsize=(6, 6))
|
101 |
+
plt.imshow(show_image)
|
102 |
+
plt.title('similarity Visualization')
|
103 |
+
plt.axis('off')
|
104 |
+
|
105 |
+
buf = io.BytesIO()
|
106 |
+
plt.savefig(buf, format='png')
|
107 |
+
buf.seek(0)
|
108 |
+
plt.close(fig)
|
109 |
+
|
110 |
+
pil_img = Image.open(buf)
|
111 |
+
# buf.close()
|
112 |
+
return pil_img
|
113 |
+
|
114 |
+
|
115 |
+
|
116 |
+
|
117 |
+
def infer(image, candidate_labels):
|
118 |
+
candidate_labels = [label.lstrip(" ") for label in candidate_labels.split(",") if label !=""]
|
119 |
+
fg_probs = Retrieval(image, candidate_labels)
|
120 |
+
return postprocess_result(fg_probs,candidate_labels)
|
121 |
+
|
122 |
+
|
123 |
+
with gr.Blocks() as demo:
|
124 |
+
gr.Markdown("# FG-CLIP Retrieval")
|
125 |
+
gr.Markdown(
|
126 |
+
"This app uses the FG-CLIP model (qihoo360/fg-clip-base) for retrieval on CPU :"
|
127 |
+
)
|
128 |
+
with gr.Row():
|
129 |
+
with gr.Column():
|
130 |
+
image_input = gr.Image(type="pil")
|
131 |
+
text_input = gr.Textbox(label="Input a list of labels (comma seperated)")
|
132 |
+
run_button = gr.Button("Run Retrieval", visible=True)
|
133 |
+
dfs_button = gr.Button("Run Densefeature", visible=True)
|
134 |
+
with gr.Column():
|
135 |
+
fg_output = gr.Label(label="FG-CLIP Output", num_top_classes=11)
|
136 |
+
dfs_output = gr.Image(label="Similarity Visualization", type="pil")
|
137 |
+
|
138 |
+
examples = [
|
139 |
+
# ["./baklava.jpg", "dessert on a plate, a serving of baklava, a plate and spoon"],
|
140 |
+
# ["./dog.jpg", "A light brown wood stool, A bucket with a body made of dark brown plastic, A black velvet back cover for a cellular telephone, A green ball with a perforated pattern, A light blue plastic helmet made of plastic, A grey slipper made of wool, A newspaper with white and black perforated printed on a paper texture, A blue dog with a white colored head, A yellow sponge with a dark green rough surface, A book with white, dark orange and brown pages made of paper, A black ceramic scarf with a body made of fabric."],
|
141 |
+
["./Landscape.jpg", "red grass, yellow grass, green grass"],
|
142 |
+
["./cat.jpg", "two sleeping cats, two cats playing, three cats laying down"],
|
143 |
+
["./cat_dfclor.jpg", "white cat,"],
|
144 |
+
]
|
145 |
+
gr.Examples(
|
146 |
+
examples=examples,
|
147 |
+
inputs=[image_input, text_input],
|
148 |
+
# outputs=fg_output,
|
149 |
+
# fn=infer,
|
150 |
+
)
|
151 |
+
run_button.click(fn=infer, inputs=[image_input, text_input], outputs=fg_output)
|
152 |
+
dfs_button.click(fn=Get_Densefeature, inputs=[image_input, text_input], outputs=dfs_output)
|
153 |
+
demo.launch()
|
cat.jpg
ADDED
![]() |
Git LFS Details
|
cat_dfclor.jpg
ADDED
![]() |
requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
gradio
|
3 |
+
accelerate
|
4 |
+
transformers==4.41.0
|
5 |
+
pillow
|
6 |
+
einops
|
7 |
+
torchvision
|
8 |
+
matplotlib
|
9 |
+
numpy
|