download.py 13.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#   Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import os.path as osp
import shutil
import requests
import tqdm
import hashlib
D
dengkaipeng 已提交
25 26
import binascii
import base64
27 28 29
import tarfile
import zipfile

K
Kaipeng Deng 已提交
30
from .voc_utils import create_list
31 32 33 34

import logging
logger = logging.getLogger(__name__)

35 36 37 38
__all__ = [
    'get_weights_path', 'get_dataset_path', 'download_dataset',
    'create_voc_list'
]
39 40 41 42

WEIGHTS_HOME = osp.expanduser("~/.cache/paddle/weights")
DATASET_HOME = osp.expanduser("~/.cache/paddle/dataset")

K
Kaipeng Deng 已提交
43
# dict of {dataset_name: (download_info, sub_dirs)}
K
Kaipeng Deng 已提交
44
# download info: [(url, md5sum)]
45 46
DATASETS = {
    'coco': ([
W
wangguanzhong 已提交
47 48 49 50 51 52 53 54 55
        (
            'http://images.cocodataset.org/zips/train2017.zip',
            'cced6f7f71b7629ddf16f17bbcfab6b2', ),
        (
            'http://images.cocodataset.org/zips/val2017.zip',
            '442b8da7639aecaf257c1dceb8ba8c80', ),
        (
            'http://images.cocodataset.org/annotations/annotations_trainval2017.zip',
            'f4bbac642086de4f52a3fdda2de5fa2c', ),
56 57
    ], ["annotations", "train2017", "val2017"]),
    'voc': ([
W
wangguanzhong 已提交
58 59 60 61 62 63 64 65 66
        (
            'http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar',
            '6cd6e144f989b92b3379bac3b3de84fd', ),
        (
            'http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtrainval_06-Nov-2007.tar',
            'c52e279531787c972589f7e41ab4ae64', ),
        (
            'http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtest_06-Nov-2007.tar',
            'b6e924de25625d8de591ea690078ad9f', ),
K
Kaipeng Deng 已提交
67
    ], ["VOCdevkit/VOC2012", "VOCdevkit/VOC2007"]),
G
Guanghua Yu 已提交
68 69 70 71 72 73 74 75 76 77 78
    'wider_face': ([
        (
            'https://dataset.bj.bcebos.com/wider_face/WIDER_train.zip',
            '3fedf70df600953d25982bcd13d91ba2', ),
        (
            'https://dataset.bj.bcebos.com/wider_face/WIDER_val.zip',
            'dfa7d7e790efa35df3788964cf0bbaea', ),
        (
            'https://dataset.bj.bcebos.com/wider_face/wider_face_split.zip',
            'a4a898d6193db4b9ef3260a68bad0dc7', ),
    ], ["WIDER_train", "WIDER_val", "wider_face_split"]),
W
wangguanzhong 已提交
79
    'fruit': ([(
80 81 82
        'https://dataset.bj.bcebos.com/PaddleDetection_demo/fruit.tar',
        'baa8806617a54ccf3685fa7153388ae6', ), ],
              ['Annotations', 'JPEGImages']),
W
wangguanzhong 已提交
83
    'objects365': (),
84 85 86 87 88 89 90 91 92
}

DOWNLOAD_RETRY_LIMIT = 3


def get_weights_path(url):
    """Get weights path from WEIGHT_HOME, if not exists,
    download it from url.
    """
K
Kaipeng Deng 已提交
93 94
    path, _ = get_path(url, WEIGHTS_HOME)
    return path
95 96


97
def get_dataset_path(path, annotation, image_dir):
98 99 100 101 102
    """
    If path exists, return path.
    Otherwise, get dataset path from DATASET_HOME, if not exists,
    download it.
    """
103
    if _dataset_exists(path, annotation, image_dir):
104 105
        return path

K
Kaipeng Deng 已提交
106
    logger.info("Dataset {} is not valid for reason above, try searching {} or "
107 108 109
                "downloading dataset...".format(
                    osp.realpath(path), DATASET_HOME))

110
    data_name = os.path.split(path.strip().lower())[-1]
111
    for name, dataset in DATASETS.items():
112
        if data_name == name:
Y
Yang Zhang 已提交
113 114
            logger.debug("Parse dataset_dir {} as dataset "
                         "{}".format(path, name))
W
wangguanzhong 已提交
115 116
            if name == 'objects365':
                raise NotImplementedError(
117 118 119
                    "Dataset {} is not valid for download automatically. "
                    "Please apply and download the dataset from "
                    "https://www.objects365.org/download.html".format(name))
120
            data_dir = osp.join(DATASET_HOME, name)
K
Kaipeng Deng 已提交
121
            # For voc, only check dir VOCdevkit/VOC2012, VOCdevkit/VOC2007
122
            if name == 'voc' or name == 'fruit':
K
Kaipeng Deng 已提交
123 124 125 126 127 128 129 130
                exists = True
                for sub_dir in dataset[1]:
                    check_dir = osp.join(data_dir, sub_dir)
                    if osp.exists(check_dir):
                        logger.info("Found {}".format(check_dir))
                    else:
                        exists = False
                if exists:
131 132
                    return data_dir

K
Kaipeng Deng 已提交
133
            # voc exist is checked above, voc is not exist here
134
            check_exist = name != 'voc' and name != 'fruit'
135
            for url, md5sum in dataset[0]:
K
Kaipeng Deng 已提交
136
                get_path(url, data_dir, md5sum, check_exist)
137

K
Kaipeng Deng 已提交
138
            # voc should create list after download
139
            if name == 'voc':
K
Kaipeng Deng 已提交
140
                create_voc_list(data_dir)
141 142 143
            return data_dir

    # not match any dataset in DATASETS
K
Kaipeng Deng 已提交
144 145
    raise ValueError("Dataset {} is not valid and cannot parse dataset type "
                     "'{}' for automaticly downloading, which only supports "
W
wangguanzhong 已提交
146 147
                     "'voc' , 'coco', 'wider_face' and 'fruit' currently".
                     format(path, osp.split(path)[-1]))
148 149


K
Kaipeng Deng 已提交
150
def create_voc_list(data_dir, devkit_subdir='VOCdevkit'):
Y
Yang Zhang 已提交
151
    logger.debug("Create voc file list...")
K
Kaipeng Deng 已提交
152
    devkit_dir = osp.join(data_dir, devkit_subdir)
153
    year_dirs = [osp.join(devkit_dir, x) for x in os.listdir(devkit_dir)]
K
Kaipeng Deng 已提交
154

K
Kaipeng Deng 已提交
155 156 157
    # NOTE: since using auto download VOC
    # dataset, VOC default label list should be used, 
    # do not generate label_list.txt here. For default
158
    # label, see ../data/source/voc.py
159
    create_list(year_dirs, data_dir)
Y
Yang Zhang 已提交
160
    logger.debug("Create voc file list finished")
K
Kaipeng Deng 已提交
161 162


163 164
def map_path(url, root_dir):
    # parse path after download to decompress under root_dir
165
    fname = osp.split(url)[-1]
166 167 168 169 170 171 172
    zip_formats = ['.zip', '.tar', '.gz']
    fpath = fname
    for zip_format in zip_formats:
        fpath = fpath.replace(zip_format, '')
    return osp.join(root_dir, fpath)


K
Kaipeng Deng 已提交
173
def get_path(url, root_dir, md5sum=None, check_exist=True):
174 175 176 177 178 179 180 181 182 183 184
    """ Download from given url to root_dir.
    if file or directory specified by url is exists under
    root_dir, return the path directly, otherwise download
    from url and decompress it, return the path.

    url (str): download url
    root_dir (str): root dir for downloading, it should be
                    WEIGHTS_HOME or DATASET_HOME
    md5sum (str): md5 sum of download package
    """
    # parse path after download to decompress under root_dir
185
    fullpath = map_path(url, root_dir)
186 187 188 189

    # For same zip file, decompressed directory name different
    # from zip file name, rename by following map
    decompress_name_map = {
K
Kaipeng Deng 已提交
190 191 192
        "VOCtrainval_11-May-2012": "VOCdevkit/VOC2012",
        "VOCtrainval_06-Nov-2007": "VOCdevkit/VOC2007",
        "VOCtest_06-Nov-2007": "VOCdevkit/VOC2007",
193 194 195 196
        "annotations_trainval": "annotations"
    }
    for k, v in decompress_name_map.items():
        if fullpath.find(k) >= 0:
197
            fullpath = osp.join(osp.split(fullpath)[0], v)
198

K
Kaipeng Deng 已提交
199 200 201
    exist_flag = False
    if osp.exists(fullpath) and check_exist:
        exist_flag = True
Y
Yang Zhang 已提交
202
        logger.debug("Found {}".format(fullpath))
203
    else:
K
Kaipeng Deng 已提交
204
        exist_flag = False
205
        fullname = _download(url, root_dir, md5sum)
K
Kaipeng Deng 已提交
206 207 208 209 210

        # new weights format which postfix is 'pdparams' not
        # need to decompress
        if osp.splitext(fullname)[-1] != '.pdparams':
            _decompress(fullname)
211

K
Kaipeng Deng 已提交
212
    return fullpath, exist_flag
213 214


K
Kaipeng Deng 已提交
215 216 217 218 219 220 221
def download_dataset(path, dataset=None):
    if dataset not in DATASETS.keys():
        logger.error("Unknown dataset {}, it should be "
                     "{}".format(dataset, DATASETS.keys()))
        return
    dataset_info = DATASETS[dataset][0]
    for info in dataset_info:
K
Kaipeng Deng 已提交
222
        get_path(info[0], path, info[1], False)
Y
Yang Zhang 已提交
223
    logger.debug("Download dataset {} finished.".format(dataset))
K
Kaipeng Deng 已提交
224 225


226
def _dataset_exists(path, annotation, image_dir):
227 228 229 230
    """
    Check if user define dataset exists
    """
    if not osp.exists(path):
Y
Yang Zhang 已提交
231 232
        logger.debug("Config dataset_dir {} is not exits, "
                     "dataset config is not valid".format(path))
233 234
        return False

235 236 237
    if annotation:
        annotation_path = osp.join(path, annotation)
        if not osp.isfile(annotation_path):
Y
Yang Zhang 已提交
238 239 240
            logger.debug("Config annotation {} is not a "
                         "file, dataset config is not "
                         "valid".format(annotation_path))
241 242 243 244
            return False
    if image_dir:
        image_path = osp.join(path, image_dir)
        if not osp.isdir(image_path):
Y
Yang Zhang 已提交
245 246 247
            logger.warning("Config image_dir {} is not a "
                           "directory, dataset config is not "
                           "valid".format(image_path))
248
            return False
249 250 251 252 253 254 255 256 257 258 259 260 261
    return True


def _download(url, path, md5sum=None):
    """
    Download from url, save to path.

    url (str): download url
    path (str): download to given path
    """
    if not osp.exists(path):
        os.makedirs(path)

262
    fname = osp.split(url)[-1]
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    fullname = osp.join(path, fname)
    retry_cnt = 0

    while not (osp.exists(fullname) and _md5check(fullname, md5sum)):
        if retry_cnt < DOWNLOAD_RETRY_LIMIT:
            retry_cnt += 1
        else:
            raise RuntimeError("Download from {} failed. "
                               "Retry limit reached".format(url))

        logger.info("Downloading {} from {}".format(fname, url))

        req = requests.get(url, stream=True)
        if req.status_code != 200:
            raise RuntimeError("Downloading from {} failed with code "
                               "{}!".format(url, req.status_code))

K
Kaipeng Deng 已提交
280 281 282 283
        # For protecting download interupted, download to
        # tmp_fullname firstly, move tmp_fullname to fullname
        # after download finished
        tmp_fullname = fullname + "_tmp"
284
        total_size = req.headers.get('content-length')
K
Kaipeng Deng 已提交
285
        with open(tmp_fullname, 'wb') as f:
286 287 288 289 290 291 292 293 294 295 296
            if total_size:
                for chunk in tqdm.tqdm(
                        req.iter_content(chunk_size=1024),
                        total=(int(total_size) + 1023) // 1024,
                        unit='KB'):
                    f.write(chunk)
            else:
                for chunk in req.iter_content(chunk_size=1024):
                    if chunk:
                        f.write(chunk)

D
dengkaipeng 已提交
297 298 299 300 301 302 303 304 305 306 307 308
        # check md5 after download in Content-MD5 in req.headers
        content_md5 = req.headers.get('content-md5')
        if not content_md5 or _md5check(
                tmp_fullname,
                binascii.hexlify(base64.b64decode(content_md5.strip('"')))):
            shutil.move(tmp_fullname, fullname)
            return fullname
        else:
            logger.warn(
                "Download from url imcomplete, try downloading again...")
            os.remove(tmp_fullname)
            continue
309 310 311 312 313 314


def _md5check(fullname, md5sum=None):
    if md5sum is None:
        return True

Y
Yang Zhang 已提交
315
    logger.debug("File {} md5 checking...".format(fullname))
316 317 318 319 320 321 322
    md5 = hashlib.md5()
    with open(fullname, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b""):
            md5.update(chunk)
    calc_md5sum = md5.hexdigest()

    if calc_md5sum != md5sum:
Y
Yang Zhang 已提交
323 324
        logger.warning("File {} md5 check failed, {}(calc) != "
                       "{}(base)".format(fullname, calc_md5sum, md5sum))
325 326 327 328 329 330 331 332 333 334 335 336 337 338
        return False
    return True


def _decompress(fname):
    """
    Decompress for zip and tar file
    """
    logger.info("Decompressing {}...".format(fname))

    # For protecting decompressing interupted,
    # decompress to fpath_tmp directory firstly, if decompress
    # successed, move decompress files to fpath and delete
    # fpath_tmp and remove download compress file.
339
    fpath = osp.split(fname)[0]
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
    fpath_tmp = osp.join(fpath, 'tmp')
    if osp.isdir(fpath_tmp):
        shutil.rmtree(fpath_tmp)
        os.makedirs(fpath_tmp)

    if fname.find('tar') >= 0:
        with tarfile.open(fname) as tf:
            tf.extractall(path=fpath_tmp)
    elif fname.find('zip') >= 0:
        with zipfile.ZipFile(fname) as zf:
            zf.extractall(path=fpath_tmp)
    else:
        raise TypeError("Unsupport compress file type {}".format(fname))

    for f in os.listdir(fpath_tmp):
        src_dir = osp.join(fpath_tmp, f)
        dst_dir = osp.join(fpath, f)
        _move_and_merge_tree(src_dir, dst_dir)

    shutil.rmtree(fpath_tmp)
    os.remove(fname)


def _move_and_merge_tree(src, dst):
    """
G
Guanghua Yu 已提交
365
    Move src directory to dst, if dst is already exists,
366 367 368 369
    merge src to dst
    """
    if not osp.exists(dst):
        shutil.move(src, dst)
370 371
    elif osp.isfile(src):
        shutil.move(src, dst)
372 373 374 375 376 377 378 379 380 381 382 383
    else:
        for fp in os.listdir(src):
            src_fp = osp.join(src, fp)
            dst_fp = osp.join(dst, fp)
            if osp.isdir(src_fp):
                if osp.isdir(dst_fp):
                    _move_and_merge_tree(src_fp, dst_fp)
                else:
                    shutil.move(src_fp, dst_fp)
            elif osp.isfile(src_fp) and \
                    not osp.isfile(dst_fp):
                shutil.move(src_fp, dst_fp)