2022-09-11 18:48:36 +03:00
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
import traceback
|
|
|
|
from collections import namedtuple
|
2023-01-23 20:29:23 +03:00
|
|
|
from pathlib import Path
|
2022-09-11 18:48:36 +03:00
|
|
|
import re
|
|
|
|
|
|
|
|
import torch
|
2023-01-21 09:14:27 +03:00
|
|
|
import torch.hub
|
2022-09-11 18:48:36 +03:00
|
|
|
|
|
|
|
from torchvision import transforms
|
|
|
|
from torchvision.transforms.functional import InterpolationMode
|
|
|
|
|
2023-01-25 19:15:42 +03:00
|
|
|
from modules import devices, paths, shared, lowvram, modelloader, errors
|
2022-09-11 18:48:36 +03:00
|
|
|
|
|
|
|
blip_image_eval_size = 384
|
|
|
|
clip_model_name = 'ViT-L/14'
|
|
|
|
|
|
|
|
Category = namedtuple("Category", ["name", "topn", "items"])
|
|
|
|
|
|
|
|
re_topn = re.compile(r"\.top(\d+)\.")
|
|
|
|
|
2023-01-23 20:29:23 +03:00
|
|
|
def category_types():
|
|
|
|
return [f.stem for f in Path(shared.interrogator.content_dir).glob('*.txt')]
|
|
|
|
|
2022-10-02 22:41:21 +03:00
|
|
|
|
2023-01-21 09:14:27 +03:00
|
|
|
def download_default_clip_interrogate_categories(content_dir):
|
|
|
|
print("Downloading CLIP categories...")
|
|
|
|
|
2023-05-09 22:17:58 +03:00
|
|
|
tmpdir = f"{content_dir}_tmp"
|
2023-01-23 20:29:23 +03:00
|
|
|
category_types = ["artists", "flavors", "mediums", "movements"]
|
|
|
|
|
2023-01-21 09:14:27 +03:00
|
|
|
try:
|
2023-04-29 10:04:01 +03:00
|
|
|
os.makedirs(tmpdir, exist_ok=True)
|
2023-01-23 17:03:17 +03:00
|
|
|
for category_type in category_types:
|
|
|
|
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"))
|
2023-01-21 09:14:27 +03:00
|
|
|
os.rename(tmpdir, content_dir)
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
errors.display(e, "downloading default CLIP interrogate categories")
|
|
|
|
finally:
|
|
|
|
if os.path.exists(tmpdir):
|
2023-04-25 17:53:06 +03:00
|
|
|
os.removedirs(tmpdir)
|
2023-01-21 09:14:27 +03:00
|
|
|
|
|
|
|
|
2022-09-11 18:48:36 +03:00
|
|
|
class InterrogateModels:
|
|
|
|
blip_model = None
|
|
|
|
clip_model = None
|
|
|
|
clip_preprocess = None
|
2022-09-11 23:24:24 +03:00
|
|
|
dtype = None
|
2022-10-20 20:22:59 +03:00
|
|
|
running_on_cpu = None
|
2022-09-11 18:48:36 +03:00
|
|
|
|
|
|
|
def __init__(self, content_dir):
|
2023-01-21 09:14:27 +03:00
|
|
|
self.loaded_categories = None
|
2023-01-23 20:29:23 +03:00
|
|
|
self.skip_categories = []
|
2023-01-21 09:14:27 +03:00
|
|
|
self.content_dir = content_dir
|
2022-10-20 20:22:59 +03:00
|
|
|
self.running_on_cpu = devices.device_interrogate == torch.device("cpu")
|
2022-09-11 18:48:36 +03:00
|
|
|
|
2023-01-21 09:14:27 +03:00
|
|
|
def categories(self):
|
2023-01-23 20:29:23 +03:00
|
|
|
if not os.path.exists(self.content_dir):
|
|
|
|
download_default_clip_interrogate_categories(self.content_dir)
|
|
|
|
|
|
|
|
if self.loaded_categories is not None and self.skip_categories == shared.opts.interrogate_clip_skip_categories:
|
2023-01-23 17:03:17 +03:00
|
|
|
return self.loaded_categories
|
2023-01-21 09:14:27 +03:00
|
|
|
|
|
|
|
self.loaded_categories = []
|
|
|
|
|
|
|
|
if os.path.exists(self.content_dir):
|
2023-01-23 20:29:23 +03:00
|
|
|
self.skip_categories = shared.opts.interrogate_clip_skip_categories
|
|
|
|
category_types = []
|
|
|
|
for filename in Path(self.content_dir).glob('*.txt'):
|
|
|
|
category_types.append(filename.stem)
|
|
|
|
if filename.stem in self.skip_categories:
|
2023-01-23 17:03:17 +03:00
|
|
|
continue
|
2023-01-23 20:29:23 +03:00
|
|
|
m = re_topn.search(filename.stem)
|
2022-09-11 18:48:36 +03:00
|
|
|
topn = 1 if m is None else int(m.group(1))
|
2023-01-23 17:03:17 +03:00
|
|
|
with open(filename, "r", encoding="utf8") as file:
|
2022-09-11 18:48:36 +03:00
|
|
|
lines = [x.strip() for x in file.readlines()]
|
|
|
|
|
2023-01-23 20:29:23 +03:00
|
|
|
self.loaded_categories.append(Category(name=filename.stem, topn=topn, items=lines))
|
2023-01-21 09:14:27 +03:00
|
|
|
|
|
|
|
return self.loaded_categories
|
2022-09-11 18:48:36 +03:00
|
|
|
|
2023-01-24 20:24:27 +03:00
|
|
|
def create_fake_fairscale(self):
|
|
|
|
class FakeFairscale:
|
|
|
|
def checkpoint_wrapper(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
sys.modules["fairscale.nn.checkpoint.checkpoint_activations"] = FakeFairscale
|
|
|
|
|
2022-09-11 18:48:36 +03:00
|
|
|
def load_blip_model(self):
|
2023-01-24 20:30:43 +03:00
|
|
|
self.create_fake_fairscale()
|
2023-01-24 20:24:27 +03:00
|
|
|
import models.blip
|
2022-09-11 18:48:36 +03:00
|
|
|
|
2022-12-03 18:45:51 +03:00
|
|
|
files = modelloader.load_models(
|
|
|
|
model_path=os.path.join(paths.models_path, "BLIP"),
|
|
|
|
model_url='https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_caption_capfilt_large.pth',
|
|
|
|
ext_filter=[".pth"],
|
|
|
|
download_name='model_base_caption_capfilt_large.pth',
|
|
|
|
)
|
2022-11-24 16:04:45 +03:00
|
|
|
|
2022-12-03 18:45:51 +03:00
|
|
|
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"))
|
2022-09-11 18:48:36 +03:00
|
|
|
blip_model.eval()
|
|
|
|
|
|
|
|
return blip_model
|
|
|
|
|
|
|
|
def load_clip_model(self):
|
|
|
|
import clip
|
|
|
|
|
2022-10-20 20:22:59 +03:00
|
|
|
if self.running_on_cpu:
|
2022-10-31 00:14:07 +03:00
|
|
|
model, preprocess = clip.load(clip_model_name, device="cpu", download_root=shared.cmd_opts.clip_models_path)
|
2022-10-20 20:22:59 +03:00
|
|
|
else:
|
2022-10-31 00:14:07 +03:00
|
|
|
model, preprocess = clip.load(clip_model_name, download_root=shared.cmd_opts.clip_models_path)
|
2022-10-20 20:22:59 +03:00
|
|
|
|
2022-09-11 18:48:36 +03:00
|
|
|
model.eval()
|
2022-10-14 11:42:53 +03:00
|
|
|
model = model.to(devices.device_interrogate)
|
2022-09-11 18:48:36 +03:00
|
|
|
|
|
|
|
return model, preprocess
|
|
|
|
|
|
|
|
def load(self):
|
|
|
|
if self.blip_model is None:
|
|
|
|
self.blip_model = self.load_blip_model()
|
2022-10-20 20:22:59 +03:00
|
|
|
if not shared.cmd_opts.no_half and not self.running_on_cpu:
|
2022-09-11 23:24:24 +03:00
|
|
|
self.blip_model = self.blip_model.half()
|
2022-09-11 18:48:36 +03:00
|
|
|
|
2022-10-14 11:42:53 +03:00
|
|
|
self.blip_model = self.blip_model.to(devices.device_interrogate)
|
2022-09-11 18:48:36 +03:00
|
|
|
|
|
|
|
if self.clip_model is None:
|
|
|
|
self.clip_model, self.clip_preprocess = self.load_clip_model()
|
2022-10-20 20:22:59 +03:00
|
|
|
if not shared.cmd_opts.no_half and not self.running_on_cpu:
|
2022-09-11 23:24:24 +03:00
|
|
|
self.clip_model = self.clip_model.half()
|
2022-09-11 18:48:36 +03:00
|
|
|
|
2022-10-14 11:42:53 +03:00
|
|
|
self.clip_model = self.clip_model.to(devices.device_interrogate)
|
2022-09-11 18:48:36 +03:00
|
|
|
|
2022-09-11 23:24:24 +03:00
|
|
|
self.dtype = next(self.clip_model.parameters()).dtype
|
|
|
|
|
2022-09-12 11:55:27 +03:00
|
|
|
def send_clip_to_ram(self):
|
2022-09-11 18:48:36 +03:00
|
|
|
if not shared.opts.interrogate_keep_models_in_memory:
|
|
|
|
if self.clip_model is not None:
|
|
|
|
self.clip_model = self.clip_model.to(devices.cpu)
|
|
|
|
|
2022-09-12 11:55:27 +03:00
|
|
|
def send_blip_to_ram(self):
|
|
|
|
if not shared.opts.interrogate_keep_models_in_memory:
|
2022-09-11 18:48:36 +03:00
|
|
|
if self.blip_model is not None:
|
|
|
|
self.blip_model = self.blip_model.to(devices.cpu)
|
|
|
|
|
2022-09-12 11:55:27 +03:00
|
|
|
def unload(self):
|
|
|
|
self.send_clip_to_ram()
|
|
|
|
self.send_blip_to_ram()
|
|
|
|
|
|
|
|
devices.torch_gc()
|
2022-09-11 18:48:36 +03:00
|
|
|
|
|
|
|
def rank(self, image_features, text_array, top_count=1):
|
|
|
|
import clip
|
|
|
|
|
2023-01-23 17:03:17 +03:00
|
|
|
devices.torch_gc()
|
|
|
|
|
2022-09-12 11:55:27 +03:00
|
|
|
if shared.opts.interrogate_clip_dict_limit != 0:
|
|
|
|
text_array = text_array[0:int(shared.opts.interrogate_clip_dict_limit)]
|
|
|
|
|
2022-09-11 18:48:36 +03:00
|
|
|
top_count = min(top_count, len(text_array))
|
2022-10-14 11:42:53 +03:00
|
|
|
text_tokens = clip.tokenize([text for text in text_array], truncate=True).to(devices.device_interrogate)
|
2022-09-11 23:24:24 +03:00
|
|
|
text_features = self.clip_model.encode_text(text_tokens).type(self.dtype)
|
2022-09-11 18:48:36 +03:00
|
|
|
text_features /= text_features.norm(dim=-1, keepdim=True)
|
|
|
|
|
2022-10-14 11:42:53 +03:00
|
|
|
similarity = torch.zeros((1, len(text_array))).to(devices.device_interrogate)
|
2022-09-11 18:48:36 +03:00
|
|
|
for i in range(image_features.shape[0]):
|
|
|
|
similarity += (100.0 * image_features[i].unsqueeze(0) @ text_features.T).softmax(dim=-1)
|
|
|
|
similarity /= image_features.shape[0]
|
|
|
|
|
|
|
|
top_probs, top_labels = similarity.cpu().topk(top_count, dim=-1)
|
|
|
|
return [(text_array[top_labels[0][i].numpy()], (top_probs[0][i].numpy()*100)) for i in range(top_count)]
|
|
|
|
|
|
|
|
def generate_caption(self, pil_image):
|
|
|
|
gpu_image = transforms.Compose([
|
|
|
|
transforms.Resize((blip_image_eval_size, blip_image_eval_size), interpolation=InterpolationMode.BICUBIC),
|
|
|
|
transforms.ToTensor(),
|
|
|
|
transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
|
2022-10-14 11:42:53 +03:00
|
|
|
])(pil_image).unsqueeze(0).type(self.dtype).to(devices.device_interrogate)
|
2022-09-11 18:48:36 +03:00
|
|
|
|
|
|
|
with torch.no_grad():
|
|
|
|
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)
|
|
|
|
|
|
|
|
return caption[0]
|
|
|
|
|
2022-10-17 08:41:02 +03:00
|
|
|
def interrogate(self, pil_image):
|
2022-12-31 15:46:04 +03:00
|
|
|
res = ""
|
2023-01-03 19:01:04 +03:00
|
|
|
shared.state.begin()
|
|
|
|
shared.state.job = 'interrogate'
|
2022-09-11 18:48:36 +03:00
|
|
|
try:
|
2022-09-12 11:55:27 +03:00
|
|
|
if shared.cmd_opts.lowvram or shared.cmd_opts.medvram:
|
|
|
|
lowvram.send_everything_to_cpu()
|
|
|
|
devices.torch_gc()
|
|
|
|
|
2022-09-11 18:48:36 +03:00
|
|
|
self.load()
|
|
|
|
|
|
|
|
caption = self.generate_caption(pil_image)
|
2022-09-12 11:55:27 +03:00
|
|
|
self.send_blip_to_ram()
|
|
|
|
devices.torch_gc()
|
|
|
|
|
2022-09-11 18:48:36 +03:00
|
|
|
res = caption
|
|
|
|
|
2022-10-14 11:42:53 +03:00
|
|
|
clip_image = self.clip_preprocess(pil_image).unsqueeze(0).type(self.dtype).to(devices.device_interrogate)
|
2022-09-11 18:48:36 +03:00
|
|
|
|
2022-11-29 05:36:35 +03:00
|
|
|
with torch.no_grad(), devices.autocast():
|
2022-10-08 22:12:24 +03:00
|
|
|
image_features = self.clip_model.encode_image(clip_image).type(self.dtype)
|
2022-09-11 18:48:36 +03:00
|
|
|
|
2022-09-11 23:24:24 +03:00
|
|
|
image_features /= image_features.norm(dim=-1, keepdim=True)
|
2022-09-11 18:48:36 +03:00
|
|
|
|
2023-01-21 09:14:27 +03:00
|
|
|
for name, topn, items in self.categories():
|
2022-09-11 23:24:24 +03:00
|
|
|
matches = self.rank(image_features, items, top_count=topn)
|
|
|
|
for match, score in matches:
|
2022-10-17 08:41:02 +03:00
|
|
|
if shared.opts.interrogate_return_ranks:
|
|
|
|
res += f", ({match}:{score/100:.3f})"
|
2022-10-17 01:10:59 +03:00
|
|
|
else:
|
2023-05-09 22:17:58 +03:00
|
|
|
res += f", {match}"
|
2022-09-11 18:48:36 +03:00
|
|
|
|
|
|
|
except Exception:
|
2022-12-24 22:35:29 +03:00
|
|
|
print("Error interrogating", file=sys.stderr)
|
2022-09-11 18:48:36 +03:00
|
|
|
print(traceback.format_exc(), file=sys.stderr)
|
2022-09-12 12:26:37 +03:00
|
|
|
res += "<error>"
|
2022-09-11 18:48:36 +03:00
|
|
|
|
|
|
|
self.unload()
|
2023-01-03 19:01:04 +03:00
|
|
|
shared.state.end()
|
2022-09-11 18:48:36 +03:00
|
|
|
|
|
|
|
return res
|