Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
automatic1111
GitHub Repository: automatic1111/stable-diffusion-webui
Path: blob/master/modules/interrogate.py
3055 views
1
import os
2
import sys
3
from collections import namedtuple
4
from pathlib import Path
5
import re
6
7
import torch
8
import torch.hub
9
10
from torchvision import transforms
11
from torchvision.transforms.functional import InterpolationMode
12
13
from modules import devices, paths, shared, lowvram, modelloader, errors, torch_utils
14
15
blip_image_eval_size = 384
16
clip_model_name = 'ViT-L/14'
17
18
Category = namedtuple("Category", ["name", "topn", "items"])
19
20
re_topn = re.compile(r"\.top(\d+)$")
21
22
def category_types():
23
return [f.stem for f in Path(shared.interrogator.content_dir).glob('*.txt')]
24
25
26
def download_default_clip_interrogate_categories(content_dir):
27
print("Downloading CLIP categories...")
28
29
tmpdir = f"{content_dir}_tmp"
30
category_types = ["artists", "flavors", "mediums", "movements"]
31
32
try:
33
os.makedirs(tmpdir, exist_ok=True)
34
for category_type in category_types:
35
torch.hub.download_url_to_file(f"https://raw.githubusercontent.com/pharmapsychotic/clip-interrogator/main/clip_interrogator/data/{category_type}.txt", os.path.join(tmpdir, f"{category_type}.txt"))
36
os.rename(tmpdir, content_dir)
37
38
except Exception as e:
39
errors.display(e, "downloading default CLIP interrogate categories")
40
finally:
41
if os.path.exists(tmpdir):
42
os.removedirs(tmpdir)
43
44
45
class InterrogateModels:
46
blip_model = None
47
clip_model = None
48
clip_preprocess = None
49
dtype = None
50
running_on_cpu = None
51
52
def __init__(self, content_dir):
53
self.loaded_categories = None
54
self.skip_categories = []
55
self.content_dir = content_dir
56
self.running_on_cpu = devices.device_interrogate == torch.device("cpu")
57
58
def categories(self):
59
if not os.path.exists(self.content_dir):
60
download_default_clip_interrogate_categories(self.content_dir)
61
62
if self.loaded_categories is not None and self.skip_categories == shared.opts.interrogate_clip_skip_categories:
63
return self.loaded_categories
64
65
self.loaded_categories = []
66
67
if os.path.exists(self.content_dir):
68
self.skip_categories = shared.opts.interrogate_clip_skip_categories
69
category_types = []
70
for filename in Path(self.content_dir).glob('*.txt'):
71
category_types.append(filename.stem)
72
if filename.stem in self.skip_categories:
73
continue
74
m = re_topn.search(filename.stem)
75
topn = 1 if m is None else int(m.group(1))
76
with open(filename, "r", encoding="utf8") as file:
77
lines = [x.strip() for x in file.readlines()]
78
79
self.loaded_categories.append(Category(name=filename.stem, topn=topn, items=lines))
80
81
return self.loaded_categories
82
83
def create_fake_fairscale(self):
84
class FakeFairscale:
85
def checkpoint_wrapper(self):
86
pass
87
88
sys.modules["fairscale.nn.checkpoint.checkpoint_activations"] = FakeFairscale
89
90
def load_blip_model(self):
91
self.create_fake_fairscale()
92
import models.blip
93
94
files = modelloader.load_models(
95
model_path=os.path.join(paths.models_path, "BLIP"),
96
model_url='https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_caption_capfilt_large.pth',
97
ext_filter=[".pth"],
98
download_name='model_base_caption_capfilt_large.pth',
99
)
100
101
blip_model = models.blip.blip_decoder(pretrained=files[0], image_size=blip_image_eval_size, vit='base', med_config=os.path.join(paths.paths["BLIP"], "configs", "med_config.json"))
102
blip_model.eval()
103
104
return blip_model
105
106
def load_clip_model(self):
107
import clip
108
109
if self.running_on_cpu:
110
model, preprocess = clip.load(clip_model_name, device="cpu", download_root=shared.cmd_opts.clip_models_path)
111
else:
112
model, preprocess = clip.load(clip_model_name, download_root=shared.cmd_opts.clip_models_path)
113
114
model.eval()
115
model = model.to(devices.device_interrogate)
116
117
return model, preprocess
118
119
def load(self):
120
if self.blip_model is None:
121
self.blip_model = self.load_blip_model()
122
if not shared.cmd_opts.no_half and not self.running_on_cpu:
123
self.blip_model = self.blip_model.half()
124
125
self.blip_model = self.blip_model.to(devices.device_interrogate)
126
127
if self.clip_model is None:
128
self.clip_model, self.clip_preprocess = self.load_clip_model()
129
if not shared.cmd_opts.no_half and not self.running_on_cpu:
130
self.clip_model = self.clip_model.half()
131
132
self.clip_model = self.clip_model.to(devices.device_interrogate)
133
134
self.dtype = torch_utils.get_param(self.clip_model).dtype
135
136
def send_clip_to_ram(self):
137
if not shared.opts.interrogate_keep_models_in_memory:
138
if self.clip_model is not None:
139
self.clip_model = self.clip_model.to(devices.cpu)
140
141
def send_blip_to_ram(self):
142
if not shared.opts.interrogate_keep_models_in_memory:
143
if self.blip_model is not None:
144
self.blip_model = self.blip_model.to(devices.cpu)
145
146
def unload(self):
147
self.send_clip_to_ram()
148
self.send_blip_to_ram()
149
150
devices.torch_gc()
151
152
def rank(self, image_features, text_array, top_count=1):
153
import clip
154
155
devices.torch_gc()
156
157
if shared.opts.interrogate_clip_dict_limit != 0:
158
text_array = text_array[0:int(shared.opts.interrogate_clip_dict_limit)]
159
160
top_count = min(top_count, len(text_array))
161
text_tokens = clip.tokenize(list(text_array), truncate=True).to(devices.device_interrogate)
162
text_features = self.clip_model.encode_text(text_tokens).type(self.dtype)
163
text_features /= text_features.norm(dim=-1, keepdim=True)
164
165
similarity = torch.zeros((1, len(text_array))).to(devices.device_interrogate)
166
for i in range(image_features.shape[0]):
167
similarity += (100.0 * image_features[i].unsqueeze(0) @ text_features.T).softmax(dim=-1)
168
similarity /= image_features.shape[0]
169
170
top_probs, top_labels = similarity.cpu().topk(top_count, dim=-1)
171
return [(text_array[top_labels[0][i].numpy()], (top_probs[0][i].numpy()*100)) for i in range(top_count)]
172
173
def generate_caption(self, pil_image):
174
gpu_image = transforms.Compose([
175
transforms.Resize((blip_image_eval_size, blip_image_eval_size), interpolation=InterpolationMode.BICUBIC),
176
transforms.ToTensor(),
177
transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
178
])(pil_image).unsqueeze(0).type(self.dtype).to(devices.device_interrogate)
179
180
with torch.no_grad():
181
caption = self.blip_model.generate(gpu_image, sample=False, num_beams=shared.opts.interrogate_clip_num_beams, min_length=shared.opts.interrogate_clip_min_length, max_length=shared.opts.interrogate_clip_max_length)
182
183
return caption[0]
184
185
def interrogate(self, pil_image):
186
res = ""
187
shared.state.begin(job="interrogate")
188
try:
189
lowvram.send_everything_to_cpu()
190
devices.torch_gc()
191
192
self.load()
193
194
caption = self.generate_caption(pil_image)
195
self.send_blip_to_ram()
196
devices.torch_gc()
197
198
res = caption
199
200
clip_image = self.clip_preprocess(pil_image).unsqueeze(0).type(self.dtype).to(devices.device_interrogate)
201
202
with torch.no_grad(), devices.autocast():
203
image_features = self.clip_model.encode_image(clip_image).type(self.dtype)
204
205
image_features /= image_features.norm(dim=-1, keepdim=True)
206
207
for cat in self.categories():
208
matches = self.rank(image_features, cat.items, top_count=cat.topn)
209
for match, score in matches:
210
if shared.opts.interrogate_return_ranks:
211
res += f", ({match}:{score/100:.3f})"
212
else:
213
res += f", {match}"
214
215
except Exception:
216
errors.report("Error interrogating", exc_info=True)
217
res += "<error>"
218
219
self.unload()
220
shared.state.end()
221
222
return res
223
224