|
| 1 | + |
| 2 | +from fastdup.sentry import fastdup_capture_exception |
| 3 | +from fastdup.definitions import MISSING_LABEL |
| 4 | +from fastdup.galleries import fastdup_imread |
| 5 | +from tqdm import tqdm |
| 6 | +import cv2 |
| 7 | + |
| 8 | +def generate_labels(filenames, kwargs): |
| 9 | + try: |
| 10 | + from transformers import VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer |
| 11 | + import torch |
| 12 | + except Exception as e: |
| 13 | + fastdup_capture_exception("Auto generate labels", e) |
| 14 | + print("For auto captioning images need to install transforms and torch packages using `pip install transformers torch`") |
| 15 | + return [MISSING_LABEL]*len(filenames) |
| 16 | + |
| 17 | + try: |
| 18 | + from PIL import Image |
| 19 | + model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning") |
| 20 | + feature_extractor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning") |
| 21 | + tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning") |
| 22 | + |
| 23 | + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 24 | + model.to(device) |
| 25 | + max_length = 16 |
| 26 | + num_beams = 4 |
| 27 | + gen_kwargs = {"max_length": max_length, "num_beams": num_beams} |
| 28 | + |
| 29 | + images = [] |
| 30 | + for image_path in tqdm(filenames): |
| 31 | + i_image = fastdup_imread(image_path, None, kwargs=kwargs) |
| 32 | + if i_image is not None: |
| 33 | + i_image = cv2.cvtColor(i_image, cv2.COLOR_BGR2RGB) |
| 34 | + im_pil = Image.fromarray(i_image) |
| 35 | + images.append(im_pil) |
| 36 | + else: |
| 37 | + images.append(None) |
| 38 | + |
| 39 | + pixel_values = feature_extractor(images=images, return_tensors="pt").pixel_values |
| 40 | + pixel_values = pixel_values.to(device) |
| 41 | + output_ids = model.generate(pixel_values, **gen_kwargs) |
| 42 | + |
| 43 | + preds = tokenizer.batch_decode(output_ids, skip_special_tokens=True) |
| 44 | + preds = [pred.strip() for pred in preds] |
| 45 | + return preds |
| 46 | + except Exception as e: |
| 47 | + fastdup_capture_exception("Auto caption image", e) |
| 48 | + return [MISSING_LABEL]*len(filenames) |
| 49 | + |
| 50 | +def generate_blip_labels(filenames, kwargs): |
| 51 | + |
| 52 | + try: |
| 53 | + from transformers import BlipProcessor, BlipForConditionalGeneration |
| 54 | + from PIL import Image |
| 55 | + except Exception as e: |
| 56 | + fastdup_capture_exception("Auto generate labels", e) |
| 57 | + print("For auto captioning images need to install transforms and torch packages using `pip install transformers`") |
| 58 | + return [MISSING_LABEL] * len(filenames) |
| 59 | + |
| 60 | + try: |
| 61 | + processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large") |
| 62 | + model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-large") |
| 63 | + preds = [] |
| 64 | + for image_path in tqdm(filenames): |
| 65 | + i_image = fastdup_imread(image_path, None, kwargs=kwargs) |
| 66 | + if i_image is not None: |
| 67 | + i_image = cv2.cvtColor(i_image, cv2.COLOR_BGR2RGB) |
| 68 | + im_pil = Image.fromarray(i_image) |
| 69 | + inputs = processor(im_pil, return_tensors="pt") |
| 70 | + out = model.generate(**inputs) |
| 71 | + preds.append((processor.decode(out[0], skip_special_tokens=True))) |
| 72 | + else: |
| 73 | + preds.append(MISSING_LABEL) |
| 74 | + return preds |
| 75 | + |
| 76 | + except Exception as e: |
| 77 | + fastdup_capture_exception("Auto caption image blip", e) |
| 78 | + return [MISSING_LABEL]*len(filenames) |
| 79 | + |
| 80 | +def generate_blip2_labels(filenames, kwargs, text=None): |
| 81 | + |
| 82 | + try: |
| 83 | + from transformers import Blip2Processor, Blip2Model |
| 84 | + from PIL import Image |
| 85 | + import torch |
| 86 | + except Exception as e: |
| 87 | + fastdup_capture_exception("Auto generate labels", e) |
| 88 | + print("For auto captioning images need to install transforms and torch packages using `pip install transformers torch`") |
| 89 | + return [MISSING_LABEL] * len(filenames) |
| 90 | + |
| 91 | + try: |
| 92 | + |
| 93 | + processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b") |
| 94 | + model = Blip2Model.from_pretrained("Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16) |
| 95 | + device = "cuda" if torch.cuda.is_available() else "cpu" |
| 96 | + model.to(device) |
| 97 | + preds = [] |
| 98 | + for image_path in tqdm(filenames): |
| 99 | + i_image = fastdup_imread(image_path, None, kwargs=kwargs) |
| 100 | + if i_image is not None: |
| 101 | + i_image = cv2.cvtColor(i_image, cv2.COLOR_BGR2RGB) |
| 102 | + im_pil = Image.fromarray(i_image) |
| 103 | + inputs = processor(images=im_pil, text=text, return_tensors="pt").to(device, torch.float16) |
| 104 | + generated_ids = model.generate(**inputs) |
| 105 | + generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip() |
| 106 | + preds.append(generated_text) |
| 107 | + else: |
| 108 | + preds.append(MISSING_LABEL) |
| 109 | + return preds |
| 110 | + |
| 111 | + except Exception as e: |
| 112 | + fastdup_capture_exception("Auto caption image blip", e) |
| 113 | + return [MISSING_LABEL]*len(filenames) |
| 114 | + |
| 115 | + |
| 116 | + |
| 117 | + |
| 118 | + |
| 119 | + |
| 120 | +def generate_vqa_labels(filenames, text, kwargs): |
| 121 | + try: |
| 122 | + from transformers import ViltProcessor, ViltForQuestionAnswering |
| 123 | + from PIL import Image |
| 124 | + except Exception as e: |
| 125 | + fastdup_capture_exception("Auto generate labels", e) |
| 126 | + print( |
| 127 | + "For auto captioning images need to install transforms and torch packages using `pip install transformers`") |
| 128 | + return [MISSING_LABEL] * len(filenames) |
| 129 | + |
| 130 | + try: |
| 131 | + preds = [] |
| 132 | + processor = ViltProcessor.from_pretrained("dandelin/vilt-b32-finetuned-vqa") |
| 133 | + model = ViltForQuestionAnswering.from_pretrained("dandelin/vilt-b32-finetuned-vqa") |
| 134 | + for image_path in tqdm(filenames): |
| 135 | + i_image = fastdup_imread(image_path, None, kwargs=kwargs) |
| 136 | + if i_image is not None: |
| 137 | + i_image = cv2.cvtColor(i_image, cv2.COLOR_BGR2RGB) |
| 138 | + im_pil = Image.fromarray(i_image) |
| 139 | + encoding = processor(im_pil, text, return_tensors="pt") |
| 140 | + |
| 141 | + # forward pass |
| 142 | + outputs = model(**encoding) |
| 143 | + logits = outputs.logits |
| 144 | + idx = logits.argmax(-1).item() |
| 145 | + preds.append(model.config.id2label[idx]) |
| 146 | + else: |
| 147 | + preds.append(MISSING_LABEL) |
| 148 | + |
| 149 | + return preds |
| 150 | + |
| 151 | + except Exception as e: |
| 152 | + fastdup_capture_exception("Auto caption image vqa", e) |
| 153 | + return [MISSING_LABEL]*len(filenames) |
| 154 | + |
| 155 | + |
| 156 | +def generate_age_labels(filenames, kwargs): |
| 157 | + from transformers import ViTFeatureExtractor, ViTForImageClassification |
| 158 | + model = ViTForImageClassification.from_pretrained('nateraw/vit-age-classifier') |
| 159 | + transforms = ViTFeatureExtractor.from_pretrained('nateraw/vit-age-classifier') |
| 160 | + |
| 161 | + try: |
| 162 | + preds = [] |
| 163 | + # Get example image from official fairface repo + read it in as an image |
| 164 | + for image_path in tqdm(filenames): |
| 165 | + i_image = fastdup_imread(image_path, None, kwargs=kwargs) |
| 166 | + # Init model, transforms |
| 167 | + |
| 168 | + # Transform our image and pass it through the model |
| 169 | + inputs = transforms(i_image, return_tensors='pt') |
| 170 | + output = model(**inputs) |
| 171 | + |
| 172 | + # Predicted Class probabilities |
| 173 | + proba = output.logits.softmax(1) |
| 174 | + |
| 175 | + # Predicted Classes |
| 176 | + pred = int(proba.argmax(1)[0].int()) |
| 177 | + preds.append( model.config.id2label[pred]) |
| 178 | + return preds |
| 179 | + except Exception as e: |
| 180 | + fastdup_capture_exception("Age label", e) |
| 181 | + return [MISSING_LABEL] * len(filenames) |
0 commit comments