Munene1 commited on
Commit
51e6591
·
verified ·
1 Parent(s): ade20c4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -0
app.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #Importing libraries
2
+ import chromadb
3
+ import time
4
+ from transformers import CLIPModel, CLIPProcessor
5
+ import gradio as gr
6
+ from sklearn.metrics.pairwise import cosine_similarity
7
+ import torch
8
+ import numpy
9
+ from PIL import Image
10
+
11
+ #create the client
12
+ client = chromadb.Client()
13
+ collection = client.create_collection('image_collection')
14
+
15
+ #define the model and the proccessor
16
+ model = CLIPModel.from_pretrained('openai/clip-vit-base-patch32')
17
+ processor = CLIPProcessor.from_pretrained ('openai/clip-vit-base-patch32')
18
+
19
+ image_paths = [
20
+ 'img/image-01.jpg',
21
+ 'img/image-02.jpg',
22
+ 'img/image-03.jpeg'
23
+ ]
24
+
25
+ images = [Image.open(image_path) for image_path in image_paths]
26
+ inputs = processor(images = images, return_tensors='pt', padding=True)
27
+
28
+ #Generate the embeddings
29
+ start_time = time.time()
30
+ with torch.no_grad():
31
+ image_embeddings = model.get_image_features(**inputs).numpy()
32
+
33
+ image_embeddings = [embedding.tolist() for embedding in image_embeddings]
34
+
35
+ end_time = time.time()
36
+ ingestion_time = end_time - start_time
37
+
38
+ collection.add(
39
+ embeddings = image_embeddings,
40
+ metadatas = [{'image':image} for image in image_paths],
41
+ ids = [str(i) for i in range(len(image_paths))]
42
+ )
43
+
44
+ print(f'image ingestion time {ingestion_time:.4f} seconds')
45
+ def calculate_accuracy(image_embedding, query_embedding):
46
+ similarity = cosine_similarity([image_embedding], [query_embedding])[0][0]
47
+ return similarity
48
+
49
+ def search_image(query):
50
+ if not query.strip():
51
+ return None, 'Ooopsy, you forgot to input something?, please try again ☠👻'
52
+
53
+ print(f'\nQuery: {query}')
54
+ start_query = time.time()
55
+ inputs = processor(text = query, return_tensors='pt', padding=True)
56
+ with torch.no_grad():
57
+ query_embeding = model.get_text_features(**inputs).numpy()
58
+
59
+ query_embeding = query_embeding.tolist()
60
+ end_query = time.time()
61
+ query_time = end_query - start_query
62
+
63
+ result = collection.query(query_embeddings = query_embeding, n_results=1)
64
+
65
+
66
+ result_image_path = result['metadatas'][0][0]['image']
67
+ result_image_index = int(result['ids'][0][0])
68
+ matched_image_embedding = image_embeddings[result_image_index]
69
+
70
+ accuracy_score = calculate_accuracy(matched_image_embedding, query_embeding[0])
71
+
72
+ result_image = Image.open(result_image_path)
73
+ file_name = result_image_path.split('/')[-1]
74
+
75
+ return result_image, f'Accuracy score: {accuracy_score:.4f}\nQuery Time: {query_time:.4f} seconds', file_name
76
+
77
+ queries = [
78
+ 'A group of polar bears',
79
+ 'A famous landmark in paris',
80
+ 'A hot pizza fresh from the oven',
81
+ 'food',
82
+ 'A place',
83
+ 'A structure in Europe',
84
+ 'Animals'
85
+ ]
86
+
87
+ def populate_queries(suggested_querries):
88
+ return suggested_querries
89
+
90
+ #defining a gradio interface
91
+ with gr.Blocks() as gr_interface:
92
+ gr.Markdown('# This is an image retrieval application Made by Allan Munene🤗😁🤑')
93
+
94
+ with gr.Row():
95
+ with gr.Column():
96
+ gr.Markdown(f'***Image Ingestion Time***: {ingestion_time:.4f} seconds')
97
+ gr.Markdown('## Input Panel')
98
+ custom_query = gr.Textbox(placeholder = 'Input your query here', label='What are you looking for?')
99
+ with gr.Row():
100
+ submit_button = gr.Button('Submit Query')
101
+ cancel_button = gr.Button('Cancel')
102
+
103
+ with gr.Row(elem_id='button-container'):
104
+ for query in queries:
105
+ gr.Button(query).click(fn=lambda q=query: q, outputs=custom_query)
106
+
107
+
108
+ with gr.Column():
109
+ gr.Markdown('Output Image')
110
+ Output_image = gr.Image(type='pil', label='Result_image')
111
+
112
+ accuracy = gr.Textbox(label='Performance')
113
+ f_name = gr.Textbox(label='File Name')
114
+
115
+ submit_button.click(fn=search_image, inputs=custom_query, outputs=[Output_image, accuracy, f_name])
116
+ cancel_button.click(fn=lambda: (None, ''), outputs=[Output_image, accuracy, f_name])
117
+
118
+ gr_interface.launch(share=True)
119
+
120
+