download.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import os
  18. import os.path as osp
  19. import sys
  20. import yaml
  21. import time
  22. import shutil
  23. import requests
  24. import tqdm
  25. import hashlib
  26. import base64
  27. import binascii
  28. import tarfile
  29. import zipfile
  30. from paddle.utils.download import _get_unique_endpoints
  31. from ppdet.core.workspace import BASE_KEY
  32. from .logger import setup_logger
  33. from .voc_utils import create_list
  34. logger = setup_logger(__name__)
  35. __all__ = [
  36. 'get_weights_path', 'get_dataset_path', 'get_config_path',
  37. 'download_dataset', 'create_voc_list'
  38. ]
  39. WEIGHTS_HOME = osp.expanduser("~/.cache/paddle/weights")
  40. DATASET_HOME = osp.expanduser("~/.cache/paddle/dataset")
  41. CONFIGS_HOME = osp.expanduser("~/.cache/paddle/configs")
  42. # dict of {dataset_name: (download_info, sub_dirs)}
  43. # download info: [(url, md5sum)]
  44. DATASETS = {
  45. 'coco': ([
  46. (
  47. 'http://images.cocodataset.org/zips/train2017.zip',
  48. 'cced6f7f71b7629ddf16f17bbcfab6b2', ),
  49. (
  50. 'http://images.cocodataset.org/zips/val2017.zip',
  51. '442b8da7639aecaf257c1dceb8ba8c80', ),
  52. (
  53. 'http://images.cocodataset.org/annotations/annotations_trainval2017.zip',
  54. 'f4bbac642086de4f52a3fdda2de5fa2c', ),
  55. ], ["annotations", "train2017", "val2017"]),
  56. 'voc': ([
  57. (
  58. 'http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar',
  59. '6cd6e144f989b92b3379bac3b3de84fd', ),
  60. (
  61. 'http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtrainval_06-Nov-2007.tar',
  62. 'c52e279531787c972589f7e41ab4ae64', ),
  63. (
  64. 'http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtest_06-Nov-2007.tar',
  65. 'b6e924de25625d8de591ea690078ad9f', ),
  66. (
  67. 'https://paddledet.bj.bcebos.com/data/label_list.txt',
  68. '5ae5d62183cfb6f6d3ac109359d06a1b', ),
  69. ], ["VOCdevkit/VOC2012", "VOCdevkit/VOC2007"]),
  70. 'wider_face': ([
  71. (
  72. 'https://dataset.bj.bcebos.com/wider_face/WIDER_train.zip',
  73. '3fedf70df600953d25982bcd13d91ba2', ),
  74. (
  75. 'https://dataset.bj.bcebos.com/wider_face/WIDER_val.zip',
  76. 'dfa7d7e790efa35df3788964cf0bbaea', ),
  77. (
  78. 'https://dataset.bj.bcebos.com/wider_face/wider_face_split.zip',
  79. 'a4a898d6193db4b9ef3260a68bad0dc7', ),
  80. ], ["WIDER_train", "WIDER_val", "wider_face_split"]),
  81. 'fruit': ([(
  82. 'https://dataset.bj.bcebos.com/PaddleDetection_demo/fruit.tar',
  83. 'baa8806617a54ccf3685fa7153388ae6', ), ],
  84. ['Annotations', 'JPEGImages']),
  85. 'roadsign_voc': ([(
  86. 'https://paddlemodels.bj.bcebos.com/object_detection/roadsign_voc.tar',
  87. '8d629c0f880dd8b48de9aeff44bf1f3e', ), ], ['annotations', 'images']),
  88. 'roadsign_coco': ([(
  89. 'https://paddlemodels.bj.bcebos.com/object_detection/roadsign_coco.tar',
  90. '49ce5a9b5ad0d6266163cd01de4b018e', ), ], ['annotations', 'images']),
  91. 'spine_coco': ([(
  92. 'https://paddledet.bj.bcebos.com/data/spine_coco.tar',
  93. '7ed69ae73f842cd2a8cf4f58dc3c5535', ), ], ['annotations', 'images']),
  94. 'mot': (),
  95. 'objects365': (),
  96. 'coco_ce': ([(
  97. 'https://paddledet.bj.bcebos.com/data/coco_ce.tar',
  98. 'eadd1b79bc2f069f2744b1dd4e0c0329', ), ], [])
  99. }
  100. DOWNLOAD_RETRY_LIMIT = 3
  101. PPDET_WEIGHTS_DOWNLOAD_URL_PREFIX = 'https://paddledet.bj.bcebos.com/'
  102. def parse_url(url):
  103. url = url.replace("ppdet://", PPDET_WEIGHTS_DOWNLOAD_URL_PREFIX)
  104. return url
  105. def get_weights_path(url):
  106. """Get weights path from WEIGHTS_HOME, if not exists,
  107. download it from url.
  108. """
  109. url = parse_url(url)
  110. path, _ = get_path(url, WEIGHTS_HOME)
  111. return path
  112. def get_config_path(url):
  113. """Get weights path from CONFIGS_HOME, if not exists,
  114. download it from url.
  115. """
  116. url = parse_url(url)
  117. path = map_path(url, CONFIGS_HOME, path_depth=2)
  118. if os.path.isfile(path):
  119. return path
  120. # config file not found, try download
  121. # 1. clear configs directory
  122. if osp.isdir(CONFIGS_HOME):
  123. shutil.rmtree(CONFIGS_HOME)
  124. # 2. get url
  125. try:
  126. from ppdet import __version__ as version
  127. except ImportError:
  128. version = None
  129. cfg_url = "ppdet://configs/{}/configs.tar".format(version) \
  130. if version else "ppdet://configs/configs.tar"
  131. cfg_url = parse_url(cfg_url)
  132. # 3. download and decompress
  133. cfg_fullname = _download_dist(cfg_url, osp.dirname(CONFIGS_HOME))
  134. _decompress_dist(cfg_fullname)
  135. # 4. check config file existing
  136. if os.path.isfile(path):
  137. return path
  138. else:
  139. logger.error("Get config {} failed after download, please contact us on " \
  140. "https://github.com/PaddlePaddle/PaddleDetection/issues".format(path))
  141. sys.exit(1)
  142. def get_dataset_path(path, annotation, image_dir):
  143. """
  144. If path exists, return path.
  145. Otherwise, get dataset path from DATASET_HOME, if not exists,
  146. download it.
  147. """
  148. if _dataset_exists(path, annotation, image_dir):
  149. return path
  150. logger.info("Dataset {} is not valid for reason above, try searching {} or "
  151. "downloading dataset...".format(
  152. osp.realpath(path), DATASET_HOME))
  153. data_name = os.path.split(path.strip().lower())[-1]
  154. for name, dataset in DATASETS.items():
  155. if data_name == name:
  156. logger.debug("Parse dataset_dir {} as dataset "
  157. "{}".format(path, name))
  158. if name == 'objects365':
  159. raise NotImplementedError(
  160. "Dataset {} is not valid for download automatically. "
  161. "Please apply and download the dataset from "
  162. "https://www.objects365.org/download.html".format(name))
  163. data_dir = osp.join(DATASET_HOME, name)
  164. if name == 'mot':
  165. if osp.exists(path) or osp.exists(data_dir):
  166. return data_dir
  167. else:
  168. raise NotImplementedError(
  169. "Dataset {} is not valid for download automatically. "
  170. "Please apply and download the dataset following docs/tutorials/PrepareMOTDataSet.md".
  171. format(name))
  172. if name == "spine_coco":
  173. if _dataset_exists(data_dir, annotation, image_dir):
  174. return data_dir
  175. # For voc, only check dir VOCdevkit/VOC2012, VOCdevkit/VOC2007
  176. if name in ['voc', 'fruit', 'roadsign_voc']:
  177. exists = True
  178. for sub_dir in dataset[1]:
  179. check_dir = osp.join(data_dir, sub_dir)
  180. if osp.exists(check_dir):
  181. logger.info("Found {}".format(check_dir))
  182. else:
  183. exists = False
  184. if exists:
  185. return data_dir
  186. # voc exist is checked above, voc is not exist here
  187. check_exist = name != 'voc' and name != 'fruit' and name != 'roadsign_voc'
  188. for url, md5sum in dataset[0]:
  189. get_path(url, data_dir, md5sum, check_exist)
  190. # voc should create list after download
  191. if name == 'voc':
  192. create_voc_list(data_dir)
  193. return data_dir
  194. # not match any dataset in DATASETS
  195. raise ValueError(
  196. "Dataset {} is not valid and cannot parse dataset type "
  197. "'{}' for automaticly downloading, which only supports "
  198. "'voc' , 'coco', 'wider_face', 'fruit', 'roadsign_voc' and 'mot' currently".
  199. format(path, osp.split(path)[-1]))
  200. def create_voc_list(data_dir, devkit_subdir='VOCdevkit'):
  201. logger.debug("Create voc file list...")
  202. devkit_dir = osp.join(data_dir, devkit_subdir)
  203. years = ['2007', '2012']
  204. # NOTE: since using auto download VOC
  205. # dataset, VOC default label list should be used,
  206. # do not generate label_list.txt here. For default
  207. # label, see ../data/source/voc.py
  208. create_list(devkit_dir, years, data_dir)
  209. logger.debug("Create voc file list finished")
  210. def map_path(url, root_dir, path_depth=1):
  211. # parse path after download to decompress under root_dir
  212. assert path_depth > 0, "path_depth should be a positive integer"
  213. dirname = url
  214. for _ in range(path_depth):
  215. dirname = osp.dirname(dirname)
  216. fpath = osp.relpath(url, dirname)
  217. zip_formats = ['.zip', '.tar', '.gz']
  218. for zip_format in zip_formats:
  219. fpath = fpath.replace(zip_format, '')
  220. return osp.join(root_dir, fpath)
  221. def get_path(url, root_dir, md5sum=None, check_exist=True):
  222. """ Download from given url to root_dir.
  223. if file or directory specified by url is exists under
  224. root_dir, return the path directly, otherwise download
  225. from url and decompress it, return the path.
  226. url (str): download url
  227. root_dir (str): root dir for downloading, it should be
  228. WEIGHTS_HOME or DATASET_HOME
  229. md5sum (str): md5 sum of download package
  230. """
  231. # parse path after download to decompress under root_dir
  232. fullpath = map_path(url, root_dir)
  233. # For same zip file, decompressed directory name different
  234. # from zip file name, rename by following map
  235. decompress_name_map = {
  236. "VOCtrainval_11-May-2012": "VOCdevkit/VOC2012",
  237. "VOCtrainval_06-Nov-2007": "VOCdevkit/VOC2007",
  238. "VOCtest_06-Nov-2007": "VOCdevkit/VOC2007",
  239. "annotations_trainval": "annotations"
  240. }
  241. for k, v in decompress_name_map.items():
  242. if fullpath.find(k) >= 0:
  243. fullpath = osp.join(osp.split(fullpath)[0], v)
  244. if osp.exists(fullpath) and check_exist:
  245. if not osp.isfile(fullpath) or \
  246. _check_exist_file_md5(fullpath, md5sum, url):
  247. logger.debug("Found {}".format(fullpath))
  248. return fullpath, True
  249. else:
  250. os.remove(fullpath)
  251. fullname = _download_dist(url, root_dir, md5sum)
  252. # new weights format which postfix is 'pdparams' not
  253. # need to decompress
  254. if osp.splitext(fullname)[-1] not in ['.pdparams', '.yml']:
  255. _decompress_dist(fullname)
  256. return fullpath, False
  257. def download_dataset(path, dataset=None):
  258. if dataset not in DATASETS.keys():
  259. logger.error("Unknown dataset {}, it should be "
  260. "{}".format(dataset, DATASETS.keys()))
  261. return
  262. dataset_info = DATASETS[dataset][0]
  263. for info in dataset_info:
  264. get_path(info[0], path, info[1], False)
  265. logger.debug("Download dataset {} finished.".format(dataset))
  266. def _dataset_exists(path, annotation, image_dir):
  267. """
  268. Check if user define dataset exists
  269. """
  270. if not osp.exists(path):
  271. logger.warning("Config dataset_dir {} is not exits, "
  272. "dataset config is not valid".format(path))
  273. return False
  274. if annotation:
  275. annotation_path = osp.join(path, annotation)
  276. if not osp.isfile(annotation_path):
  277. logger.warning("Config annotation {} is not a "
  278. "file, dataset config is not "
  279. "valid".format(annotation_path))
  280. return False
  281. if image_dir:
  282. image_path = osp.join(path, image_dir)
  283. if not osp.isdir(image_path):
  284. logger.warning("Config image_dir {} is not a "
  285. "directory, dataset config is not "
  286. "valid".format(image_path))
  287. return False
  288. return True
  289. def _download(url, path, md5sum=None):
  290. """
  291. Download from url, save to path.
  292. url (str): download url
  293. path (str): download to given path
  294. """
  295. if not osp.exists(path):
  296. os.makedirs(path)
  297. fname = osp.split(url)[-1]
  298. fullname = osp.join(path, fname)
  299. retry_cnt = 0
  300. while not (osp.exists(fullname) and _check_exist_file_md5(fullname, md5sum,
  301. url)):
  302. if retry_cnt < DOWNLOAD_RETRY_LIMIT:
  303. retry_cnt += 1
  304. else:
  305. raise RuntimeError("Download from {} failed. "
  306. "Retry limit reached".format(url))
  307. logger.info("Downloading {} from {}".format(fname, url))
  308. # NOTE: windows path join may incur \, which is invalid in url
  309. if sys.platform == "win32":
  310. url = url.replace('\\', '/')
  311. req = requests.get(url, stream=True)
  312. if req.status_code != 200:
  313. raise RuntimeError("Downloading from {} failed with code "
  314. "{}!".format(url, req.status_code))
  315. # For protecting download interupted, download to
  316. # tmp_fullname firstly, move tmp_fullname to fullname
  317. # after download finished
  318. tmp_fullname = fullname + "_tmp"
  319. total_size = req.headers.get('content-length')
  320. with open(tmp_fullname, 'wb') as f:
  321. if total_size:
  322. for chunk in tqdm.tqdm(
  323. req.iter_content(chunk_size=1024),
  324. total=(int(total_size) + 1023) // 1024,
  325. unit='KB'):
  326. f.write(chunk)
  327. else:
  328. for chunk in req.iter_content(chunk_size=1024):
  329. if chunk:
  330. f.write(chunk)
  331. shutil.move(tmp_fullname, fullname)
  332. return fullname
  333. def _download_dist(url, path, md5sum=None):
  334. env = os.environ
  335. if 'PADDLE_TRAINERS_NUM' in env and 'PADDLE_TRAINER_ID' in env:
  336. trainer_id = int(env['PADDLE_TRAINER_ID'])
  337. num_trainers = int(env['PADDLE_TRAINERS_NUM'])
  338. if num_trainers <= 1:
  339. return _download(url, path, md5sum)
  340. else:
  341. fname = osp.split(url)[-1]
  342. fullname = osp.join(path, fname)
  343. lock_path = fullname + '.download.lock'
  344. if not osp.isdir(path):
  345. os.makedirs(path)
  346. if not osp.exists(fullname):
  347. from paddle.distributed import ParallelEnv
  348. unique_endpoints = _get_unique_endpoints(ParallelEnv()
  349. .trainer_endpoints[:])
  350. with open(lock_path, 'w'): # touch
  351. os.utime(lock_path, None)
  352. if ParallelEnv().current_endpoint in unique_endpoints:
  353. _download(url, path, md5sum)
  354. os.remove(lock_path)
  355. else:
  356. while os.path.exists(lock_path):
  357. time.sleep(0.5)
  358. return fullname
  359. else:
  360. return _download(url, path, md5sum)
  361. def _check_exist_file_md5(filename, md5sum, url):
  362. # if md5sum is None, and file to check is weights file,
  363. # read md5um from url and check, else check md5sum directly
  364. return _md5check_from_url(filename, url) if md5sum is None \
  365. and filename.endswith('pdparams') \
  366. else _md5check(filename, md5sum)
  367. def _md5check_from_url(filename, url):
  368. # For weights in bcebos URLs, MD5 value is contained
  369. # in request header as 'content_md5'
  370. req = requests.get(url, stream=True)
  371. content_md5 = req.headers.get('content-md5')
  372. req.close()
  373. if not content_md5 or _md5check(
  374. filename,
  375. binascii.hexlify(base64.b64decode(content_md5.strip('"'))).decode(
  376. )):
  377. return True
  378. else:
  379. return False
  380. def _md5check(fullname, md5sum=None):
  381. if md5sum is None:
  382. return True
  383. logger.debug("File {} md5 checking...".format(fullname))
  384. md5 = hashlib.md5()
  385. with open(fullname, 'rb') as f:
  386. for chunk in iter(lambda: f.read(4096), b""):
  387. md5.update(chunk)
  388. calc_md5sum = md5.hexdigest()
  389. if calc_md5sum != md5sum:
  390. logger.warning("File {} md5 check failed, {}(calc) != "
  391. "{}(base)".format(fullname, calc_md5sum, md5sum))
  392. return False
  393. return True
  394. def _decompress(fname):
  395. """
  396. Decompress for zip and tar file
  397. """
  398. logger.info("Decompressing {}...".format(fname))
  399. # For protecting decompressing interupted,
  400. # decompress to fpath_tmp directory firstly, if decompress
  401. # successed, move decompress files to fpath and delete
  402. # fpath_tmp and remove download compress file.
  403. fpath = osp.split(fname)[0]
  404. fpath_tmp = osp.join(fpath, 'tmp')
  405. if osp.isdir(fpath_tmp):
  406. shutil.rmtree(fpath_tmp)
  407. os.makedirs(fpath_tmp)
  408. if fname.find('tar') >= 0:
  409. with tarfile.open(fname) as tf:
  410. tf.extractall(path=fpath_tmp)
  411. elif fname.find('zip') >= 0:
  412. with zipfile.ZipFile(fname) as zf:
  413. zf.extractall(path=fpath_tmp)
  414. elif fname.find('.txt') >= 0:
  415. return
  416. else:
  417. raise TypeError("Unsupport compress file type {}".format(fname))
  418. for f in os.listdir(fpath_tmp):
  419. src_dir = osp.join(fpath_tmp, f)
  420. dst_dir = osp.join(fpath, f)
  421. _move_and_merge_tree(src_dir, dst_dir)
  422. shutil.rmtree(fpath_tmp)
  423. os.remove(fname)
  424. def _decompress_dist(fname):
  425. env = os.environ
  426. if 'PADDLE_TRAINERS_NUM' in env and 'PADDLE_TRAINER_ID' in env:
  427. trainer_id = int(env['PADDLE_TRAINER_ID'])
  428. num_trainers = int(env['PADDLE_TRAINERS_NUM'])
  429. if num_trainers <= 1:
  430. _decompress(fname)
  431. else:
  432. lock_path = fname + '.decompress.lock'
  433. from paddle.distributed import ParallelEnv
  434. unique_endpoints = _get_unique_endpoints(ParallelEnv()
  435. .trainer_endpoints[:])
  436. # NOTE(dkp): _decompress_dist always performed after
  437. # _download_dist, in _download_dist sub-trainers is waiting
  438. # for download lock file release with sleeping, if decompress
  439. # prograss is very fast and finished with in the sleeping gap
  440. # time, e.g in tiny dataset such as coco_ce, spine_coco, main
  441. # trainer may finish decompress and release lock file, so we
  442. # only craete lock file in main trainer and all sub-trainer
  443. # wait 1s for main trainer to create lock file, for 1s is
  444. # twice as sleeping gap, this waiting time can keep all
  445. # trainer pipeline in order
  446. # **change this if you have more elegent methods**
  447. if ParallelEnv().current_endpoint in unique_endpoints:
  448. with open(lock_path, 'w'): # touch
  449. os.utime(lock_path, None)
  450. _decompress(fname)
  451. os.remove(lock_path)
  452. else:
  453. time.sleep(1)
  454. while os.path.exists(lock_path):
  455. time.sleep(0.5)
  456. else:
  457. _decompress(fname)
  458. def _move_and_merge_tree(src, dst):
  459. """
  460. Move src directory to dst, if dst is already exists,
  461. merge src to dst
  462. """
  463. if not osp.exists(dst):
  464. shutil.move(src, dst)
  465. elif osp.isfile(src):
  466. shutil.move(src, dst)
  467. else:
  468. for fp in os.listdir(src):
  469. src_fp = osp.join(src, fp)
  470. dst_fp = osp.join(dst, fp)
  471. if osp.isdir(src_fp):
  472. if osp.isdir(dst_fp):
  473. _move_and_merge_tree(src_fp, dst_fp)
  474. else:
  475. shutil.move(src_fp, dst_fp)
  476. elif osp.isfile(src_fp) and \
  477. not osp.isfile(dst_fp):
  478. shutil.move(src_fp, dst_fp)