File size: 11,809 Bytes
c5e886e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 7 16:51:54 2024
@author: Yiyang Liu
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('fivethirtyeight')
import warnings
import os, sys
import cv2
from torchvision import transforms
from transformers import AutoImageProcessor, AutoModel
from transformers import BertTokenizer
import torch
from PIL import Image
import requests
from transformers import Dinov2Config, Dinov2Model
from transformers import ViTModel, ViTFeatureExtractor
import io
import spacy
class Meme_DataSet():
def __init__(self, img_dir, text_file ='Datasets/TEXT_sentences.csv', label = 'Datasets/Sentiments.csv' ,img_model = 'DINOv2', text_model = 'DistilledBert'):
self.text_path = text_file
self.labelpath = label
self.img_dir = img_dir
self.text_tokenizer =None
self.img_preprocess = None
if img_model == 'DINOv2':
self.img_preprocess = AutoImageProcessor.from_pretrained('facebook/dinov2-base')
# Fill in the efficient net
if text_model == 'DistilledBert':
self.text_tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
self.images = []
self.text = []
self.label = []
self.nlp = spacy.load("en_core_web_sm")
def __len__(self):
item_list = os.listdir(self.img_dir)
return len(item_list)
def __getitem__(self, idx):
maxlength = 60
text = pd.read_csv(self.text_path)
label = pd.read_csv(self.labelpath)
self.label = list(label['sarcasm'])[idx]
self.text = list(text['text_corrected'])[idx]
doc = self.nlp(self.text)
lemmatized_words = [token.lemma_ for token in doc if not token.is_stop]
self.text = ' '.join(lemmatized_words)
ct = len(os.listdir(self.img_dir)[idx])
img_path = os.path.join(self.img_dir, os.listdir(self.img_dir)[idx])
transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((224, 224)),
transforms.ToTensor()
])
with open(img_path, 'rb') as file:
corrupted_data = file.read()
# clean corrupted images. strip the last byte
img = Image.open(io.BytesIO(corrupted_data))
img = img.convert("RGB")
buffer = io.BytesIO()
img.save(buffer, format="JPEG")
cleaned_data = buffer.getvalue()
im = Image.open(io.BytesIO(cleaned_data))
image_batch = transform(im)
if self.img_preprocess:
image = self.img_preprocess(images = image_batch, return_tensors = 'pt',do_rescale=False)
#CAPTION at entry 1
text_batch = self.text_tokenizer.encode_plus(
self.text,
add_special_tokens=True, # Add [CLS] and [SEP]
max_length=maxlength,
padding='max_length',
truncation=True, # Truncate to max_length
return_attention_mask=True, # Return attention masks
return_tensors='pt' # Return PyTorch tensors
)
print(text_batch['input_ids'])
return {'image': image['pixel_values'], 'input_ids': text_batch['input_ids'], 'attention': text_batch['attention_mask'], 'label': self.label}
def getimages(self, idx):
'''
Used to return unprocessed image
'''
for i in idx:
item = os.listdir(self.img_dir)[i]
img_path = os.path.join(self.img_dir,item)
image = cv2.imread(img_path)
#image = cv2.resize(image,(224, 224,3))
self.images.append(image)
return self.images
#
#-----------------------------
class Meme_Classify():
def __init__(self, img_dir, text_file ='Datasets/TEXT_sentences.csv', label = 'Datasets/Sentiments.csv' ,img_model = 'DINOv2', text_model = 'Bert'):
self.nlp = spacy.load("en_core_web_sm")
self.text_path = text_file
self.labelpath = label
self.img_dir = img_dir
self.text_tokenizer =None
self.img_preprocess = None
if img_model == 'DINOv2':
self.img_preprocess = AutoImageProcessor.from_pretrained('facebook/dinov2-base')
# Fill in the efficient net
if text_model == 'Bert':
self.text_tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
self.images = []
self.text = []
self.label = []
self.raw_label = []
def __len__(self):
item_list = os.listdir(self.img_dir)
return len(item_list)
def __getitem__(self, idx):
maxlength = 30 # REMEMBER TO ADJUST THIS!!!!!!!!
text = pd.read_csv(self.text_path)
label = pd.read_csv(self.labelpath)
label = label['sarcasm'].tolist()
l = label[idx]
if l == 1:
self.label = 'a sarcastic meme'
self.raw_label = l
else:
self.label = 'a regular meme'
self.raw_label = l
#Lemmatization and filter stop words
tt = text['text_corrected'].tolist()
self.text = tt[idx]
doc = self.nlp(self.text)
lemmatized_words = [token.lemma_ for token in doc if not token.is_stop]
self.text = ' '.join(lemmatized_words)
#self.text = self.text + self.label
ct = len(os.listdir(self.img_dir)[idx])
img_path = os.path.join(self.img_dir, os.listdir(self.img_dir)[idx])
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.ColorJitter(brightness=.3, hue=.2),
transforms.Normalize((0.48145466, 0.4578275, 0.40821073),(0.26862954, 0.26130258, 0.27577711)),
])
with open(img_path, 'rb') as file:
corrupted_data = file.read()
# clean corrupted images. strip the last byte
img = Image.open(io.BytesIO(corrupted_data))
img = img.convert("RGB")
buffer = io.BytesIO()
img.save(buffer, format="JPEG")
cleaned_data = buffer.getvalue()
im = Image.open(io.BytesIO(cleaned_data))
image_batch = transform(im)
if self.img_preprocess:
#image = self.img_preprocess(images = image_batch, return_tensors = 'pt', do_rescale = False)
pass
#CAPTION at entry 1
text_batch = self.text_tokenizer.encode_plus(
self.text + self.label,
add_special_tokens=True, # Add [CLS] and [SEP]
max_length=maxlength,
padding='max_length',
truncation=True, # Truncate to max_length
return_attention_mask=True, # Return attention masks
return_tensors='pt' # Return PyTorch tensors
)
#return {'image': image['pixel_values'], 'input_ids': text_batch['input_ids'], 'attention': text_batch['attention_mask'], 'label': self.raw_label}
return {'image': image_batch, 'input_ids': text_batch['input_ids'], 'attention': text_batch['attention_mask'], 'label': self.raw_label}
def getimages(self, idx):
'''
Used to return unprocessed image
'''
for i in idx:
item = os.listdir(self.img_dir)[i]
img_path = os.path.join(self.img_dir,item)
image = cv2.imread(img_path)
#image = cv2.resize(image,(224, 224,3))
self.images.append(image)
return self.images
class Meme_Verify():
def __init__(self, img_dir, label = 'Datasets/Sentiments.csv' ,img_model = 'DINOv2', text_model = 'DistilledBert'):
self.nlp = spacy.load("en_core_web_sm")
self.labelpath = label
self.img_dir = img_dir
self.text_tokenizer =None
self.img_preprocess = None
if img_model == 'DINOv2':
self.img_preprocess = AutoImageProcessor.from_pretrained('facebook/dinov2-base')
# Fill in the efficient net
if text_model == 'DistilledBert':
self.text_tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
self.images = []
self.label = []
def __len__(self):
item_list = os.listdir(self.img_dir)
return len(item_list)
def __getitem__(self, idx):
maxlength = 128 # REMEMBER TO ADJUST THIS!!!!!!!!
label = pd.read_csv(self.labelpath)
if list(label['sarcasm'])[idx] == 1:
self.label = 'a sarcastic meme'
else:
self.label = 'a regular meme'
#Lemmatization and filter stop words
ct = len(os.listdir(self.img_dir)[idx])
img_path = os.path.join(self.img_dir, os.listdir(self.img_dir)[idx])
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor().permute(2, 0, 1).float()
])
with open(img_path, 'rb') as file:
corrupted_data = file.read()
# clean corrupted images. strip the last byte
img = Image.open(io.BytesIO(corrupted_data))
img = img.convert("RGB")
buffer = io.BytesIO()
img.save(buffer, format="JPEG")
cleaned_data = buffer.getvalue()
im = Image.open(io.BytesIO(cleaned_data))
image_batch = transform(im)
if self.img_preprocess:
image = self.img_preprocess(images = image_batch, return_tensors = 'pt')
#CAPTION at entry 1
text_batch = self.text_tokenizer.encode_plus(
self.label,
add_special_tokens=True, # Add [CLS] and [SEP]
max_length=maxlength,
padding='max_length',
truncation=True, # Truncate to max_length
return_attention_mask=True, # Return attention masks
return_tensors='pt' # Return PyTorch tensors
)
return {'image': image['pixel_values'], 'input_ids': text_batch['input_ids'], 'attention': text_batch['attention_mask']}
def getimages(self, idx):
'''
Used to return unprocessed image
'''
for i in idx:
item = os.listdir(self.img_dir)[i]
img_path = os.path.join(self.img_dir,item)
image = cv2.imread(img_path)
#image = cv2.resize(image,(224, 224,3))
self.images.append(image)
return self.images
|