Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
import pandas as pd
|
4 |
+
import gradio as gr
|
5 |
+
from PIL import Image
|
6 |
+
from transformers import CLIPProcessor, CLIPModel
|
7 |
+
|
8 |
+
def find_similar(image):
|
9 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
10 |
+
|
11 |
+
## Define model
|
12 |
+
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
13 |
+
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
14 |
+
model = model.to(device)
|
15 |
+
|
16 |
+
## Load data
|
17 |
+
photos = pd.read_csv("./photos.tsv000", sep='\t', header=0)
|
18 |
+
photo_features = np.load("./features.npy")
|
19 |
+
photo_ids = pd.read_csv("./photo_ids.csv")
|
20 |
+
photo_ids = list(photo_ids['photo_id'])
|
21 |
+
|
22 |
+
## Inference
|
23 |
+
with torch.no_grad():
|
24 |
+
photo_preprocessed = processor(text=None, images=image, return_tensors="pt", padding=True)["pixel_values"]
|
25 |
+
search_photo_feature = model.get_image_features(photos_preprocessed.to(device))
|
26 |
+
search_photo_feature /= search_photo_feature.norm(dim=-1, keepdim=True)
|
27 |
+
search_photos_feature = search_photos_feature.cpu().numpy()
|
28 |
+
|
29 |
+
## Find similarity
|
30 |
+
similarities = list((search_photos_features @ photo_features.T).squeeze(0))
|
31 |
+
|
32 |
+
## Return best image :)
|
33 |
+
best_photo = sorted(zip(similarities, range(photo_features.shape[0])), key=lambda x: x[0], reverse=True)[0]
|
34 |
+
idx = best_photos[1]
|
35 |
+
photo_id = photo_ids[idx]
|
36 |
+
photo_data = photos[photos["photo_id"] == photo_id].iloc[0]
|
37 |
+
|
38 |
+
return Image(url=photo_data["photo_image_url"] + "?w=640")
|
39 |
+
|
40 |
+
|
41 |
+
iface = gr.Interface(fn=bg_remove, inputs="image", outputs="image").launch()
|