Path: blob/master/modules/interrogate.py
3055 views
import os1import sys2from collections import namedtuple3from pathlib import Path4import re56import torch7import torch.hub89from torchvision import transforms10from torchvision.transforms.functional import InterpolationMode1112from modules import devices, paths, shared, lowvram, modelloader, errors, torch_utils1314blip_image_eval_size = 38415clip_model_name = 'ViT-L/14'1617Category = namedtuple("Category", ["name", "topn", "items"])1819re_topn = re.compile(r"\.top(\d+)$")2021def category_types():22return [f.stem for f in Path(shared.interrogator.content_dir).glob('*.txt')]232425def download_default_clip_interrogate_categories(content_dir):26print("Downloading CLIP categories...")2728tmpdir = f"{content_dir}_tmp"29category_types = ["artists", "flavors", "mediums", "movements"]3031try:32os.makedirs(tmpdir, exist_ok=True)33for category_type in category_types:34torch.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"))35os.rename(tmpdir, content_dir)3637except Exception as e:38errors.display(e, "downloading default CLIP interrogate categories")39finally:40if os.path.exists(tmpdir):41os.removedirs(tmpdir)424344class InterrogateModels:45blip_model = None46clip_model = None47clip_preprocess = None48dtype = None49running_on_cpu = None5051def __init__(self, content_dir):52self.loaded_categories = None53self.skip_categories = []54self.content_dir = content_dir55self.running_on_cpu = devices.device_interrogate == torch.device("cpu")5657def categories(self):58if not os.path.exists(self.content_dir):59download_default_clip_interrogate_categories(self.content_dir)6061if self.loaded_categories is not None and self.skip_categories == shared.opts.interrogate_clip_skip_categories:62return self.loaded_categories6364self.loaded_categories = []6566if os.path.exists(self.content_dir):67self.skip_categories = shared.opts.interrogate_clip_skip_categories68category_types = []69for filename in Path(self.content_dir).glob('*.txt'):70category_types.append(filename.stem)71if filename.stem in self.skip_categories:72continue73m = re_topn.search(filename.stem)74topn = 1 if m is None else int(m.group(1))75with open(filename, "r", encoding="utf8") as file:76lines = [x.strip() for x in file.readlines()]7778self.loaded_categories.append(Category(name=filename.stem, topn=topn, items=lines))7980return self.loaded_categories8182def create_fake_fairscale(self):83class FakeFairscale:84def checkpoint_wrapper(self):85pass8687sys.modules["fairscale.nn.checkpoint.checkpoint_activations"] = FakeFairscale8889def load_blip_model(self):90self.create_fake_fairscale()91import models.blip9293files = modelloader.load_models(94model_path=os.path.join(paths.models_path, "BLIP"),95model_url='https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_caption_capfilt_large.pth',96ext_filter=[".pth"],97download_name='model_base_caption_capfilt_large.pth',98)99100blip_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"))101blip_model.eval()102103return blip_model104105def load_clip_model(self):106import clip107108if self.running_on_cpu:109model, preprocess = clip.load(clip_model_name, device="cpu", download_root=shared.cmd_opts.clip_models_path)110else:111model, preprocess = clip.load(clip_model_name, download_root=shared.cmd_opts.clip_models_path)112113model.eval()114model = model.to(devices.device_interrogate)115116return model, preprocess117118def load(self):119if self.blip_model is None:120self.blip_model = self.load_blip_model()121if not shared.cmd_opts.no_half and not self.running_on_cpu:122self.blip_model = self.blip_model.half()123124self.blip_model = self.blip_model.to(devices.device_interrogate)125126if self.clip_model is None:127self.clip_model, self.clip_preprocess = self.load_clip_model()128if not shared.cmd_opts.no_half and not self.running_on_cpu:129self.clip_model = self.clip_model.half()130131self.clip_model = self.clip_model.to(devices.device_interrogate)132133self.dtype = torch_utils.get_param(self.clip_model).dtype134135def send_clip_to_ram(self):136if not shared.opts.interrogate_keep_models_in_memory:137if self.clip_model is not None:138self.clip_model = self.clip_model.to(devices.cpu)139140def send_blip_to_ram(self):141if not shared.opts.interrogate_keep_models_in_memory:142if self.blip_model is not None:143self.blip_model = self.blip_model.to(devices.cpu)144145def unload(self):146self.send_clip_to_ram()147self.send_blip_to_ram()148149devices.torch_gc()150151def rank(self, image_features, text_array, top_count=1):152import clip153154devices.torch_gc()155156if shared.opts.interrogate_clip_dict_limit != 0:157text_array = text_array[0:int(shared.opts.interrogate_clip_dict_limit)]158159top_count = min(top_count, len(text_array))160text_tokens = clip.tokenize(list(text_array), truncate=True).to(devices.device_interrogate)161text_features = self.clip_model.encode_text(text_tokens).type(self.dtype)162text_features /= text_features.norm(dim=-1, keepdim=True)163164similarity = torch.zeros((1, len(text_array))).to(devices.device_interrogate)165for i in range(image_features.shape[0]):166similarity += (100.0 * image_features[i].unsqueeze(0) @ text_features.T).softmax(dim=-1)167similarity /= image_features.shape[0]168169top_probs, top_labels = similarity.cpu().topk(top_count, dim=-1)170return [(text_array[top_labels[0][i].numpy()], (top_probs[0][i].numpy()*100)) for i in range(top_count)]171172def generate_caption(self, pil_image):173gpu_image = transforms.Compose([174transforms.Resize((blip_image_eval_size, blip_image_eval_size), interpolation=InterpolationMode.BICUBIC),175transforms.ToTensor(),176transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))177])(pil_image).unsqueeze(0).type(self.dtype).to(devices.device_interrogate)178179with torch.no_grad():180caption = 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)181182return caption[0]183184def interrogate(self, pil_image):185res = ""186shared.state.begin(job="interrogate")187try:188lowvram.send_everything_to_cpu()189devices.torch_gc()190191self.load()192193caption = self.generate_caption(pil_image)194self.send_blip_to_ram()195devices.torch_gc()196197res = caption198199clip_image = self.clip_preprocess(pil_image).unsqueeze(0).type(self.dtype).to(devices.device_interrogate)200201with torch.no_grad(), devices.autocast():202image_features = self.clip_model.encode_image(clip_image).type(self.dtype)203204image_features /= image_features.norm(dim=-1, keepdim=True)205206for cat in self.categories():207matches = self.rank(image_features, cat.items, top_count=cat.topn)208for match, score in matches:209if shared.opts.interrogate_return_ranks:210res += f", ({match}:{score/100:.3f})"211else:212res += f", {match}"213214except Exception:215errors.report("Error interrogating", exc_info=True)216res += "<error>"217218self.unload()219shared.state.end()220221return res222223224