utils.py 925 Bytes
Newer Older
soumith's avatar
soumith committed
1
2
3
4
import os
import hashlib
import errno

5
6
7
def check_integrity(fpath, md5):
    if not os.path.isfile(fpath):
        return False
soumith's avatar
soumith committed
8
9
10
11
12
13
    md5o = hashlib.md5()
    with open(fpath,'rb') as f:
        # read in 1MB chunks
        for chunk in iter(lambda: f.read(1024 * 1024 * 1024), b''):
            md5o.update(chunk)
    md5c = md5o.hexdigest()
14
15
16
17
18
    if md5c != md5:
        return False
    return True


soumith's avatar
soumith committed
19
def download_url(url, root, filename, md5=None):
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    from six.moves import urllib

    fpath = os.path.join(root, filename)

    try:
        os.makedirs(root)
    except OSError as e:
        if e.errno == errno.EEXIST:
            pass
        else:
            raise

    # downloads file
    if os.path.isfile(fpath) and check_integrity(fpath, md5):
        print('Using downloaded and verified file: ' + fpath)
    else:
        print('Downloading ' + url + ' to ' + fpath)
        urllib.request.urlretrieve(url, fpath)