This repository has been archived by the owner on Nov 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
build_data.py
711 lines (592 loc) · 24 KB
/
build_data.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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Utilities for downloading and building data.
These can be replaced if your particular file system does not support them.
"""
import importlib
import json
import time
import datetime
import os
import requests
import shutil
import hashlib
import tqdm
import gzip
import math
import contextlib
import parlai.utils.logging as logging
from parlai.utils.io import PathManager
try:
from torch.multiprocessing import Pool
except ImportError:
from multiprocessing import Pool
try:
# internal infra requires special attention to use http sessions
from parlai_fb import get_http_session
except (ImportError, AttributeError):
@contextlib.contextmanager
def get_http_session():
with requests.Session() as session:
yield session
class DownloadableFile:
"""
A class used to abstract any file that has to be downloaded online.
Any task that needs to download a file needs to have a list RESOURCES
that have objects of this class as elements.
This class provides the following functionality:
- Download a file from a URL / Google Drive
- Untar the file if zipped
- Checksum for the downloaded file
- Send HEAD request to validate URL or Google Drive link
An object of this class needs to be created with:
- url <string> : URL or Google Drive id to download from
- file_name <string> : File name that the file should be named
- hashcode <string> : SHA256 hashcode of the downloaded file
- zipped <boolean> : False if the file is not compressed
- from_google <boolean> : True if the file is from Google Drive
"""
def __init__(self, url, file_name, hashcode, zipped=True, from_google=False):
self.url = url
self.file_name = file_name
self.hashcode = hashcode
self.zipped = zipped
self.from_google = from_google
def checksum(self, dpath):
"""
Checksum on a given file.
:param dpath: path to the downloaded file.
"""
sha256_hash = hashlib.sha256()
with PathManager.open(os.path.join(dpath, self.file_name), "rb") as f:
for byte_block in iter(lambda: f.read(65536), b""):
sha256_hash.update(byte_block)
if sha256_hash.hexdigest() != self.hashcode:
# remove_dir(dpath)
raise AssertionError(
f"Checksum for {self.file_name} from \n{self.url}\n"
f"does not match the expected checksum:\n"
f"{sha256_hash.hexdigest()} (received) != {self.hashcode} (expected)\n"
f"\nPlease try again. You may need to manually delete {self.file_name}."
)
else:
logging.debug("Checksum Successful")
def download_file(self, dpath):
if self.from_google:
download_from_google_drive(self.url, os.path.join(dpath, self.file_name))
else:
download(self.url, dpath, self.file_name)
self.checksum(dpath)
if self.zipped:
untar(dpath, self.file_name)
def check_header(self):
"""
Performs a HEAD request to check if the URL / Google Drive ID is live.
"""
with get_http_session() as session:
if self.from_google:
URL = 'https://docs.google.com/uc?export=download'
response = session.head(URL, params={'id': self.url}, stream=True)
else:
headers = {
'User-Agent': (
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/77.0.3865.90 Safari/537.36'
)
}
response = session.head(self.url, allow_redirects=True, headers=headers)
status = response.status_code
assert status == 200
def built(path, version_string=None):
"""
Check if '.built' flag has been set for that task.
If a version_string is provided, this has to match, or the version is regarded as
not built.
"""
if version_string:
fname = os.path.join(path, '.built')
if not PathManager.exists(fname):
return False
else:
with PathManager.open(fname, 'r') as read:
text = read.read().split('\n')
return len(text) > 1 and text[1] == version_string
else:
return PathManager.exists(os.path.join(path, '.built'))
def mark_done(path, version_string=None):
"""
Mark this path as prebuilt.
Marks the path as done by adding a '.built' file with the current timestamp
plus a version description string if specified.
:param str path:
The file path to mark as built.
:param str version_string:
The version of this dataset.
"""
with PathManager.open(os.path.join(path, '.built'), 'w') as write:
write.write(str(datetime.datetime.today()))
if version_string:
write.write('\n' + version_string)
def download(url, path, fname, redownload=False, num_retries=5):
"""
Download file using `requests`.
If ``redownload`` is set to false, then will not download tar file again if it is
present (default ``False``).
"""
outfile = os.path.join(path, fname)
download = not PathManager.exists(outfile) or redownload
logging.info(f"Downloading {url} to {outfile}")
retry = num_retries
exp_backoff = [2 ** r for r in reversed(range(retry))]
pbar = tqdm.tqdm(unit='B', unit_scale=True, desc='Downloading {}'.format(fname))
while download and retry > 0:
response = None
with get_http_session() as session:
try:
response = session.get(url, stream=True, timeout=5)
# negative reply could be 'none' or just missing
CHUNK_SIZE = 32768
total_size = int(response.headers.get('Content-Length', -1))
# server returns remaining size if resuming, so adjust total
pbar.total = total_size
done = 0
with PathManager.open(outfile, 'wb') as f:
for chunk in response.iter_content(CHUNK_SIZE):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
if total_size > 0:
done += len(chunk)
if total_size < done:
# don't freak out if content-length was too small
total_size = done
pbar.total = total_size
pbar.update(len(chunk))
break
except (
requests.exceptions.ConnectionError,
requests.exceptions.ReadTimeout,
):
retry -= 1
pbar.clear()
if retry > 0:
pl = 'y' if retry == 1 else 'ies'
logging.debug(
f'Connection error, retrying. ({retry} retr{pl} left)'
)
time.sleep(exp_backoff[retry])
else:
logging.error('Retried too many times, stopped retrying.')
finally:
if response:
response.close()
if retry <= 0:
raise RuntimeError('Connection broken too many times. Stopped retrying.')
if download and retry > 0:
pbar.update(done - pbar.n)
if done < total_size:
raise RuntimeError(
f'Received less data than specified in Content-Length header for '
f'{url}. There may be a download problem.'
)
pbar.close()
def make_dir(path):
"""
Make the directory and any nonexistent parent directories (`mkdir -p`).
"""
# the current working directory is a fine path
if path != '':
PathManager.mkdirs(path)
def remove_dir(path):
"""
Remove the given directory, if it exists.
"""
shutil.rmtree(path, ignore_errors=True)
def untar(path, fname, delete=True, flatten_tar=False):
"""
Unpack the given archive file to the same directory.
:param str path:
The folder containing the archive. Will contain the contents.
:param str fname:
The filename of the archive file.
:param bool delete:
If true, the archive will be deleted after extraction.
"""
if ".zip" in fname:
return _unzip(path, fname, delete=delete)
else:
return _untar(path, fname, delete=delete, flatten=flatten_tar)
def _untar(path, fname, delete=True, flatten=False):
"""
Unpack the given archive file to the same directory.
:param str path:
The folder containing the archive. Will contain the contents.
:param str fname:
The filename of the archive file.
:param bool delete:
If true, the archive will be deleted after extraction.
"""
import tarfile
logging.debug(f'unpacking {fname}')
fullpath = os.path.join(path, fname)
# very painfully manually extract files so that we can use PathManger.open
# instead, lest we are using fb internal file services
with tarfile.open(fileobj=PathManager.open(fullpath, 'rb')) as tf:
for item in tf:
item_name = item.name
while item_name.startswith("./"):
# internal file systems will actually create a literal "."
# directory, so we gotta watch out for that
item_name = item_name[2:]
if flatten:
# flatten the tar file if there are subdirectories
fn = os.path.join(path, os.path.split(item_name)[-1])
else:
fn = os.path.join(path, item_name)
logging.debug(f"Extracting to {fn}")
if item.isdir():
PathManager.mkdirs(fn)
elif item.isfile():
with PathManager.open(fn, 'wb') as wf, tf.extractfile(item.name) as rf:
tarfile.copyfileobj(rf, wf)
else:
raise NotImplementedError("No support for symlinks etc. right now.")
if delete:
try:
PathManager.rm(fullpath)
except PermissionError:
logging.error(
f"Tried to delete {fullpath} but got a permission error. This "
"is known to happen in Windows and is probably not fatal."
)
def ungzip(path, fname, deleteGZip=True):
"""
Unzips the given gzip compressed file to the same directory.
:param str path:
The folder containing the archive. Will contain the contents.
:param str fname:
The filename of the archive file.
:param bool deleteGZip:
If true, the compressed file will be deleted after extraction.
"""
def _get_output_filename(input_fname):
GZIP_EXTENSIONS = ('.gz', '.gzip', '.tgz', '.tar')
for ext in GZIP_EXTENSIONS:
if input_fname.endswith(ext):
return input_fname[: -len(ext)]
return f'{input_fname}_unzip'
logging.debug(f'unzipping {fname}')
fullpath = os.path.join(path, fname)
with gzip.open(PathManager.open(fullpath, 'rb'), 'r') as fin, PathManager.open(
_get_output_filename(fullpath), 'wb'
) as fout:
shutil.copyfileobj(fin, fout)
if deleteGZip:
os.remove(fullpath)
def _unzip(path, fname, delete=True):
"""
Unpack the given zip file to the same directory.
:param str path:
The folder containing the archive. Will contain the contents.
:param str fname:
The filename of the archive file.
:param bool delete:
If true, the archive will be deleted after extraction.
"""
import zipfile
logging.debug(f'unpacking {fname}')
fullpath = os.path.join(path, fname)
with zipfile.ZipFile(PathManager.open(fullpath, 'rb'), 'r') as zf:
for member in zf.namelist():
outpath = os.path.join(path, member)
if zf.getinfo(member).is_dir():
logging.debug(f"Making directory {outpath}")
PathManager.mkdirs(outpath)
continue
logging.debug(f"Extracting to {outpath}")
with zf.open(member, 'r') as inf, PathManager.open(outpath, 'wb') as outf:
shutil.copyfileobj(inf, outf)
if delete:
try:
PathManager.rm(fullpath)
except PermissionError:
logging.error(
f"Tried to delete {fullpath} but got a permission error. This "
"is known to happen in Windows and is probably not fatal."
)
def _get_confirm_token(response):
for key, value in response.cookies.items():
if key.startswith('download_warning'):
return value
return None
def download_from_google_drive(gd_id, destination):
"""
Use the requests package to download a file from Google Drive.
"""
URL = 'https://docs.google.com/uc?export=download'
with get_http_session() as session:
response = session.get(URL, params={'id': gd_id}, stream=True)
token = _get_confirm_token(response) or 't'
if token:
response.close()
params = {'id': gd_id, 'confirm': token}
response = session.get(URL, params=params, stream=True)
CHUNK_SIZE = 32768
with PathManager.open(destination, 'wb') as f:
for chunk in response.iter_content(CHUNK_SIZE):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
response.close()
def get_model_dir(datapath):
return os.path.join(datapath, 'models')
def download_models(
opt,
fnames,
model_folder,
version='v1.0',
path='aws',
use_model_type=False,
flatten_tar=False,
):
"""
Download models into the ParlAI model zoo from a url.
:param fnames: list of filenames to download
:param model_folder: models will be downloaded into models/model_folder/model_type
:param path: url for downloading models; defaults to downloading from AWS
:param use_model_type: whether models are categorized by type in AWS
"""
model_type = opt.get('model_type', None)
if model_type is not None:
dpath = os.path.join(opt['datapath'], 'models', model_folder, model_type)
else:
dpath = os.path.join(opt['datapath'], 'models', model_folder)
if not built(dpath, version):
for fname in fnames:
logging.info(f'building data: {dpath}/{fname}')
if built(dpath):
# An older version exists, so remove these outdated files.
remove_dir(dpath)
make_dir(dpath)
# Download the data.
for fname in fnames:
if path == 'aws':
url = 'http://parl.ai/downloads/_models/'
url += model_folder + '/'
if use_model_type:
url += model_type + '/'
url += fname
else:
url = path + '/' + fname
download(url, dpath, fname)
if '.tgz' in fname or '.gz' in fname or '.zip' in fname:
untar(dpath, fname, flatten_tar=flatten_tar)
# Mark the data as built.
mark_done(dpath, version)
def modelzoo_path(datapath, path):
"""
Map pretrain models filenames to their path on disk.
If path starts with 'models:', then we remap it to the model zoo path within the
data directory (default is ParlAI/data/models). We download models from the model
zoo if they are not here yet.
"""
if path is None:
return None
if (
not path.startswith('models:')
and not path.startswith('zoo:')
and not path.startswith('izoo:')
):
return path
elif path.startswith('models:') or path.startswith('zoo:'):
zoo = path.split(':')[0]
zoo_len = len(zoo) + 1
model_path = path[zoo_len:]
# Check if we need to download the model
if "/" in path:
animal = path[zoo_len : path.rfind('/')].replace('/', '.')
else:
animal = path[zoo_len:]
if '.' not in animal:
animal += '.build'
module_name = 'parlai.zoo.{}'.format(animal)
try:
my_module = importlib.import_module(module_name)
my_module.download(datapath)
except (ImportError, AttributeError):
try:
# maybe we didn't find a specific model, let's try generic .build
animal_ = '.'.join(animal.split(".")[:-1]) + '.build'
module_name_ = 'parlai.zoo.{}'.format(animal_)
my_module = importlib.import_module(module_name_)
my_module.download(datapath)
except (ImportError, AttributeError) as exc:
# truly give up
raise ImportError(
f'Could not find pretrained model in {module_name} or {module_name_}.'
' Please check your spelling and make sure you\'ve pulled from master.'
) from exc
return os.path.join(datapath, 'models', model_path)
else:
# Internal path (starts with "izoo:") -- useful for non-public
# projects. Save the path to your internal model zoo in
# parlai_internal/.internal_zoo_path
# TODO: test the internal zoo.
zoo_path = 'parlai_internal/zoo/.internal_zoo_path'
if not PathManager.exists('parlai_internal/zoo/.internal_zoo_path'):
raise RuntimeError(
'Please specify the path to your internal zoo in the '
'file parlai_internal/zoo/.internal_zoo_path in your '
'internal repository.'
)
else:
with PathManager.open(zoo_path, 'r') as f:
zoo = f.read().split('\n')[0]
return os.path.join(zoo, path[5:])
def download_multiprocess(
urls, path, num_processes=32, chunk_size=100, dest_filenames=None, error_path=None
):
"""
Download items in parallel (e.g. for an image + dialogue task).
WARNING: may have issues with OS X.
:param urls:
Array of urls to download
:param path:
directory to save items in
:param num_processes:
number of processes to use
:param chunk_size:
chunk size to use
:param dest_filenames:
optional array of same length as url with filenames. Images will be
saved as path + dest_filename
:param error_path:
where to save error logs
:return:
array of tuples of (destination filename, http status code, error
message if any). Note that upon failure, file may not actually be
created.
"""
pbar = tqdm.tqdm(total=len(urls), position=0)
# Resume TODO: isfile() may take too long ?? Should I try in a .tmp file
if dest_filenames:
if len(dest_filenames) != len(urls):
raise Exception(
'If specified, destination filenames must equal url array in length.'
)
else:
def _naming_fn(url, url_metadata=None):
return hashlib.md5(url.encode('utf-8')).hexdigest()
dest_filenames = [_naming_fn(url) for url in urls]
items = zip(urls, dest_filenames)
remaining_items = [
it for it in items if not PathManager.exists(os.path.join(path, it[1]))
]
logging.info(
f'Of {len(urls)} items, {len(urls) - len(remaining_items)} already existed; only going to download {len(remaining_items)} items.'
)
pbar.update(len(urls) - len(remaining_items))
pool_chunks = (
(remaining_items[i : i + chunk_size], path, _download_multiprocess_single)
for i in range(0, len(remaining_items), chunk_size)
)
remaining_chunks_count = math.ceil(float(len(remaining_items) / chunk_size))
logging.info(
f'Going to download {remaining_chunks_count} chunks with {chunk_size} images per chunk using {num_processes} processes.'
)
pbar.desc = 'Downloading'
all_results = []
collected_errors = []
with Pool(num_processes) as pool:
for idx, chunk_result in enumerate(
pool.imap_unordered(_download_multiprocess_map_chunk, pool_chunks, 2)
):
all_results.extend(chunk_result)
for dest_file, http_status_code, error_msg in chunk_result:
if http_status_code != 200:
# msg field available as third item in the tuple
# not using b/c error log file would blow up
collected_errors.append(
{
'dest_file': dest_file,
'status_code': http_status_code,
'error': error_msg,
}
)
logging.error(
f'Bad download - chunk: {idx}, dest_file: {dest_file}, http status code: {http_status_code}, error_msg: {error_msg}'
)
pbar.update(len(chunk_result))
pbar.close()
if error_path:
now = time.strftime("%Y%m%d-%H%M%S")
error_filename = os.path.join(
error_path, 'parlai_download_multiprocess_errors_%s.log' % now
)
with PathManager.open(os.path.join(error_filename), 'w') as error_file:
error_file.write(json.dumps(collected_errors))
logging.error(f'Summary of errors written to {error_filename}')
logging.info(
f'Of {len(remaining_items)} items attempted downloading, '
f'{len(collected_errors)} had errors.'
)
logging.debug('Finished downloading chunks.')
return all_results
def _download_multiprocess_map_chunk(pool_tup):
"""
Helper function for Pool imap_unordered.
Apparently function must be pickable (which apparently means must be
defined at the top level of a module and can't be a lamdba) to be used in
imap_unordered. Has to do with how it's passed to the subprocess.
:param pool_tup: is a tuple where first arg is an array of tuples of url
and dest file name for the current chunk and second arg is function to be
called.
:return: an array of tuples
"""
items = pool_tup[0]
path = pool_tup[1]
fn = pool_tup[2]
return [fn(it[0], path, it[1]) for it in items]
def _download_multiprocess_single(url, path, dest_fname):
"""
Helper function to download an individual item.
Unlike download() above, does not deal with downloading chunks of a big
file, does not support retries (and does not fail if retries are exhausted).
:param url: URL to download from
:param path: directory to save in
:param dest_fname: destination file name of image
:return tuple (dest_fname, http status)
"""
status = None
error_msg = None
try:
# 'User-Agent' header may need to be specified
headers = {}
# Use smaller timeout to skip errors, but can result in failed downloads
response = requests.get(
url, stream=False, timeout=10, allow_redirects=True, headers=headers
)
except Exception as e:
# Likely a timeout during fetching but had an error in requests.get()
status = 500
error_msg = '[Exception during download during fetching] ' + str(e)
return dest_fname, status, error_msg
if response.ok:
try:
with PathManager.open(os.path.join(path, dest_fname), 'wb+') as out_file:
# Some sites respond with gzip transport encoding
response.raw.decode_content = True
out_file.write(response.content)
status = 200
except Exception as e:
# Likely a timeout during download or decoding
status = 500
error_msg = '[Exception during decoding or writing] ' + str(e)
else:
# We get here if there is an HTML error page (i.e. a page saying "404
# not found" or anything else)
status = response.status_code
error_msg = '[Response not OK] Response: %s' % response
return dest_fname, status, error_msg