TomasHalmazna commited on
Commit
4be3b11
·
verified ·
1 Parent(s): 273cd09

initial commit

Browse files
Files changed (3) hide show
  1. app.py +86 -0
  2. precomputed_clips.pickle +3 -0
  3. requirements.txt +9 -0
app.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import and precomputed clips
2
+ import pickle
3
+
4
+ precomputed_filename = 'precomputed_clips'
5
+
6
+ def load_precomputed(precomputed_filename):
7
+ with open(precomputed_filename + '.pickle', 'rb') as f:
8
+ return pickle.load(f)
9
+
10
+ precomputed_dict = load_precomputed(precomputed_filename)
11
+
12
+
13
+
14
+ # embeddings and similar pictures
15
+ import torch
16
+ from PIL import Image
17
+ from transformers import CLIPProcessor, CLIPModel
18
+ import os
19
+ import numpy as np
20
+ from sklearn.metrics.pairwise import cosine_similarity
21
+
22
+ def get_clip_embeddings(input_data, input_type='text'):
23
+ # Load the CLIP model and processor
24
+ model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
25
+ processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
26
+
27
+ # Prepare the input based on the type
28
+ if input_type == 'text':
29
+ inputs = processor(text=input_data, return_tensors="pt", padding=True, truncation=True)
30
+ elif input_type == 'image':
31
+ if isinstance(input_data, str):
32
+ image = Image.open(input_data)
33
+ elif isinstance(input_data, Image.Image):
34
+ image = input_data
35
+ else:
36
+ raise ValueError("For image input, provide either a file path or a PIL Image object")
37
+ inputs = processor(images=image, return_tensors="pt")
38
+ else:
39
+ raise ValueError("Invalid input_type. Choose 'text' or 'image'")
40
+
41
+ # Get the embeddings
42
+ with torch.no_grad():
43
+ if input_type == 'text':
44
+ embeddings = model.get_text_features(**inputs)
45
+ else:
46
+ embeddings = model.get_image_features(**inputs)
47
+
48
+ return embeddings.numpy()
49
+
50
+
51
+ def find_similar_images(text_input, image_embeddings, all_images, take_best = 4):
52
+ # Získání embeddingu pro text
53
+ text_embedding = get_clip_embeddings(text_input, input_type='text')
54
+
55
+ # Výpočet kosinové podobnosti mezi textem a obrázky
56
+ similarities = cosine_similarity(text_embedding, image_embeddings)
57
+
58
+ # Seřazení podle podobnosti
59
+ best_indices = np.argsort(similarities[0])[::-1][:take_best]
60
+
61
+ # Výběr nejlepších 4 obrázků
62
+ best_images = [all_images[i] for i in best_indices]
63
+ return [Image.open(img) for img in best_images]
64
+
65
+
66
+
67
+ # find the most similar pictures compared to text inserted
68
+ def find_most_similar(text_input):
69
+ return find_similar_images(text_input, precomputed_dict['image_clips'], precomputed_dict['image_paths'])
70
+
71
+
72
+ # gradio run
73
+ import gradio as gr # Importing Gradio for creating the web interface
74
+
75
+ # vytvoření Gradio rozhraní
76
+ interface = gr.Interface(
77
+ fn=find_most_similar,
78
+ inputs="text",
79
+ outputs=gr.Gallery(label="Most Similar Images"),
80
+ title="Find Similar Images with CLIP",
81
+ description="Enter a text prompt to find the most similar images."
82
+ )
83
+
84
+ # app launch
85
+
86
+ interface.launch()
precomputed_clips.pickle ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f31005adeddd524deed221bff7b6f9b5acb313aad0bf6ee1b591b529c9a62369
3
+ size 1322672
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ numpy==1.26.4
2
+ scipy==1.11.4
3
+ scikit-learn==1.3.2
4
+ fastai==2.7.17
5
+ gradio==4.44.1
6
+ timm==1.0.9
7
+ torch==2.2.1
8
+ torchvision==0.17.1
9
+ setuptools