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
| import numpy as np import torch import torch.nn as nn import json import imageio.v3 as iiov3 import torchvision.transforms as transforms from torch.utils.data import Dataset
def load_vocab(if_reverse=False): """load a vocab for indice
Args: input if_reverse -> False : words->indice True : indice->words output vocab -> a dict contains all words(from train_val dset) and its indice count -> total amount of words 0 -> padding """ vocab={} vocab['<pad>']=0 vocab[' ']=1 vocab['<BOS>']=2 vocab['<EOS>']=3 vocab['<UNK>']=4 count=5 with open('./dset/msrvtt/train_val_annotation/train_val_videodatainfo.json',mode='r',) as p: sentences=json.load(p)['sentences'] for sentence in sentences: tmp=sentence['caption'] tmp=tmp.split() for words in tmp: if not(words in vocab): vocab[words]=count count+=1 if(if_reverse): tmp={} for i,words in enumerate(vocab): tmp[i]=words vocab=tmp return vocab,count
def load_annotation(max_lens): """to load train and val annotation
Args: input -> max_lens the max number of words output -> train : a list of training annotation(indice) val : a list of validation annotation(indice) max_lens words """ vocab,_=load_vocab(if_reverse=False) train=[] val=[] with open('./dset/msrvtt/train_val_annotation/train_val_videodatainfo.json',mode='r',) as p: load=json.load(p) sentence_json=load['sentences'] video_json=load['videos'] for i in sentence_json: str_caption=i['caption'] str_id=i['video_id'] tmp=str_caption.split() caption_indice=[] for word in tmp: caption_indice.append(vocab[word]) caption_indice=caption_indice[:max_lens-1] caption_indice.append(3) caption_indice=torch.tensor(np.array(caption_indice),dtype=torch.int64) caption_indice=torch.nn.functional.pad(caption_indice,(0,max_lens-caption_indice.size(0)),mode='constant') num=eval(str_id[5:]) if(video_json[num]['split']=='train'): train.append((caption_indice,str_id)) else: val.append((caption_indice,str_id)) return train,val
def transform_initial_img(img): """ To do pre-process for the image """ process=torch.nn.Sequential( transforms.Resize((256,256),), transforms.RandomCrop((224,224),), ) return process(img)
def load_videos(name,max_frames): """ to load videos Args: input: name -> str (the video to be loaded) // max_frames -> int the max number of frames output: tensorimg -> (T(max_frames),C,H,W) """ address='./dset/msrvtt/train_val_video/'+name+'.mp4' tmp=iiov3.imread(address,plugin='pyav') tmp_shape=tmp.shape[0] index=np.arange(0,min(tmp_shape,max_frames*10),10) tmp=tmp[index,:,:] tmp=torch.tensor(tmp) tmp=torch.swapaxes(tmp,1,3) tmp=torch.swapaxes(tmp,2,3) for per in range(tmp.shape[0]): cur=transform_initial_img(tmp[per]) cur=torch.reshape(cur,(1,3,224,224)) if(per==0): tensorimg=cur else: tensorimg=torch.cat((tensorimg,cur),dim=0) if(tensorimg.size(0)<max_frames): pad=max_frames-tensorimg.size(0) padtensor=torch.zeros([pad,3,224,224]) tensorimg=torch.cat((tensorimg,padtensor),dim=0) tensorimg=tensorimg.type(dtype=torch.float32) return tensorimg
class msrvtt_train_dataloader(Dataset): """subclass to Dataset Args: input:no input output: img: #size(N,T,C,H,W) N->batch_size T->max_length(frames) C,H,W->img frame caption:tuple of diffrent captions perbatch """ def __init__(self,max_frames,max_lens): self.annotation,_=load_annotation(max_lens) self.max_frames=max_frames
def __len__(self): return len(self.annotation) def __getitem__(self, index): curr_caption,curr_name=self.annotation[index] curr_img_sequence=load_videos(curr_name,self.max_frames) return curr_img_sequence,curr_caption
class msrvtt_val_dataloader(Dataset): """subclass to Dataset Args: input:no input output: img: #size(N,T,C,H,W) N->batch_size T->max_length(frames) C,H,W->img frame caption:tuple of diffrent captions perbatch """ def __init__(self,max_lens,max_frames): _,self.annotation=load_annotation(max_lens) self.max_frames=max_frames def __len__(self): return len(self.annotation)
def __getitem__(self, index): curr_caption,curr_name=self.annotation[index] curr_img_sequence=load_videos(curr_name,self.max_frames) return curr_img_sequence,curr_caption
|