-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtest_dareblopy.py
466 lines (349 loc) · 17 KB
/
test_dareblopy.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
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
import unittest
import PIL
import PIL.Image
import zipfile
import numpy as np
import pickle
import dareblopy as db
class BasicFileOps(unittest.TestCase):
def test_file_exist(self):
fs = db.FileSystem()
self.assertTrue(fs.exists('README.md'))
def test_rename(self):
fs = db.FileSystem()
self.assertFalse(fs.exists('README2.md'))
fs.rename('README.md', 'README2.md')
self.assertTrue(fs.exists('README2.md'))
fs.rename('README2.md', 'README.md')
def test_seek_tell(self):
fs = db.FileSystem()
file = fs.open("test_utils/test_archive.zip")
self.assertTrue(file)
self.assertEqual(file.tell(), 0)
file.seek(0, 2)
size = file.tell()
self.assertEqual(file.size(), size)
file.seek(-1, 2)
self.assertEqual(file.tell(), size - 1)
file.seek(-100, 1)
self.assertEqual(file.tell(), size - 101)
file.seek(2, 1)
self.assertEqual(file.tell(), size - 101 + 2)
file.seek(0)
self.assertEqual(file.tell(), 0)
def test_does_not_exist(self):
fs = db.FileSystem()
file = fs.open("does_not_exist")
self.assertTrue(file is None)
def test_zip_mounting(self):
fs = db.FileSystem()
zip = fs.open("test_utils/test_archive.zip", lockable=True)
self.assertTrue(zip)
fs.mount_archive(db.open_zip_archive(zip))
s = fs.open('test.txt')
self.assertEqual(s.read().decode('utf-8'), "asdasdasd")
class FileAndImageReadingOps(unittest.TestCase):
def test_reading_to_bytes(self):
f = open("test_utils/test_image.jpg", 'rb')
b1 = f.read()
f.close()
b2 = db.open_as_bytes("test_utils/test_image.jpg")
self.assertEqual(b1, b2)
def test_reading_to_bytes_does_not_exist(self):
with self.assertRaises(RuntimeError) as context:
db.open_as_bytes("does_not_exist")
self.assertTrue('No such file does_not_exist' == context.exception.args[0])
def test_reading_to_numpy(self):
image = PIL.Image.open("test_utils/test_image.jpg")
ndarray1 = np.array(image)
ndarray2 = db.read_jpg_as_numpy("test_utils/test_image.jpg")
ndarray3 = db.read_jpg_as_numpy("test_utils/test_image.jpg", True)
PIL.Image.fromarray(ndarray3).save("test_image2.png")
self.assertTrue(np.all(ndarray1 == ndarray2))
mean_error = np.abs(ndarray1.astype(int) - ndarray3.astype(int)).mean()
PIL.Image.fromarray(np.abs(ndarray1.astype(int) - ndarray3.astype(int)).astype(np.uint8)).save("test_image_diff.png")
self.assertTrue(mean_error < 0.5)
def test_reading_to_numpy_does_not_exist(self):
with self.assertRaises(RuntimeError) as context:
db.read_jpg_as_numpy("does_not_exist")
self.assertTrue('No such file does_not_exist' == context.exception.args[0])
def test_reading_to_bytes_from_zip(self):
archive = zipfile.ZipFile("test_utils/test_image_archive.zip", 'r')
s = archive.open('0.jpg')
b1 = s.read()
archive = db.open_zip_archive("test_utils/test_image_archive.zip")
b2 = archive.open_as_bytes('0.jpg')
b3 = archive.open('0.jpg').read()
self.assertEqual(b1, b2)
self.assertEqual(b1, b3)
def test_reading_to_bytes_from_zip_does_not_exist(self):
archive = db.open_zip_archive("test_utils/test_image_archive.zip")
with self.assertRaises(RuntimeError) as context:
archive.open_as_bytes('does_not_exist')
self.assertEqual('Can\'t open file: does_not_exist', context.exception.args[0])
def test_reading_to_numpy_from_zip(self):
archive = zipfile.ZipFile("test_utils/test_image_archive.zip", 'r')
s = archive.open('0.jpg')
image = PIL.Image.open(s)
ndarray1 = np.array(image)
archive = db.open_zip_archive("test_utils/test_image_archive.zip")
ndarray2 = archive.read_jpg_as_numpy('0.jpg')
self.assertTrue(np.all(ndarray1 == ndarray2))
class TFRecordsReading(unittest.TestCase):
def test_reading_record_does_not_exist(self):
with self.assertRaises(RuntimeError) as context:
db.RecordReader('does_not_exist.tfrecords')
self.assertEqual('Can\'t create RecordReader. Can\'t find file: does_not_exist.tfrecords', context.exception.args[0])
def test_reading_record(self):
rr = db.RecordReader('test_utils/test-small-r00.tfrecords')
self.assertIsNotNone(rr)
file_size, data_size, entries = rr.get_metadata()
self.assertEqual(entries, 50)
records = list(rr)
self.assertEqual(len(records), 50)
# reading ground truth records to confirm reading container was correct
with open('test_utils/test-small-records-r00.pth', 'rb') as f:
records_gt = pickle.load(f)
self.assertEqual(records_gt, records)
def test_record_yielder(self):
record_yielder = db.RecordYielderBasic(['test_utils/test-small-r00.tfrecords',
'test_utils/test-small-r01.tfrecords',
'test_utils/test-small-r02.tfrecords',
'test_utils/test-small-r03.tfrecords'])
self.assertIsNotNone(record_yielder)
records = []
while True:
try:
batch = record_yielder.next_n(32)
records += batch
except StopIteration:
break
# reading ground truth records to confirm reading the container was correct
records_gt = []
for file in ['test_utils/test-small-records-r00.pth',
'test_utils/test-small-records-r01.pth',
'test_utils/test-small-records-r02.pth',
'test_utils/test-small-records-r03.pth']:
with open(file, 'rb') as f:
records_gt += pickle.load(f)
self.assertEqual(records_gt, records)
def test_record_yielder_does_not_exist(self):
record_yielder = db.RecordYielderBasic(['does_not_exist-r00.tfrecords',
'does_not_exist-r01.tfrecords',
'does_not_exist-r02.tfrecords',
'does_not_exist-r03.tfrecords'])
self.assertIsNotNone(record_yielder)
records = []
with self.assertRaises(RuntimeError) as context:
while True:
try:
batch = record_yielder.next_n(32)
records += batch
except StopIteration:
break
def test_record_yielder_randomized(self):
record_yielder = db.RecordYielderRandomized(['test_utils/test-small-r00.tfrecords',
'test_utils/test-small-r01.tfrecords',
'test_utils/test-small-r02.tfrecords',
'test_utils/test-small-r03.tfrecords'],
buffer_size=16,
seed=0,
epoch=0)
self.assertIsNotNone(record_yielder)
records = []
while True:
try:
batch = record_yielder.next_n(32)
records += batch
except StopIteration:
break
# reading ground truth records to confirm reading the container was correct
records_gt = []
for file in ['test_utils/test-small-records-r00.pth',
'test_utils/test-small-records-r01.pth',
'test_utils/test-small-records-r02.pth',
'test_utils/test-small-records-r03.pth']:
with open(file, 'rb') as f:
records_gt += pickle.load(f)
self.assertNotEqual(records_gt, records)
# Check that all records present, and they are unique.
for record in records:
self.assertIn(record, records_gt)
for record_gt in records_gt:
self.assertIn(record_gt, records)
index = []
for record in records:
index.append(records_gt.index(record))
# TODO: Check if sequence is random? For small `buffer_size` it's going to be random only at local scale.
# print(index)
def test_record_yielder_randomized_does_not_exist(self):
record_yielder = db.RecordYielderRandomized(['does_not_exist-r00.tfrecords',
'does_not_exist-r01.tfrecords',
'does_not_exist-r02.tfrecords',
'does_not_exist-r03.tfrecords'],
buffer_size=16,
seed=0,
epoch=0)
self.assertIsNotNone(record_yielder)
records = []
with self.assertRaises(RuntimeError) as context:
while True:
try:
batch = record_yielder.next_n(32)
records += batch
except StopIteration:
break
class TFRecordsReadingCompressed(unittest.TestCase):
def test_reading_record(self):
rr = db.RecordReader('test_utils/test-small-gzip-r00.tfrecords', db.Compression.ZLIB)
self.assertIsNotNone(rr)
file_size, data_size, entries = rr.get_metadata()
self.assertEqual(entries, 50)
records = list(rr)
self.assertEqual(len(records), 50)
# reading ground truth records to confirm reading container was correct
with open('test_utils/test-small-records-gzip-r00.pth', 'rb') as f:
records_gt = pickle.load(f)
self.assertEqual(records_gt, records)
def test_record_yielder(self):
record_yielder = db.RecordYielderBasic(['test_utils/test-small-gzip-r00.tfrecords',
'test_utils/test-small-gzip-r01.tfrecords',
'test_utils/test-small-gzip-r02.tfrecords',
'test_utils/test-small-gzip-r03.tfrecords'], db.Compression.ZLIB)
self.assertIsNotNone(record_yielder)
records = []
while True:
try:
batch = record_yielder.next_n(32)
records += batch
except StopIteration:
break
# reading ground truth records to confirm reading the container was correct
records_gt = []
for file in ['test_utils/test-small-records-gzip-r00.pth',
'test_utils/test-small-records-gzip-r01.pth',
'test_utils/test-small-records-gzip-r02.pth',
'test_utils/test-small-records-gzip-r03.pth']:
with open(file, 'rb') as f:
records_gt += pickle.load(f)
self.assertEqual(records_gt, records)
class TFRecordsParsing(unittest.TestCase):
def setUp(self):
# reading records
self.records = []
for file in ['test_utils/test-small-records-r00.pth',
'test_utils/test-small-records-r01.pth',
'test_utils/test-small-records-r02.pth',
'test_utils/test-small-records-r03.pth']:
with open(file, 'rb') as f:
self.records += pickle.load(f)
# reading ground-truth data
self.images_gt = []
for file in ['test_utils/test-small-images-r00.pth',
'test_utils/test-small-images-r01.pth',
'test_utils/test-small-images-r02.pth',
'test_utils/test-small-images-r03.pth']:
with open(file, 'rb') as f:
self.images_gt += pickle.load(f)
def test_parsing_single_record(self):
features = {
'shape': db.FixedLenFeature([3], db.int64),
'data': db.FixedLenFeature([], db.string)
}
parser = db.RecordParser(features)
self.assertIsNotNone(parser)
for record, image_gt in zip(self.records, self.images_gt):
shape, data = parser.parse_single_example(record)
self.assertTrue(np.all(shape == [3, 32, 32]))
self.assertTrue(np.all(
np.frombuffer(data[0], dtype=np.uint8).reshape(3, 32, 32) == image_gt
))
def test_parsing_single_record_raise(self):
features = {
'does_not_exist': db.FixedLenFeature([], db.string)
}
parser = db.RecordParser(features)
self.assertIsNotNone(parser)
with self.assertRaises(RuntimeError) as context:
for record, image_gt in zip(self.records, self.images_gt):
shape, data = parser.parse_single_example(record)
self.assertEqual('Feature does_not_exist is required but could not be found.', context.exception.args[0])
def test_parsing_single_record_raise2(self):
features = {
'data': db.FixedLenFeature([], db.int64)
}
parser = db.RecordParser(features)
self.assertIsNotNone(parser)
with self.assertRaises(RuntimeError) as context:
for record, image_gt in zip(self.records, self.images_gt):
shape, data = parser.parse_single_example(record)
self.assertEqual('Feature: data. Data types don\'t match. Expected type: int64, Feature is: string.', context.exception.args[0])
def test_parsing_single_record_with_uint8_alternative_to_string(self):
features_alternative = {
'shape': db.FixedLenFeature([3], db.int64),
'data': db.FixedLenFeature([3, 32, 32], db.uint8)
}
parser = db.RecordParser(features_alternative)
self.assertIsNotNone(parser)
for record, image_gt in zip(self.records, self.images_gt):
shape, data = parser.parse_single_example(record)
self.assertTrue(np.all(shape == [3, 32, 32]))
self.assertTrue(np.all(data == image_gt))
def test_parsing_single_record_with_uint8_alternative_to_string_raise(self):
features_alternative = {
'shape': db.FixedLenFeature([3], db.int64),
'data': db.FixedLenFeature([3, 32, 64], db.uint8)
}
parser = db.RecordParser(features_alternative)
self.assertIsNotNone(parser)
with self.assertRaises(RuntimeError) as context:
for record, image_gt in zip(self.records, self.images_gt):
shape, data = parser.parse_single_example(record)
self.assertEqual('Key: data. Number of uint8 values != expected. Values size: 3072 but output shape: [3, 32, 64].', context.exception.args[0])
def test_parsing_records_in_batch(self):
features_alternative = {
'data': db.FixedLenFeature([3, 32, 32], db.uint8)
}
parser = db.RecordParser(features_alternative, False)
self.assertIsNotNone(parser)
data = parser.parse_example(self.records)[0]
self.assertTrue(np.all(data == self.images_gt))
def test_parsing_single_record_inplace(self):
features = {
'shape': db.FixedLenFeature([3], db.int64),
'data': db.FixedLenFeature([], db.string)}
parser = db.RecordParser(features)
self.assertIsNotNone(parser)
shape = np.zeros(3, dtype=np.int64)
data = np.asarray([bytes()], dtype=object)
for record, image_gt in zip(self.records, self.images_gt):
parser.parse_single_example_inplace(record, [shape, data], 0)
image = np.frombuffer(data[0], dtype=np.uint8).reshape(shape)
self.assertTrue(np.all(image == image_gt))
def test_parsing_single_record_inplace_with_uint8(self):
features_alternative = {
'data': db.FixedLenFeature([3, 32, 32], db.uint8)
}
parser = db.RecordParser(features_alternative, False)
self.assertIsNotNone(parser)
data = np.zeros([3, 32, 32], dtype=np.uint8)
for record, image_gt in zip(self.records, self.images_gt):
parser.parse_single_example_inplace(record, [data], 0)
self.assertTrue(np.all(data == image_gt))
class DatasetIterator(unittest.TestCase):
def setUp(self):
# reading ground-truth data
self.images_gt = []
for file in ['test_utils/test-small-images-r00.pth']:
with open(file, 'rb') as f:
self.images_gt += pickle.load(f)
def test_dataset_iterator(self):
features = {
'data': db.FixedLenFeature([3, 32, 32], db.uint8)
}
iterator = db.ParsedTFRecordsDatasetIterator(['test_utils/test-small-r00.tfrecords'],
features, 32, buffer_size=1)
images = np.concatenate([x[0] for x in iterator], axis=0)
self.assertTrue(np.all(images == self.images_gt))
if __name__ == '__main__':
unittest.main()