JustDelet commited on
Commit
57bbf59
·
verified ·
1 Parent(s): a123843

Upload dataset_tool.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. dataset_tool.py +459 -0
dataset_tool.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ #
3
+ # NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ # and proprietary rights in and to this software, related documentation
5
+ # and any modifications thereto. Any use, reproduction, disclosure or
6
+ # distribution of this software and related documentation without an express
7
+ # license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+
9
+ """Tool for creating ZIP/PNG based datasets."""
10
+
11
+ import functools
12
+ import gzip
13
+ import io
14
+ import json
15
+ import os
16
+ import pickle
17
+ import re
18
+ import sys
19
+ import tarfile
20
+ import zipfile
21
+ from pathlib import Path
22
+ from typing import Callable, Optional, Tuple, Union
23
+
24
+ import click
25
+ import numpy as np
26
+ import PIL.Image
27
+ from tqdm import tqdm
28
+
29
+ #----------------------------------------------------------------------------
30
+
31
+ def error(msg):
32
+ print('Error: ' + msg)
33
+ sys.exit(1)
34
+
35
+ #----------------------------------------------------------------------------
36
+
37
+ def parse_tuple(s: str) -> Tuple[int, int]:
38
+ '''Parse a 'M,N' or 'MxN' integer tuple.
39
+
40
+ Example:
41
+ '4x2' returns (4,2)
42
+ '0,1' returns (0,1)
43
+ '''
44
+ m = re.match(r'^(\d+)[x,](\d+)$', s)
45
+ if m:
46
+ return (int(m.group(1)), int(m.group(2)))
47
+ raise ValueError(f'cannot parse tuple {s}')
48
+
49
+ #----------------------------------------------------------------------------
50
+
51
+ def maybe_min(a: int, b: Optional[int]) -> int:
52
+ if b is not None:
53
+ return min(a, b)
54
+ return a
55
+
56
+ #----------------------------------------------------------------------------
57
+
58
+ def file_ext(name: Union[str, Path]) -> str:
59
+ return str(name).split('.')[-1]
60
+
61
+ #----------------------------------------------------------------------------
62
+
63
+ def is_image_ext(fname: Union[str, Path]) -> bool:
64
+ ext = file_ext(fname).lower()
65
+ return f'.{ext}' in PIL.Image.EXTENSION # type: ignore
66
+
67
+ #----------------------------------------------------------------------------
68
+
69
+ def open_image_folder(source_dir, *, max_images: Optional[int]):
70
+ input_images = [str(f) for f in sorted(Path(source_dir).rglob('*')) if is_image_ext(f) and os.path.isfile(f)]
71
+
72
+ # Load labels.
73
+ labels = {}
74
+ meta_fname = os.path.join(source_dir, 'dataset.json')
75
+ if os.path.isfile(meta_fname):
76
+ with open(meta_fname, 'r') as file:
77
+ labels = json.load(file)['labels']
78
+ if labels is not None:
79
+ labels = { x[0]: x[1] for x in labels }
80
+ else:
81
+ labels = {}
82
+
83
+ max_idx = maybe_min(len(input_images), max_images)
84
+
85
+ def iterate_images():
86
+ for idx, fname in enumerate(input_images):
87
+ arch_fname = os.path.relpath(fname, source_dir)
88
+ arch_fname = arch_fname.replace('\\', '/')
89
+ img = np.array(PIL.Image.open(fname))
90
+ yield dict(img=img, label=labels.get(arch_fname))
91
+ if idx >= max_idx-1:
92
+ break
93
+ return max_idx, iterate_images()
94
+
95
+ #----------------------------------------------------------------------------
96
+
97
+ def open_image_zip(source, *, max_images: Optional[int]):
98
+ with zipfile.ZipFile(source, mode='r') as z:
99
+ input_images = [str(f) for f in sorted(z.namelist()) if is_image_ext(f)]
100
+
101
+ # Load labels.
102
+ labels = {}
103
+ if 'dataset.json' in z.namelist():
104
+ with z.open('dataset.json', 'r') as file:
105
+ labels = json.load(file)['labels']
106
+ if labels is not None:
107
+ labels = { x[0]: x[1] for x in labels }
108
+ else:
109
+ labels = {}
110
+
111
+ max_idx = maybe_min(len(input_images), max_images)
112
+
113
+ def iterate_images():
114
+ with zipfile.ZipFile(source, mode='r') as z:
115
+ for idx, fname in enumerate(input_images):
116
+ with z.open(fname, 'r') as file:
117
+ img = PIL.Image.open(file) # type: ignore
118
+ img = np.array(img)
119
+ yield dict(img=img, label=labels.get(fname))
120
+ if idx >= max_idx-1:
121
+ break
122
+ return max_idx, iterate_images()
123
+
124
+ #----------------------------------------------------------------------------
125
+
126
+ def open_lmdb(lmdb_dir: str, *, max_images: Optional[int]):
127
+ import cv2 # pip install opencv-python # pylint: disable=import-error
128
+ import lmdb # pip install lmdb # pylint: disable=import-error
129
+
130
+ with lmdb.open(lmdb_dir, readonly=True, lock=False).begin(write=False) as txn:
131
+ max_idx = maybe_min(txn.stat()['entries'], max_images)
132
+
133
+ def iterate_images():
134
+ with lmdb.open(lmdb_dir, readonly=True, lock=False).begin(write=False) as txn:
135
+ for idx, (_key, value) in enumerate(txn.cursor()):
136
+ try:
137
+ try:
138
+ img = cv2.imdecode(np.frombuffer(value, dtype=np.uint8), 1)
139
+ if img is None:
140
+ raise IOError('cv2.imdecode failed')
141
+ img = img[:, :, ::-1] # BGR => RGB
142
+ except IOError:
143
+ img = np.array(PIL.Image.open(io.BytesIO(value)))
144
+ yield dict(img=img, label=None)
145
+ if idx >= max_idx-1:
146
+ break
147
+ except:
148
+ print(sys.exc_info()[1])
149
+
150
+ return max_idx, iterate_images()
151
+
152
+ #----------------------------------------------------------------------------
153
+
154
+ def open_cifar10(tarball: str, *, max_images: Optional[int]):
155
+ images = []
156
+ labels = []
157
+
158
+ with tarfile.open(tarball, 'r:gz') as tar:
159
+ for batch in range(1, 6):
160
+ member = tar.getmember(f'cifar-10-batches-py/data_batch_{batch}')
161
+ with tar.extractfile(member) as file:
162
+ data = pickle.load(file, encoding='latin1')
163
+ images.append(data['data'].reshape(-1, 3, 32, 32))
164
+ labels.append(data['labels'])
165
+
166
+ images = np.concatenate(images)
167
+ labels = np.concatenate(labels)
168
+ images = images.transpose([0, 2, 3, 1]) # NCHW -> NHWC
169
+ assert images.shape == (50000, 32, 32, 3) and images.dtype == np.uint8
170
+ assert labels.shape == (50000,) and labels.dtype in [np.int32, np.int64]
171
+ assert np.min(images) == 0 and np.max(images) == 255
172
+ assert np.min(labels) == 0 and np.max(labels) == 9
173
+
174
+ max_idx = maybe_min(len(images), max_images)
175
+
176
+ def iterate_images():
177
+ for idx, img in enumerate(images):
178
+ yield dict(img=img, label=int(labels[idx]))
179
+ if idx >= max_idx-1:
180
+ break
181
+
182
+ return max_idx, iterate_images()
183
+
184
+ #----------------------------------------------------------------------------
185
+
186
+ def open_mnist(images_gz: str, *, max_images: Optional[int]):
187
+ labels_gz = images_gz.replace('-images-idx3-ubyte.gz', '-labels-idx1-ubyte.gz')
188
+ assert labels_gz != images_gz
189
+ images = []
190
+ labels = []
191
+
192
+ with gzip.open(images_gz, 'rb') as f:
193
+ images = np.frombuffer(f.read(), np.uint8, offset=16)
194
+ with gzip.open(labels_gz, 'rb') as f:
195
+ labels = np.frombuffer(f.read(), np.uint8, offset=8)
196
+
197
+ images = images.reshape(-1, 28, 28)
198
+ images = np.pad(images, [(0,0), (2,2), (2,2)], 'constant', constant_values=0)
199
+ assert images.shape == (60000, 32, 32) and images.dtype == np.uint8
200
+ assert labels.shape == (60000,) and labels.dtype == np.uint8
201
+ assert np.min(images) == 0 and np.max(images) == 255
202
+ assert np.min(labels) == 0 and np.max(labels) == 9
203
+
204
+ max_idx = maybe_min(len(images), max_images)
205
+
206
+ def iterate_images():
207
+ for idx, img in enumerate(images):
208
+ yield dict(img=img, label=int(labels[idx]))
209
+ if idx >= max_idx-1:
210
+ break
211
+
212
+ return max_idx, iterate_images()
213
+
214
+ #----------------------------------------------------------------------------
215
+
216
+ def make_transform(
217
+ transform: Optional[str],
218
+ output_width: Optional[int],
219
+ output_height: Optional[int]
220
+ ) -> Callable[[np.ndarray], Optional[np.ndarray]]:
221
+ def scale(width, height, img):
222
+ w = img.shape[1]
223
+ h = img.shape[0]
224
+ if width == w and height == h:
225
+ return img
226
+ img = PIL.Image.fromarray(img)
227
+ ww = width if width is not None else w
228
+ hh = height if height is not None else h
229
+ img = img.resize((ww, hh), PIL.Image.LANCZOS)
230
+ return np.array(img)
231
+
232
+ def center_crop(width, height, img):
233
+ crop = np.min(img.shape[:2])
234
+ img = img[(img.shape[0] - crop) // 2 : (img.shape[0] + crop) // 2, (img.shape[1] - crop) // 2 : (img.shape[1] + crop) // 2]
235
+ img = PIL.Image.fromarray(img, 'RGB')
236
+ img = img.resize((width, height), PIL.Image.LANCZOS)
237
+ return np.array(img)
238
+
239
+ def center_crop_wide(width, height, img):
240
+ ch = int(np.round(width * img.shape[0] / img.shape[1]))
241
+ if img.shape[1] < width or ch < height:
242
+ return None
243
+
244
+ img = img[(img.shape[0] - ch) // 2 : (img.shape[0] + ch) // 2]
245
+ img = PIL.Image.fromarray(img, 'RGB')
246
+ img = img.resize((width, height), PIL.Image.LANCZOS)
247
+ img = np.array(img)
248
+
249
+ canvas = np.zeros([width, width, 3], dtype=np.uint8)
250
+ canvas[(width - height) // 2 : (width + height) // 2, :] = img
251
+ return canvas
252
+
253
+ if transform is None:
254
+ return functools.partial(scale, output_width, output_height)
255
+ if transform == 'center-crop':
256
+ if (output_width is None) or (output_height is None):
257
+ error ('must specify --resolution=WxH when using ' + transform + 'transform')
258
+ return functools.partial(center_crop, output_width, output_height)
259
+ if transform == 'center-crop-wide':
260
+ if (output_width is None) or (output_height is None):
261
+ error ('must specify --resolution=WxH when using ' + transform + ' transform')
262
+ return functools.partial(center_crop_wide, output_width, output_height)
263
+ assert False, 'unknown transform'
264
+
265
+ #----------------------------------------------------------------------------
266
+
267
+ def open_dataset(source, *, max_images: Optional[int]):
268
+ if os.path.isdir(source):
269
+ if source.rstrip('/').endswith('_lmdb'):
270
+ return open_lmdb(source, max_images=max_images)
271
+ else:
272
+ return open_image_folder(source, max_images=max_images)
273
+ elif os.path.isfile(source):
274
+ if os.path.basename(source) == 'cifar-10-python.tar.gz':
275
+ return open_cifar10(source, max_images=max_images)
276
+ elif os.path.basename(source) == 'train-images-idx3-ubyte.gz':
277
+ return open_mnist(source, max_images=max_images)
278
+ elif file_ext(source) == 'zip':
279
+ return open_image_zip(source, max_images=max_images)
280
+ else:
281
+ assert False, 'unknown archive type'
282
+ else:
283
+ error(f'Missing input file or directory: {source}')
284
+
285
+ #----------------------------------------------------------------------------
286
+
287
+ def open_dest(dest: str) -> Tuple[str, Callable[[str, Union[bytes, str]], None], Callable[[], None]]:
288
+ dest_ext = file_ext(dest)
289
+
290
+ if dest_ext == 'zip':
291
+ if os.path.dirname(dest) != '':
292
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
293
+ zf = zipfile.ZipFile(file=dest, mode='w', compression=zipfile.ZIP_STORED)
294
+ def zip_write_bytes(fname: str, data: Union[bytes, str]):
295
+ zf.writestr(fname, data)
296
+ return '', zip_write_bytes, zf.close
297
+ else:
298
+ # If the output folder already exists, check that is is
299
+ # empty.
300
+ #
301
+ # Note: creating the output directory is not strictly
302
+ # necessary as folder_write_bytes() also mkdirs, but it's better
303
+ # to give an error message earlier in case the dest folder
304
+ # somehow cannot be created.
305
+ if os.path.isdir(dest) and len(os.listdir(dest)) != 0:
306
+ error('--dest folder must be empty')
307
+ os.makedirs(dest, exist_ok=True)
308
+
309
+ def folder_write_bytes(fname: str, data: Union[bytes, str]):
310
+ os.makedirs(os.path.dirname(fname), exist_ok=True)
311
+ with open(fname, 'wb') as fout:
312
+ if isinstance(data, str):
313
+ data = data.encode('utf8')
314
+ fout.write(data)
315
+ return dest, folder_write_bytes, lambda: None
316
+
317
+ #----------------------------------------------------------------------------
318
+
319
+ @click.command()
320
+ @click.pass_context
321
+ @click.option('--source', help='Directory or archive name for input dataset', required=True, metavar='PATH')
322
+ @click.option('--dest', help='Output directory or archive name for output dataset', required=True, metavar='PATH')
323
+ @click.option('--max-images', help='Output only up to `max-images` images', type=int, default=None)
324
+ @click.option('--transform', help='Input crop/resize mode', type=click.Choice(['center-crop', 'center-crop-wide']))
325
+ @click.option('--resolution', help='Output resolution (e.g., \'512x512\')', metavar='WxH', type=parse_tuple)
326
+ def convert_dataset(
327
+ ctx: click.Context,
328
+ source: str,
329
+ dest: str,
330
+ max_images: Optional[int],
331
+ transform: Optional[str],
332
+ resolution: Optional[Tuple[int, int]]
333
+ ):
334
+ """Convert an image dataset into a dataset archive usable with StyleGAN2 ADA PyTorch.
335
+
336
+ The input dataset format is guessed from the --source argument:
337
+
338
+ \b
339
+ --source *_lmdb/ Load LSUN dataset
340
+ --source cifar-10-python.tar.gz Load CIFAR-10 dataset
341
+ --source train-images-idx3-ubyte.gz Load MNIST dataset
342
+ --source path/ Recursively load all images from path/
343
+ --source dataset.zip Recursively load all images from dataset.zip
344
+
345
+ Specifying the output format and path:
346
+
347
+ \b
348
+ --dest /path/to/dir Save output files under /path/to/dir
349
+ --dest /path/to/dataset.zip Save output files into /path/to/dataset.zip
350
+
351
+ The output dataset format can be either an image folder or an uncompressed zip archive.
352
+ Zip archives makes it easier to move datasets around file servers and clusters, and may
353
+ offer better training performance on network file systems.
354
+
355
+ Images within the dataset archive will be stored as uncompressed PNG.
356
+ Uncompresed PNGs can be efficiently decoded in the training loop.
357
+
358
+ Class labels are stored in a file called 'dataset.json' that is stored at the
359
+ dataset root folder. This file has the following structure:
360
+
361
+ \b
362
+ {
363
+ "labels": [
364
+ ["00000/img00000000.png",6],
365
+ ["00000/img00000001.png",9],
366
+ ... repeated for every image in the datase
367
+ ["00049/img00049999.png",1]
368
+ ]
369
+ }
370
+
371
+ If the 'dataset.json' file cannot be found, the dataset is interpreted as
372
+ not containing class labels.
373
+
374
+ Image scale/crop and resolution requirements:
375
+
376
+ Output images must be square-shaped and they must all have the same power-of-two
377
+ dimensions.
378
+
379
+ To scale arbitrary input image size to a specific width and height, use the
380
+ --resolution option. Output resolution will be either the original
381
+ input resolution (if resolution was not specified) or the one specified with
382
+ --resolution option.
383
+
384
+ Use the --transform=center-crop or --transform=center-crop-wide options to apply a
385
+ center crop transform on the input image. These options should be used with the
386
+ --resolution option. For example:
387
+
388
+ \b
389
+ python dataset_tool.py --source LSUN/raw/cat_lmdb --dest /tmp/lsun_cat \\
390
+ --transform=center-crop-wide --resolution=512x384
391
+ """
392
+
393
+ PIL.Image.init() # type: ignore
394
+
395
+ if dest == '':
396
+ ctx.fail('--dest output filename or directory must not be an empty string')
397
+
398
+ num_files, input_iter = open_dataset(source, max_images=max_images)
399
+ archive_root_dir, save_bytes, close_dest = open_dest(dest)
400
+
401
+ if resolution is None: resolution = (None, None)
402
+ transform_image = make_transform(transform, *resolution)
403
+
404
+ dataset_attrs = None
405
+
406
+ labels = []
407
+ for idx, image in tqdm(enumerate(input_iter), total=num_files):
408
+ idx_str = f'{idx:08d}'
409
+ archive_fname = f'{idx_str[:5]}/img{idx_str}.png'
410
+
411
+ # Apply crop and resize.
412
+ img = transform_image(image['img'])
413
+
414
+ # Transform may drop images.
415
+ if img is None:
416
+ continue
417
+
418
+ if img.ndim == 2:
419
+ img = np.stack([img] * 3, axis=-1)
420
+
421
+ # Error check to require uniform image attributes across
422
+ # the whole dataset.
423
+ channels = img.shape[2] if img.ndim == 3 else 1
424
+ cur_image_attrs = {
425
+ 'width': img.shape[1],
426
+ 'height': img.shape[0],
427
+ 'channels': channels
428
+ }
429
+ if dataset_attrs is None:
430
+ dataset_attrs = cur_image_attrs
431
+ width = dataset_attrs['width']
432
+ height = dataset_attrs['height']
433
+ if width != height:
434
+ error(f'Image dimensions after scale and crop are required to be square. Got {width}x{height}')
435
+ if dataset_attrs['channels'] not in [1, 3]:
436
+ error('Input images must be stored as RGB or grayscale')
437
+ # if width != 2 ** int(np.floor(np.log2(width))):
438
+ # error('Image width/height after scale and crop are required to be power-of-two')
439
+ elif dataset_attrs != cur_image_attrs:
440
+ err = [f' dataset {k}/cur image {k}: {dataset_attrs[k]}/{cur_image_attrs[k]}' for k in dataset_attrs.keys()] # pylint: disable=unsubscriptable-object
441
+ error(f'Image {archive_fname} attributes must be equal across all images of the dataset. Got:\n' + '\n'.join(err))
442
+
443
+ # Save the image as an uncompressed PNG.
444
+ img = PIL.Image.fromarray(img, { 1: 'L', 3: 'RGB' }[channels])
445
+ image_bits = io.BytesIO()
446
+ img.save(image_bits, format='png', compress_level=0, optimize=False)
447
+ save_bytes(os.path.join(archive_root_dir, archive_fname), image_bits.getbuffer())
448
+ labels.append([archive_fname, image['label']] if image['label'] is not None else None)
449
+
450
+ metadata = {
451
+ 'labels': labels if all(x is not None for x in labels) else None
452
+ }
453
+ save_bytes(os.path.join(archive_root_dir, 'dataset.json'), json.dumps(metadata))
454
+ close_dest()
455
+
456
+ #----------------------------------------------------------------------------
457
+
458
+ if __name__ == "__main__":
459
+ convert_dataset() # pylint: disable=no-value-for-parameter