Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -16,22 +16,24 @@ model_bytes = requests.get(model_url).content
|
|
| 16 |
model = torch.load(BytesIO(model_bytes), map_location=device)
|
| 17 |
model.eval()
|
| 18 |
|
| 19 |
-
# Load CLIP
|
| 20 |
model_clip, preprocess = clip.load("ViT-B/32", device=device)
|
| 21 |
|
| 22 |
-
# Load
|
| 23 |
dataset = load_dataset("nlphuji/flickr30k", split="test")
|
| 24 |
|
| 25 |
-
captions = []
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
|
| 30 |
for example in dataset:
|
| 31 |
try:
|
| 32 |
img = Image.open(requests.get(example["image"], stream=True).raw).convert("RGB")
|
|
|
|
|
|
|
| 33 |
images.append(img)
|
| 34 |
-
captions.append(
|
| 35 |
|
| 36 |
img_tensor = preprocess(img).unsqueeze(0).to(device)
|
| 37 |
with torch.no_grad():
|
|
@@ -39,71 +41,62 @@ for example in dataset:
|
|
| 39 |
img_feat /= img_feat.norm(dim=-1, keepdim=True)
|
| 40 |
image_embeddings.append(img_feat.cpu())
|
| 41 |
|
| 42 |
-
txt_token = clip.tokenize([
|
| 43 |
txt_feat = model_clip.encode_text(txt_token)
|
| 44 |
txt_feat /= txt_feat.norm(dim=-1, keepdim=True)
|
| 45 |
text_embeddings.append(txt_feat.cpu())
|
| 46 |
-
except:
|
|
|
|
| 47 |
continue
|
| 48 |
|
| 49 |
image_embeddings = torch.cat(image_embeddings, dim=0)
|
| 50 |
text_embeddings = torch.cat(text_embeddings, dim=0)
|
| 51 |
|
| 52 |
-
#
|
| 53 |
image_index = faiss.IndexFlatIP(image_embeddings.shape[1])
|
| 54 |
image_index.add(image_embeddings.numpy())
|
| 55 |
|
| 56 |
text_index = faiss.IndexFlatIP(text_embeddings.shape[1])
|
| 57 |
text_index.add(text_embeddings.numpy())
|
| 58 |
|
| 59 |
-
#
|
| 60 |
def image_to_text(image):
|
| 61 |
image_input = preprocess(image).unsqueeze(0).to(device)
|
| 62 |
with torch.no_grad():
|
| 63 |
image_feature = model_clip.encode_image(image_input)
|
| 64 |
image_feature /= image_feature.norm(dim=-1, keepdim=True)
|
|
|
|
| 65 |
D, I = text_index.search(image_feature.cpu().numpy(), 1)
|
|
|
|
| 66 |
score = round(float(D[0][0]) * 100, 2)
|
| 67 |
-
return f"{
|
| 68 |
-
|
| 69 |
-
image_input = preprocess(image).unsqueeze(0).to(device)
|
| 70 |
-
with torch.no_grad():
|
| 71 |
-
image_feature = model_clip.encode_image(image_input)
|
| 72 |
-
image_feature /= image_feature.norm(dim=-1, keepdim=True)
|
| 73 |
-
_, I = text_index.search(image_feature.cpu().numpy(), 1)
|
| 74 |
-
return captions[I[0][0]]
|
| 75 |
|
| 76 |
def text_to_image(text):
|
| 77 |
text_input = clip.tokenize([text]).to(device)
|
| 78 |
with torch.no_grad():
|
| 79 |
text_feature = model_clip.encode_text(text_input)
|
| 80 |
text_feature /= text_feature.norm(dim=-1, keepdim=True)
|
|
|
|
| 81 |
D, I = image_index.search(text_feature.cpu().numpy(), 1)
|
|
|
|
| 82 |
score = round(float(D[0][0]) * 100, 2)
|
| 83 |
-
|
| 84 |
-
return img, f"Match Score: {score}%"
|
| 85 |
-
|
| 86 |
-
text_input = clip.tokenize([text]).to(device)
|
| 87 |
-
with torch.no_grad():
|
| 88 |
-
text_feature = model_clip.encode_text(text_input)
|
| 89 |
-
text_feature /= text_feature.norm(dim=-1, keepdim=True)
|
| 90 |
-
_, I = image_index.search(text_feature.cpu().numpy(), 1)
|
| 91 |
-
return images[I[0][0]]
|
| 92 |
|
| 93 |
# Gradio UI
|
| 94 |
with gr.Blocks() as demo:
|
| 95 |
gr.Markdown("## ๐ผ๏ธ๐ Cross-Modal Retriever on Flickr30k Test Split")
|
|
|
|
| 96 |
with gr.Tab("Image to Text"):
|
| 97 |
img_input = gr.Image(type="pil")
|
| 98 |
text_output = gr.Textbox(label="Retrieved Caption")
|
| 99 |
btn1 = gr.Button("Search Caption")
|
| 100 |
-
btn1.click(image_to_text, inputs=img_input, outputs=text_output)
|
| 101 |
|
| 102 |
with gr.Tab("Text to Image"):
|
| 103 |
text_input = gr.Textbox(label="Enter Text Prompt")
|
| 104 |
img_output = gr.Image(label="Most Similar Image")
|
| 105 |
score_output = gr.Textbox(label="Similarity Score")
|
| 106 |
btn2 = gr.Button("Search Image")
|
| 107 |
-
btn2.click(text_to_image, inputs=text_input, outputs=[img_output, score_output])
|
| 108 |
|
| 109 |
-
demo.launch()
|
|
|
|
| 16 |
model = torch.load(BytesIO(model_bytes), map_location=device)
|
| 17 |
model.eval()
|
| 18 |
|
| 19 |
+
# Load CLIP model
|
| 20 |
model_clip, preprocess = clip.load("ViT-B/32", device=device)
|
| 21 |
|
| 22 |
+
# Load test dataset
|
| 23 |
dataset = load_dataset("nlphuji/flickr30k", split="test")
|
| 24 |
|
| 25 |
+
captions, images = [], []
|
| 26 |
+
image_embeddings, text_embeddings = [], []
|
| 27 |
+
|
| 28 |
+
print("Extracting features...")
|
| 29 |
|
| 30 |
for example in dataset:
|
| 31 |
try:
|
| 32 |
img = Image.open(requests.get(example["image"], stream=True).raw).convert("RGB")
|
| 33 |
+
caption = example["sentence"]
|
| 34 |
+
|
| 35 |
images.append(img)
|
| 36 |
+
captions.append(caption)
|
| 37 |
|
| 38 |
img_tensor = preprocess(img).unsqueeze(0).to(device)
|
| 39 |
with torch.no_grad():
|
|
|
|
| 41 |
img_feat /= img_feat.norm(dim=-1, keepdim=True)
|
| 42 |
image_embeddings.append(img_feat.cpu())
|
| 43 |
|
| 44 |
+
txt_token = clip.tokenize([caption]).to(device)
|
| 45 |
txt_feat = model_clip.encode_text(txt_token)
|
| 46 |
txt_feat /= txt_feat.norm(dim=-1, keepdim=True)
|
| 47 |
text_embeddings.append(txt_feat.cpu())
|
| 48 |
+
except Exception as e:
|
| 49 |
+
print(f"Skipped one sample due to error: {e}")
|
| 50 |
continue
|
| 51 |
|
| 52 |
image_embeddings = torch.cat(image_embeddings, dim=0)
|
| 53 |
text_embeddings = torch.cat(text_embeddings, dim=0)
|
| 54 |
|
| 55 |
+
# Build FAISS indexes
|
| 56 |
image_index = faiss.IndexFlatIP(image_embeddings.shape[1])
|
| 57 |
image_index.add(image_embeddings.numpy())
|
| 58 |
|
| 59 |
text_index = faiss.IndexFlatIP(text_embeddings.shape[1])
|
| 60 |
text_index.add(text_embeddings.numpy())
|
| 61 |
|
| 62 |
+
# Inference Functions
|
| 63 |
def image_to_text(image):
|
| 64 |
image_input = preprocess(image).unsqueeze(0).to(device)
|
| 65 |
with torch.no_grad():
|
| 66 |
image_feature = model_clip.encode_image(image_input)
|
| 67 |
image_feature /= image_feature.norm(dim=-1, keepdim=True)
|
| 68 |
+
|
| 69 |
D, I = text_index.search(image_feature.cpu().numpy(), 1)
|
| 70 |
+
matched_caption = captions[I[0][0]]
|
| 71 |
score = round(float(D[0][0]) * 100, 2)
|
| 72 |
+
return f"{matched_caption}\n(Match Score: {score}%)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
def text_to_image(text):
|
| 75 |
text_input = clip.tokenize([text]).to(device)
|
| 76 |
with torch.no_grad():
|
| 77 |
text_feature = model_clip.encode_text(text_input)
|
| 78 |
text_feature /= text_feature.norm(dim=-1, keepdim=True)
|
| 79 |
+
|
| 80 |
D, I = image_index.search(text_feature.cpu().numpy(), 1)
|
| 81 |
+
matched_image = images[I[0][0]]
|
| 82 |
score = round(float(D[0][0]) * 100, 2)
|
| 83 |
+
return matched_image, f"Match Score: {score}%"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
# Gradio UI
|
| 86 |
with gr.Blocks() as demo:
|
| 87 |
gr.Markdown("## ๐ผ๏ธ๐ Cross-Modal Retriever on Flickr30k Test Split")
|
| 88 |
+
|
| 89 |
with gr.Tab("Image to Text"):
|
| 90 |
img_input = gr.Image(type="pil")
|
| 91 |
text_output = gr.Textbox(label="Retrieved Caption")
|
| 92 |
btn1 = gr.Button("Search Caption")
|
| 93 |
+
btn1.click(fn=image_to_text, inputs=img_input, outputs=text_output)
|
| 94 |
|
| 95 |
with gr.Tab("Text to Image"):
|
| 96 |
text_input = gr.Textbox(label="Enter Text Prompt")
|
| 97 |
img_output = gr.Image(label="Most Similar Image")
|
| 98 |
score_output = gr.Textbox(label="Similarity Score")
|
| 99 |
btn2 = gr.Button("Search Image")
|
| 100 |
+
btn2.click(fn=text_to_image, inputs=text_input, outputs=[img_output, score_output])
|
| 101 |
|
| 102 |
+
demo.launch()
|