Files changed (1) hide show
  1. app.py +4 -240
app.py CHANGED
@@ -1,243 +1,7 @@
1
- import sys
2
- sys.path.append('src/blip')
3
- sys.path.append('src/clip')
4
-
5
- import clip
6
  import gradio as gr
7
- import hashlib
8
- import math
9
- import numpy as np
10
- import os
11
- import pickle
12
- import torch
13
- import torchvision.transforms as T
14
- import torchvision.transforms.functional as TF
15
-
16
- from models.blip import blip_decoder
17
- from PIL import Image
18
- from torch import nn
19
- from torch.nn import functional as F
20
- from tqdm import tqdm
21
-
22
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
23
-
24
- print("Loading BLIP model...")
25
- blip_image_eval_size = 384
26
- blip_model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_large_caption.pth'
27
- blip_model = blip_decoder(pretrained=blip_model_url, image_size=blip_image_eval_size, vit='large', med_config='./src/blip/configs/med_config.json')
28
- blip_model.eval()
29
- blip_model = blip_model.to(device)
30
-
31
- print("Loading CLIP model...")
32
- clip_model_name = 'ViT-L/14'
33
- clip_model, clip_preprocess = clip.load(clip_model_name, device=device)
34
- clip_model.to(device).eval()
35
-
36
- chunk_size = 2048
37
- flavor_intermediate_count = 2048
38
-
39
-
40
- class LabelTable():
41
- def __init__(self, labels, desc):
42
- self.labels = labels
43
- self.embeds = []
44
-
45
- hash = hashlib.sha256(",".join(labels).encode()).hexdigest()
46
-
47
- os.makedirs('./cache', exist_ok=True)
48
- cache_filepath = f"./cache/{desc}.pkl"
49
- if desc is not None and os.path.exists(cache_filepath):
50
- with open(cache_filepath, 'rb') as f:
51
- data = pickle.load(f)
52
- if data['hash'] == hash:
53
- self.labels = data['labels']
54
- self.embeds = data['embeds']
55
-
56
- if len(self.labels) != len(self.embeds):
57
- self.embeds = []
58
- chunks = np.array_split(self.labels, max(1, len(self.labels)/chunk_size))
59
- for chunk in tqdm(chunks, desc=f"Preprocessing {desc}" if desc else None):
60
- text_tokens = clip.tokenize(chunk).to(device)
61
- with torch.no_grad():
62
- text_features = clip_model.encode_text(text_tokens).float()
63
- text_features /= text_features.norm(dim=-1, keepdim=True)
64
- text_features = text_features.half().cpu().numpy()
65
- for i in range(text_features.shape[0]):
66
- self.embeds.append(text_features[i])
67
-
68
- with open(cache_filepath, 'wb') as f:
69
- pickle.dump({"labels":self.labels, "embeds":self.embeds, "hash":hash}, f)
70
-
71
- def _rank(self, image_features, text_embeds, top_count=1):
72
- top_count = min(top_count, len(text_embeds))
73
- similarity = torch.zeros((1, len(text_embeds))).to(device)
74
- text_embeds = torch.stack([torch.from_numpy(t) for t in text_embeds]).float().to(device)
75
- for i in range(image_features.shape[0]):
76
- similarity += (image_features[i].unsqueeze(0) @ text_embeds.T).softmax(dim=-1)
77
- _, top_labels = similarity.cpu().topk(top_count, dim=-1)
78
- return [top_labels[0][i].numpy() for i in range(top_count)]
79
-
80
- def rank(self, image_features, top_count=1):
81
- if len(self.labels) <= chunk_size:
82
- tops = self._rank(image_features, self.embeds, top_count=top_count)
83
- return [self.labels[i] for i in tops]
84
-
85
- num_chunks = int(math.ceil(len(self.labels)/chunk_size))
86
- keep_per_chunk = int(chunk_size / num_chunks)
87
-
88
- top_labels, top_embeds = [], []
89
- for chunk_idx in tqdm(range(num_chunks)):
90
- start = chunk_idx*chunk_size
91
- stop = min(start+chunk_size, len(self.embeds))
92
- tops = self._rank(image_features, self.embeds[start:stop], top_count=keep_per_chunk)
93
- top_labels.extend([self.labels[start+i] for i in tops])
94
- top_embeds.extend([self.embeds[start+i] for i in tops])
95
-
96
- tops = self._rank(image_features, top_embeds, top_count=top_count)
97
- return [top_labels[i] for i in tops]
98
-
99
- def generate_caption(pil_image):
100
- gpu_image = T.Compose([
101
- T.Resize((blip_image_eval_size, blip_image_eval_size), interpolation=TF.InterpolationMode.BICUBIC),
102
- T.ToTensor(),
103
- T.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
104
- ])(pil_image).unsqueeze(0).to(device)
105
-
106
- with torch.no_grad():
107
- caption = blip_model.generate(gpu_image, sample=False, num_beams=3, max_length=20, min_length=5)
108
- return caption[0]
109
-
110
- def load_list(filename):
111
- with open(filename, 'r', encoding='utf-8', errors='replace') as f:
112
- items = [line.strip() for line in f.readlines()]
113
- return items
114
-
115
- def rank_top(image_features, text_array):
116
- text_tokens = clip.tokenize([text for text in text_array]).to(device)
117
- with torch.no_grad():
118
- text_features = clip_model.encode_text(text_tokens).float()
119
- text_features /= text_features.norm(dim=-1, keepdim=True)
120
-
121
- similarity = torch.zeros((1, len(text_array)), device=device)
122
- for i in range(image_features.shape[0]):
123
- similarity += (image_features[i].unsqueeze(0) @ text_features.T).softmax(dim=-1)
124
-
125
- _, top_labels = similarity.cpu().topk(1, dim=-1)
126
- return text_array[top_labels[0][0].numpy()]
127
-
128
- def similarity(image_features, text):
129
- text_tokens = clip.tokenize([text]).to(device)
130
- with torch.no_grad():
131
- text_features = clip_model.encode_text(text_tokens).float()
132
- text_features /= text_features.norm(dim=-1, keepdim=True)
133
- similarity = text_features.cpu().numpy() @ image_features.cpu().numpy().T
134
- return similarity[0][0]
135
-
136
- def interrogate(image):
137
- caption = generate_caption(image)
138
-
139
- images = clip_preprocess(image).unsqueeze(0).to(device)
140
- with torch.no_grad():
141
- image_features = clip_model.encode_image(images).float()
142
- image_features /= image_features.norm(dim=-1, keepdim=True)
143
-
144
- flaves = flavors.rank(image_features, flavor_intermediate_count)
145
- best_medium = mediums.rank(image_features, 1)[0]
146
- best_artist = artists.rank(image_features, 1)[0]
147
- best_trending = trendings.rank(image_features, 1)[0]
148
- best_movement = movements.rank(image_features, 1)[0]
149
-
150
- best_prompt = caption
151
- best_sim = similarity(image_features, best_prompt)
152
-
153
- def check(addition):
154
- nonlocal best_prompt, best_sim
155
- prompt = best_prompt + ", " + addition
156
- sim = similarity(image_features, prompt)
157
- if sim > best_sim:
158
- best_sim = sim
159
- best_prompt = prompt
160
- return True
161
- return False
162
-
163
- def check_multi_batch(opts):
164
- nonlocal best_prompt, best_sim
165
- prompts = []
166
- for i in range(2**len(opts)):
167
- prompt = best_prompt
168
- for bit in range(len(opts)):
169
- if i & (1 << bit):
170
- prompt += ", " + opts[bit]
171
- prompts.append(prompt)
172
-
173
- prompt = rank_top(image_features, prompts)
174
- sim = similarity(image_features, prompt)
175
- if sim > best_sim:
176
- best_sim = sim
177
- best_prompt = prompt
178
-
179
- check_multi_batch([best_medium, best_artist, best_trending, best_movement])
180
-
181
- extended_flavors = set(flaves)
182
- for _ in tqdm(range(25), desc="Flavor chain"):
183
- try:
184
- best = rank_top(image_features, [f"{best_prompt}, {f}" for f in extended_flavors])
185
- flave = best[len(best_prompt)+2:]
186
- if not check(flave):
187
- break
188
- extended_flavors.remove(flave)
189
- except:
190
- # exceeded max prompt length
191
- break
192
-
193
- return best_prompt
194
-
195
-
196
- sites = ['Artstation', 'behance', 'cg society', 'cgsociety', 'deviantart', 'dribble', 'flickr', 'instagram', 'pexels', 'pinterest', 'pixabay', 'pixiv', 'polycount', 'reddit', 'shutterstock', 'tumblr', 'unsplash', 'zbrush central']
197
- trending_list = [site for site in sites]
198
- trending_list.extend(["trending on "+site for site in sites])
199
- trending_list.extend(["featured on "+site for site in sites])
200
- trending_list.extend([site+" contest winner" for site in sites])
201
-
202
- raw_artists = load_list('data/artists.txt')
203
- artists = [f"by {a}" for a in raw_artists]
204
- artists.extend([f"inspired by {a}" for a in raw_artists])
205
-
206
- artists = LabelTable(artists, "artists")
207
- flavors = LabelTable(load_list('data/flavors.txt'), "flavors")
208
- mediums = LabelTable(load_list('data/mediums.txt'), "mediums")
209
- movements = LabelTable(load_list('data/movements.txt'), "movements")
210
- trendings = LabelTable(trending_list, "trendings")
211
-
212
-
213
- def inference(image):
214
- return interrogate(image)
215
-
216
- inputs = [gr.inputs.Image(type='pil')]
217
- outputs = gr.outputs.Textbox(label="Output")
218
-
219
- title = "CLIP Interrogator"
220
- description = "Want to figure out what a good prompt might be to create new images like an existing one? The CLIP Interrogator is here to get you answers!"
221
- article = """
222
- <p>
223
- Example art by <a href="https://pixabay.com/illustrations/watercolour-painting-art-effect-4799014/">Layers</a>
224
- and <a href="https://pixabay.com/illustrations/animal-painting-cat-feline-pet-7154059/">Lin Tong</a>
225
- from pixabay.com
226
- </p>
227
 
228
- <p>
229
- Has this been helpful to you? Follow me on twitter
230
- <a href="https://twitter.com/pharmapsychotic">@pharmapsychotic</a>
231
- and check out more tools at my
232
- <a href="https://pharmapsychotic.com/tools.html">Ai generative art tools list</a>
233
- </p>
234
- """
235
 
236
- gr.Interface(
237
- inference,
238
- inputs,
239
- outputs,
240
- title=title, description=description,
241
- article=article,
242
- examples=[['example01.jpg'], ['example02.jpg']]
243
- ).launch(enable_queue=True)
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ def greet(name):
4
+ return "Hello " + name + "!!"
 
 
 
 
 
5
 
6
+ iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
+ iface.launch()