Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,99 +1,96 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
import clip
|
|
|
|
| 4 |
from PIL import Image
|
| 5 |
import faiss
|
| 6 |
import requests
|
| 7 |
-
from datasets import load_dataset
|
| 8 |
from io import BytesIO
|
| 9 |
|
| 10 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 11 |
|
| 12 |
-
# Load base CLIP model
|
| 13 |
model_clip, preprocess = clip.load("ViT-B/32", device=device)
|
| 14 |
|
| 15 |
-
# Load fine
|
| 16 |
state_dict = torch.load("best_model.pt", map_location=device)
|
| 17 |
-
model_clip.load_state_dict(state_dict)
|
|
|
|
| 18 |
model_clip.eval()
|
| 19 |
|
| 20 |
-
#
|
| 21 |
dataset = load_dataset("nlphuji/flickr30k", split="test")
|
| 22 |
|
| 23 |
-
captions = []
|
| 24 |
-
|
| 25 |
-
image_embeddings = []
|
| 26 |
-
text_embeddings = []
|
| 27 |
-
|
| 28 |
-
print("Preparing embeddings for retrieval pool...")
|
| 29 |
|
|
|
|
| 30 |
for example in dataset:
|
| 31 |
try:
|
| 32 |
-
#
|
| 33 |
img = Image.open(requests.get(example["image"], stream=True).raw).convert("RGB")
|
| 34 |
images.append(img)
|
| 35 |
captions.append(example["sentence"])
|
| 36 |
|
| 37 |
-
#
|
| 38 |
-
|
| 39 |
with torch.no_grad():
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
continue
|
| 52 |
|
| 53 |
-
#
|
| 54 |
-
|
| 55 |
-
|
| 56 |
|
| 57 |
-
#
|
| 58 |
-
|
| 59 |
-
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
|
|
|
| 66 |
with torch.no_grad():
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
D, I =
|
| 70 |
-
score =
|
| 71 |
-
return f"{captions[I[0][0]]}\n(Match Score: {score}%)"
|
| 72 |
-
|
| 73 |
-
def text_to_image(
|
| 74 |
-
|
| 75 |
with torch.no_grad():
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
D, I =
|
| 79 |
-
score =
|
| 80 |
-
|
| 81 |
-
return img, f"Match Score: {score}%"
|
| 82 |
|
|
|
|
| 83 |
with gr.Blocks() as demo:
|
| 84 |
-
gr.Markdown("## π Cross-Modal Retriever
|
| 85 |
-
|
| 86 |
-
with gr.Tab("πΌοΈ Image
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
btn2 = gr.Button("Find Image")
|
| 97 |
-
btn2.click(text_to_image, inputs=text_input, outputs=[img_output, score_output])
|
| 98 |
|
| 99 |
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import torch
|
| 3 |
import clip
|
| 4 |
+
from datasets import load_dataset
|
| 5 |
from PIL import Image
|
| 6 |
import faiss
|
| 7 |
import requests
|
|
|
|
| 8 |
from io import BytesIO
|
| 9 |
|
| 10 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 11 |
|
| 12 |
+
# 1) Load base CLIP model + preprocess
|
| 13 |
model_clip, preprocess = clip.load("ViT-B/32", device=device)
|
| 14 |
|
| 15 |
+
# 2) Load your fineβtuned weights (state_dict) into model_clip
|
| 16 |
state_dict = torch.load("best_model.pt", map_location=device)
|
| 17 |
+
missing, unexpected = model_clip.load_state_dict(state_dict, strict=False)
|
| 18 |
+
print(f"β οΈ Missing keys: {missing}\nβ οΈ Unexpected keys: {unexpected}")
|
| 19 |
model_clip.eval()
|
| 20 |
|
| 21 |
+
# 3) Build retrieval pool from Flickr30k test split
|
| 22 |
dataset = load_dataset("nlphuji/flickr30k", split="test")
|
| 23 |
|
| 24 |
+
images, captions = [], []
|
| 25 |
+
img_embs, txt_embs = [], []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
print("π Preparing retrieval pool embeddings...")
|
| 28 |
for example in dataset:
|
| 29 |
try:
|
| 30 |
+
# load & store raw image + caption
|
| 31 |
img = Image.open(requests.get(example["image"], stream=True).raw).convert("RGB")
|
| 32 |
images.append(img)
|
| 33 |
captions.append(example["sentence"])
|
| 34 |
|
| 35 |
+
# encode image
|
| 36 |
+
img_t = preprocess(img).unsqueeze(0).to(device)
|
| 37 |
with torch.no_grad():
|
| 38 |
+
v = model_clip.encode_image(img_t)
|
| 39 |
+
v /= v.norm(dim=-1, keepdim=True)
|
| 40 |
+
img_embs.append(v.cpu())
|
| 41 |
|
| 42 |
+
# encode text
|
| 43 |
+
t = clip.tokenize([example["sentence"]]).to(device)
|
| 44 |
+
with torch.no_grad():
|
| 45 |
+
tfeat = model_clip.encode_text(t)
|
| 46 |
+
tfeat /= tfeat.norm(dim=-1, keepdim=True)
|
| 47 |
+
txt_embs.append(tfeat.cpu())
|
| 48 |
+
except:
|
| 49 |
continue
|
| 50 |
|
| 51 |
+
# cat into tensors
|
| 52 |
+
img_embs = torch.cat(img_embs, dim=0)
|
| 53 |
+
txt_embs = torch.cat(txt_embs, dim=0)
|
| 54 |
|
| 55 |
+
# build FAISS indices (InnerβProduct = cosine)
|
| 56 |
+
img_index = faiss.IndexFlatIP(img_embs.shape[1])
|
| 57 |
+
img_index.add(img_embs.numpy())
|
| 58 |
|
| 59 |
+
txt_index = faiss.IndexFlatIP(txt_embs.shape[1])
|
| 60 |
+
txt_index.add(txt_embs.numpy())
|
| 61 |
|
| 62 |
+
# 4) Gradio callbacks
|
| 63 |
+
def image_to_text(inp_img):
|
| 64 |
+
im = preprocess(inp_img).unsqueeze(0).to(device)
|
| 65 |
with torch.no_grad():
|
| 66 |
+
v = model_clip.encode_image(im)
|
| 67 |
+
v /= v.norm(dim=-1, keepdim=True)
|
| 68 |
+
D, I = txt_index.search(v.cpu().numpy(), 1)
|
| 69 |
+
score = D[0][0] * 100
|
| 70 |
+
return f"{captions[I[0][0]]}\n(Match Score: {score:.2f}%)"
|
| 71 |
+
|
| 72 |
+
def text_to_image(inp_txt):
|
| 73 |
+
tok = clip.tokenize([inp_txt]).to(device)
|
| 74 |
with torch.no_grad():
|
| 75 |
+
t = model_clip.encode_text(tok)
|
| 76 |
+
t /= t.norm(dim=-1, keepdim=True)
|
| 77 |
+
D, I = img_index.search(t.cpu().numpy(), 1)
|
| 78 |
+
score = D[0][0] * 100
|
| 79 |
+
return images[I[0][0]], f"Match Score: {score:.2f}%"
|
|
|
|
| 80 |
|
| 81 |
+
# 5) Gradio UI
|
| 82 |
with gr.Blocks() as demo:
|
| 83 |
+
gr.Markdown("## π Cross-Modal Retriever (Flickr30k Test Split)\nUpload an image or enter text to retrieve the best match.")
|
| 84 |
+
|
| 85 |
+
with gr.Tab("πΌοΈ Image β Text"):
|
| 86 |
+
img_in = gr.Image(type="pil", label="Upload Image")
|
| 87 |
+
txt_out = gr.Textbox(label="Retrieved Caption")
|
| 88 |
+
gr.Button("Search Caption").click(image_to_text, img_in, txt_out)
|
| 89 |
+
|
| 90 |
+
with gr.Tab("π Text β Image"):
|
| 91 |
+
txt_in = gr.Textbox(label="Enter Text")
|
| 92 |
+
img_out = gr.Image(label="Retrieved Image")
|
| 93 |
+
score_out = gr.Textbox(label="Score")
|
| 94 |
+
gr.Button("Search Image").click(text_to_image, txt_in, [img_out, score_out])
|
|
|
|
|
|
|
| 95 |
|
| 96 |
demo.launch()
|