-
Notifications
You must be signed in to change notification settings - Fork 16
/
dataloader.py
298 lines (239 loc) · 9.6 KB
/
dataloader.py
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
from __future__ import print_function, division
import os, cv2, json
import torch
import pandas as pd
import numpy as np
import scipy.io.wavfile as wav
from scipy import signal
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from torchvision.transforms import Compose, Normalize, ToTensor
# Get index for each genre
with open("metadata/tags.cls") as fi:
tags = map(lambda x: x[:-1], fi.readlines())
tags = dict((x, i) for i, x in enumerate(tags))
# Function for getting class to video map
# And video to class map
def getMappings(path1="metadata/videos.csv", check_file="metadata/videoToGenre.json", videoFolder="Video"):
# Read from files and generate mappings
if os.path.exists(check_file):
with open(check_file) as fi:
vidToGenre, genreToVid = json.loads(fi.read())
return vidToGenre, genreToVid
# Else
vidToGenre = dict()
genreToVid = dict()
for path in [path1]:
# genre to video path
p = open(path)
lines = p.readlines()
for lin in lines:
words = [word.replace("\n","").replace('"', '') for word in lin.replace(" ", "").split(",")]
words = words[0:3] + [words[3:]]
video_id = words[0]
# Check if video is present in the folder
if not os.path.exists(os.path.join(videoFolder, "video_" + video_id + ".mp4")):
continue
vidToGenre[video_id] = words[3]
# For all genres, add the video to it
for genre in words[3]:
genreToVid[genre] = genreToVid.get(genre, []) + [video_id]
# Save the file
with open(check_file, "w+") as fi:
fi.write(json.dumps([vidToGenre, genreToVid]))
return vidToGenre, genreToVid
def getValMappings(path1="metadata/videos.csv", check_file="metadata/videoToGenreVal.json", videoFolder="Video_val"):
# Read from files and generate mappings
if os.path.exists(check_file):
with open(check_file) as fi:
vidToGenre, genreToVid = json.loads(fi.read())
return vidToGenre, genreToVid
# Else
vidToGenre = dict()
genreToVid = dict()
for path in [path1]:
# genre to video path
p = open(path)
lines = p.readlines()
for lin in lines:
words = [word.replace("\n","").replace('"', '') for word in lin.replace(" ", "").split(",")]
words = words[0:3] + [words[3:]]
video_id = words[0]
# Check if video is present in the folder
if not os.path.exists(os.path.join(videoFolder, "video_" + video_id + ".mp4")):
continue
vidToGenre[video_id] = words[3]
# For all genres, add the video to it
for genre in words[3]:
genreToVid[genre] = genreToVid.get(genre, []) + [video_id]
# Save the file
with open(check_file, "w+") as fi:
fi.write(json.dumps([vidToGenre, genreToVid]))
return vidToGenre, genreToVid
## Define custom dataset here
class GetAudioVideoDataset(Dataset):
def __init__(self, video_path="Video/", audio_path="Audio/", transforms=None, \
validation=None, return_tags=False, return_audio=False):
self.video_path = video_path
self.audio_path = audio_path
self.transforms = transforms
self.return_tags = return_tags
if validation == True or validation == "validation":
v2g, g2v = getValMappings()
elif validation == "test":
v2g, g2v = getValMappings("metadata/videos.csv", "metadata/videosToGenreTest.json", "Video_test")
else:
v2g, g2v = getMappings()
self.vidToGenre = v2g
self.genreToVid = g2v
self.genreClasses = list(g2v.keys())
self.sampleRate = 48000
self.return_audio = return_audio
# Retrieve list of audio and video files
for r, dirs, files in os.walk(self.video_path):
if len(files) > 0:
self.video_files = sorted(files)
break
for r, dirs, files in os.walk(self.audio_path):
if len(files) > 0:
self.audio_files = sorted(files)
break
# Print video and audio files at this point
# print(self.video_files)
# print(self.audio_files)
## Calculate the number of frames and set a length appropriately
# 40% of the total number of items are positive examples
# 60% of the total number are negative
# self.length --> all examples
fps = 30
time = 9
tot_frames = len(self.video_files)*fps*time
# Frames per video
self.fps = fps
self.time = time
self.fpv = fps*time
self.length = 2*tot_frames
self._vid_transform, self._aud_transform = self._get_normalization_transform()
def _get_normalization_transform(self):
_vid_transform = Compose([Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
_aud_transform = Compose([Normalize(mean=[0.0], std=[12.0])])
return _vid_transform, _aud_transform
def __len__(self):
# Consider all positive and negative examples
return self.length
def __getitem__(self, idx):
# Given index of item, decide if its positive or negative example, and then
if idx >= self.length:
print("ERROR")
if self.return_tags:
if self.return_audio:
return (None, None, None, None, None, None)
else:
return (None, None, None, None, None)
else:
return (None, None, None)
# Positive examples
if idx < self.length/2:
video_idx = int(idx/self.fpv)
video_frame_number = idx%self.fpv
frame_time = 500 + (video_frame_number*1000/30)
result = [0]
rate, samples = wav.read(os.path.join(self.audio_path, self.audio_files[video_idx]))
# Extract relevant audio file
time = frame_time/1000.0
# Get video ID
videoID = self.video_files[video_idx].split("video_")[1].split(".mp4")[0]
vidClasses = self.vidToGenre[videoID]
vidIndex = tags[vidClasses[0]]
audIndex = vidIndex
# Store the position of audio
audPos = self.audio_files.index(self.audio_files[video_idx])
# Negative examples
else:
video_idx = int((idx-self.length/2)/self.fpv)
video_frame_number = (idx-self.length/2)%self.fpv
frame_time = 500 + (video_frame_number*1000/30)
result = [1]
# Check for classes of the video and select the ones not in video
videoID = self.video_files[video_idx].split("video_")[1].split(".mp4")[0]
vidClasses = self.vidToGenre[videoID]
restClasses = filter(lambda x: x not in vidClasses, self.genreClasses)
randomClass = np.random.choice(restClasses)
randomVideoID = np.random.choice(self.genreToVid[randomClass])
# Store the position of audio
audPos = self.audio_files.index("audio_" + randomVideoID + ".wav")
# Read the audio now
rate, samples = wav.read(os.path.join(self.audio_path, "audio_" + randomVideoID + ".wav"))
time = (500 + (np.random.randint(self.fpv)*1000/30))/1000.0
# Get video ID
videoID = self.video_files[video_idx].split("video_")[1].split(".mp4")[0]
vidClasses = self.vidToGenre[videoID]
vidIndex = tags[vidClasses[0]]
audIndex = tags[randomClass]
# Extract relevant frame
#########################
vidcap = cv2.VideoCapture(os.path.join(self.video_path, self.video_files[video_idx]))
vidcap.set(cv2.CAP_PROP_POS_MSEC, frame_time)
image = None
success = True
if success:
success, image = vidcap.read()
# Some problem with image, return some random stuff
if image is None:
if self.return_tags:
if self.return_audio:
return torch.Tensor(np.random.rand(3, 224, 224)), torch.Tensor(np.random.rand(1, 257, 200)), torch.LongTensor([2]) \
, torch.LongTensor([vidIndex]), torch.LongTensor([audIndex]), torch.LongTensor([-1])
else:
return torch.Tensor(np.random.rand(3, 224, 224)), torch.Tensor(np.random.rand(1, 257, 200)), torch.LongTensor([2]) \
, torch.LongTensor([vidIndex]), torch.LongTensor([audIndex])
else:
return torch.Tensor(np.random.rand(3, 224, 224)), torch.Tensor(np.random.rand(1, 257, 200)), torch.LongTensor([2])
image = cv2.resize(image, (224,224))
image = image/255.0
else:
print("FAILURE: Breakpoint 1, video_path = {0}".format(self.video_files[video_idx]))
return None, None, None, None, None
##############################
# Bring the channel to front
image = image.transpose(2, 0, 1)
start = int(time*48000)-24000
end = int(time*48000)+24000
samples = samples[start:end]
frequencies, times, spectrogram = signal.spectrogram(samples, self.sampleRate, nperseg=512, noverlap=274)
# Remove bad examples
if spectrogram.shape != (257, 200):
if self.return_tags:
if self.return_audio:
return torch.Tensor(np.random.rand(3, 224, 224)), torch.Tensor(np.random.rand(1, 257, 200)), torch.LongTensor([2]) \
, torch.LongTensor([vidIndex]), torch.LongTensor([audIndex]), torch.LongTensor([audPos])
else:
return torch.Tensor(np.random.rand(3, 224, 224)), torch.Tensor(np.random.rand(1, 257, 200)), torch.LongTensor([2]) \
, torch.LongTensor([vidIndex]), torch.LongTensor([audIndex])
else:
return torch.Tensor(np.random.rand(3, 224, 224)), torch.Tensor(np.random.rand(1, 257, 200)), torch.LongTensor([2])
# Audio
spectrogram = np.log(spectrogram + 1e-7)
spec_shape = list(spectrogram.shape)
spec_shape = tuple([1] + spec_shape)
image = self._vid_transform(torch.Tensor(image))
audio = torch.Tensor(spectrogram.reshape(spec_shape))
audio = self._aud_transform(audio)
# print(image.shape, audio.shape, result)
if self.return_tags:
if self.return_audio:
return image, audio, torch.LongTensor(result), torch.LongTensor([vidIndex]), torch.LongTensor([audIndex]), torch.LongTensor([audPos])
else:
return image, audio, torch.LongTensor(result), torch.LongTensor([vidIndex]), torch.LongTensor([audIndex])
else:
return image, audio, torch.LongTensor(result)
if __name__ == "__main__":
# a, b = getMappings()
dataset = GetAudioVideoDataset()
dataloader = DataLoader(dataset, batch_size=64, shuffle=True)
for (img, aud, res) in dataloader:
print(img.shape, aud.shape, res.shape)
print(img.max(), img.min(), aud.max(), aud.min())
# for k in dataloader:
# print(k)