osanseviero commited on
Commit
234d9d6
·
1 Parent(s): 327168e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -0
app.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd, numpy as np
2
+ import os
3
+ from transformers import CLIPProcessor, CLIPTextModel, CLIPModel
4
+
5
+ import gradio as gr
6
+
7
+
8
+ model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
9
+ processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
10
+ df = {0: pd.read_csv('data.csv'), 1: pd.read_csv('data2.csv')}
11
+ embeddings = {0: np.load('embeddings2.npy'), 1: np.load('embeddings.npy')}
12
+ for k in [0, 1]:
13
+ embeddings[k] = np.divide(embeddings[k], np.sqrt(np.sum(embeddings[k]**2, axis=1, keepdims=True)))
14
+
15
+ def compute_text_embeddings(list_of_strings):
16
+ inputs = processor(text=list_of_strings, return_tensors="pt", padding=True)
17
+ return model.get_text_features(**inputs)
18
+
19
+ def compute(query):
20
+ corpus = 'Unsplash'
21
+ n_results=1
22
+
23
+ text_embeddings = compute_text_embeddings([query]).detach().numpy()
24
+ k = 0 if corpus == 'Unsplash' else 1
25
+ results = np.argsort((embeddings[k]@text_embeddings.T)[:, 0])[-1:-n_results-1:-1]
26
+ paths = [df[k].iloc[i]['path'] for i in results]
27
+ print(paths)
28
+ return paths
29
+
30
+ title = "Draw to Search"
31
+ iface = gr.Interface(
32
+ fn=predict,
33
+ inputs=[gr.inputs.Textbox(label="text", lines=3)],
34
+ outputs='text',
35
+ title=title,
36
+ examples=[["Sunset"]]
37
+ )
38
+ iface.launch(debug=True)
39
+