bala1802 commited on
Commit
baa3f20
1 Parent(s): 6cc90da

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -0
app.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+
4
+ import torch.nn.functional as F
5
+ from transformers import DistilBertTokenizer
6
+
7
+ from PIL import Image
8
+ import numpy as np
9
+ import requests
10
+
11
+ import clip_inferencing as inference
12
+
13
+ device="cpu"
14
+ valid_df = inference.load_df()
15
+ image_embeddings = inference.load_image_embeddings()
16
+ model = inference.load_model(model_path="model/best.pt")
17
+ tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
18
+ image_embeddings_n = F.normalize(image_embeddings, p=2, dim=-1)
19
+
20
+ n=9
21
+ image_filenames=valid_df['image'].values
22
+
23
+ with gr.Blocks() as demo:
24
+
25
+ def inference(query):
26
+ encoded_query = tokenizer([query])
27
+ batch = {
28
+ key: torch.tensor(values).to(device)
29
+ for key, values in encoded_query.items()
30
+ }
31
+ with torch.no_grad():
32
+ text_features = model.text_encoder(
33
+ input_ids=batch["input_ids"], attention_mask=batch["attention_mask"]
34
+ )
35
+ text_embeddings = model.text_projection(text_features)
36
+
37
+ text_embeddings_n = F.normalize(text_embeddings, p=2, dim=-1)
38
+ dot_similarity = text_embeddings_n @ image_embeddings_n.T
39
+
40
+ values, indices = torch.topk(dot_similarity.squeeze(0), n * 5)
41
+ matches = [image_filenames[idx] for idx in indices[::5]]
42
+
43
+ resulting_images = []
44
+ for match in matches:
45
+ img_https_link = "https://raw.githubusercontent.com/bala1802/ERA_Session19/main/Images/" + match
46
+ resulting_images.append(np.array(Image.open(requests.get(img_https_link, stream=True).raw).convert('RGB')))
47
+
48
+ # resulting_images.append(np.array(Image.open(f"Images/{match}").convert('RGB')))
49
+ return resulting_images
50
+
51
+ gr.Markdown(
52
+ """
53
+ # CLIP Demo !!!
54
+ """
55
+ )
56
+ with gr.Column(variant="panel"):
57
+ with gr.Row():
58
+ text = gr.Textbox(
59
+ label="Enter your prompt",
60
+ max_lines=1,
61
+ placeholder="Extract the matching images ....",
62
+ container=False,
63
+ )
64
+ btn = gr.Button("Show Images", scale=0)
65
+
66
+ gallery = gr.Gallery(
67
+ label="Movies", show_label=False, elem_id="gallery"
68
+ , columns=[4], rows=[1], object_fit="contain", height="auto")
69
+
70
+ btn.click(inference, text, gallery)
71
+
72
+ if __name__ == "__main__":
73
+ demo.launch()