download.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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 paddlex.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. }
  97. DOWNLOAD_RETRY_LIMIT = 3
  98. PPDET_WEIGHTS_DOWNLOAD_URL_PREFIX = 'https://paddledet.bj.bcebos.com/'
  99. def parse_url(url):
  100. url = url.replace("ppdet://", PPDET_WEIGHTS_DOWNLOAD_URL_PREFIX)
  101. return url
  102. def get_weights_path(url):
  103. """Get weights path from WEIGHTS_HOME, if not exists,
  104. download it from url.
  105. """
  106. url = parse_url(url)
  107. path, _ = get_path(url, WEIGHTS_HOME)
  108. return path
  109. def get_config_path(url):
  110. """Get weights path from CONFIGS_HOME, if not exists,
  111. download it from url.
  112. """
  113. url = parse_url(url)
  114. path = map_path(url, CONFIGS_HOME, path_depth=2)
  115. if os.path.isfile(path):
  116. return path
  117. # config file not found, try download
  118. # 1. clear configs directory
  119. if osp.isdir(CONFIGS_HOME):
  120. shutil.rmtree(CONFIGS_HOME)
  121. # 2. get url
  122. try:
  123. from paddlex.ppdet import __version__ as version
  124. except ImportError:
  125. version = None
  126. cfg_url = "ppdet://configs/{}/configs.tar".format(version) \
  127. if version else "ppdet://configs/configs.tar"
  128. cfg_url = parse_url(cfg_url)
  129. # 3. download and decompress
  130. cfg_fullname = _download_dist(cfg_url, osp.dirname(CONFIGS_HOME))
  131. _decompress_dist(cfg_fullname)
  132. # 4. check config file existing
  133. if os.path.isfile(path):
  134. return path
  135. else:
  136. logger.error("Get config {} failed after download, please contact us on " \
  137. "https://github.com/PaddlePaddle/PaddleDetection/issues".format(path))
  138. sys.exit(1)
  139. def get_dataset_path(path, annotation, image_dir):
  140. """
  141. If path exists, return path.
  142. Otherwise, get dataset path from DATASET_HOME, if not exists,
  143. download it.
  144. """
  145. if _dataset_exists(path, annotation, image_dir):
  146. return path
  147. logger.info(
  148. "Dataset {} is not valid for reason above, try searching {} or "
  149. "downloading dataset...".format(osp.realpath(path), DATASET_HOME))
  150. data_name = os.path.split(path.strip().lower())[-1]
  151. for name, dataset in DATASETS.items():
  152. if data_name == name:
  153. logger.debug("Parse dataset_dir {} as dataset "
  154. "{}".format(path, name))
  155. if name == 'objects365':
  156. raise NotImplementedError(
  157. "Dataset {} is not valid for download automatically. "
  158. "Please apply and download the dataset from "
  159. "https://www.objects365.org/download.html".format(name))
  160. data_dir = osp.join(DATASET_HOME, name)
  161. if name == 'mot':
  162. if osp.exists(path) or osp.exists(data_dir):
  163. return data_dir
  164. else:
  165. raise NotImplementedError(
  166. "Dataset {} is not valid for download automatically. "
  167. "Please apply and download the dataset following docs/tutorials/PrepareMOTDataSet.md".
  168. format(name))
  169. if name == "spine_coco":
  170. if _dataset_exists(data_dir, annotation, image_dir):
  171. return data_dir
  172. # For voc, only check dir VOCdevkit/VOC2012, VOCdevkit/VOC2007
  173. if name in ['voc', 'fruit', 'roadsign_voc']:
  174. exists = True
  175. for sub_dir in dataset[1]:
  176. check_dir = osp.join(data_dir, sub_dir)
  177. if osp.exists(check_dir):
  178. logger.info("Found {}".format(check_dir))
  179. else:
  180. exists = False
  181. if exists:
  182. return data_dir
  183. # voc exist is checked above, voc is not exist here
  184. check_exist = name != 'voc' and name != 'fruit' and name != 'roadsign_voc'
  185. for url, md5sum in dataset[0]:
  186. get_path(url, data_dir, md5sum, check_exist)
  187. # voc should create list after download
  188. if name == 'voc':
  189. create_voc_list(data_dir)
  190. return data_dir
  191. # not match any dataset in DATASETS
  192. raise ValueError(
  193. "Dataset {} is not valid and cannot parse dataset type "
  194. "'{}' for automaticly downloading, which only supports "
  195. "'voc' , 'coco', 'wider_face', 'fruit', 'roadsign_voc' and 'mot' currently".
  196. format(path, osp.split(path)[-1]))
  197. def create_voc_list(data_dir, devkit_subdir='VOCdevkit'):
  198. logger.debug("Create voc file list...")
  199. devkit_dir = osp.join(data_dir, devkit_subdir)
  200. years = ['2007', '2012']
  201. # NOTE: since using auto download VOC
  202. # dataset, VOC default label list should be used,
  203. # do not generate label_list.txt here. For default
  204. # label, see ../data/source/voc.py
  205. create_list(devkit_dir, years, data_dir)
  206. logger.debug("Create voc file list finished")
  207. def map_path(url, root_dir, path_depth=1):
  208. # parse path after download to decompress under root_dir
  209. assert path_depth > 0, "path_depth should be a positive integer"
  210. dirname = url
  211. for _ in range(path_depth):
  212. dirname = osp.dirname(dirname)
  213. fpath = osp.relpath(url, dirname)
  214. zip_formats = ['.zip', '.tar', '.gz']
  215. for zip_format in zip_formats:
  216. fpath = fpath.replace(zip_format, '')
  217. return osp.join(root_dir, fpath)
  218. def get_path(url, root_dir, md5sum=None, check_exist=True):
  219. """ Download from given url to root_dir.
  220. if file or directory specified by url is exists under
  221. root_dir, return the path directly, otherwise download
  222. from url and decompress it, return the path.
  223. url (str): download url
  224. root_dir (str): root dir for downloading, it should be
  225. WEIGHTS_HOME or DATASET_HOME
  226. md5sum (str): md5 sum of download package
  227. """
  228. # parse path after download to decompress under root_dir
  229. fullpath = map_path(url, root_dir)
  230. # For same zip file, decompressed directory name different
  231. # from zip file name, rename by following map
  232. decompress_name_map = {
  233. "VOCtrainval_11-May-2012": "VOCdevkit/VOC2012",
  234. "VOCtrainval_06-Nov-2007": "VOCdevkit/VOC2007",
  235. "VOCtest_06-Nov-2007": "VOCdevkit/VOC2007",
  236. "annotations_trainval": "annotations"
  237. }
  238. for k, v in decompress_name_map.items():
  239. if fullpath.find(k) >= 0:
  240. fullpath = osp.join(osp.split(fullpath)[0], v)
  241. if osp.exists(fullpath) and check_exist:
  242. if not osp.isfile(fullpath) or \
  243. _check_exist_file_md5(fullpath, md5sum, url):
  244. logger.debug("Found {}".format(fullpath))
  245. return fullpath, True
  246. else:
  247. os.remove(fullpath)
  248. fullname = _download_dist(url, root_dir, md5sum)
  249. # new weights format which postfix is 'pdparams' not
  250. # need to decompress
  251. if osp.splitext(fullname)[-1] not in ['.pdparams', '.yml']:
  252. _decompress_dist(fullname)
  253. return fullpath, False
  254. def download_dataset(path, dataset=None):
  255. if dataset not in DATASETS.keys():
  256. logger.error("Unknown dataset {}, it should be "
  257. "{}".format(dataset, DATASETS.keys()))
  258. return
  259. dataset_info = DATASETS[dataset][0]
  260. for info in dataset_info:
  261. get_path(info[0], path, info[1], False)
  262. logger.debug("Download dataset {} finished.".format(dataset))
  263. def _dataset_exists(path, annotation, image_dir):
  264. """
  265. Check if user define dataset exists
  266. """
  267. if not osp.exists(path):
  268. logger.warning("Config dataset_dir {} is not exits, "
  269. "dataset config is not valid".format(path))
  270. return False
  271. if annotation:
  272. annotation_path = osp.join(path, annotation)
  273. if not osp.isfile(annotation_path):
  274. logger.warning("Config annotation {} is not a "
  275. "file, dataset config is not "
  276. "valid".format(annotation_path))
  277. return False
  278. if image_dir:
  279. image_path = osp.join(path, image_dir)
  280. if not osp.isdir(image_path):
  281. logger.warning("Config image_dir {} is not a "
  282. "directory, dataset config is not "
  283. "valid".format(image_path))
  284. return False
  285. return True
  286. def _download(url, path, md5sum=None):
  287. """
  288. Download from url, save to path.
  289. url (str): download url
  290. path (str): download to given path
  291. """
  292. if not osp.exists(path):
  293. os.makedirs(path)
  294. fname = osp.split(url)[-1]
  295. fullname = osp.join(path, fname)
  296. retry_cnt = 0
  297. while not (osp.exists(fullname) and _check_exist_file_md5(fullname, md5sum,
  298. url)):
  299. if retry_cnt < DOWNLOAD_RETRY_LIMIT:
  300. retry_cnt += 1
  301. else:
  302. raise RuntimeError("Download from {} failed. "
  303. "Retry limit reached".format(url))
  304. logger.info("Downloading {} from {}".format(fname, url))
  305. # NOTE: windows path join may incur \, which is invalid in url
  306. if sys.platform == "win32":
  307. url = url.replace('\\', '/')
  308. req = requests.get(url, stream=True)
  309. if req.status_code != 200:
  310. raise RuntimeError("Downloading from {} failed with code "
  311. "{}!".format(url, req.status_code))
  312. # For protecting download interupted, download to
  313. # tmp_fullname firstly, move tmp_fullname to fullname
  314. # after download finished
  315. tmp_fullname = fullname + "_tmp"
  316. total_size = req.headers.get('content-length')
  317. with open(tmp_fullname, 'wb') as f:
  318. if total_size:
  319. for chunk in tqdm.tqdm(
  320. req.iter_content(chunk_size=1024),
  321. total=(int(total_size) + 1023) // 1024,
  322. unit='KB'):
  323. f.write(chunk)
  324. else:
  325. for chunk in req.iter_content(chunk_size=1024):
  326. if chunk:
  327. f.write(chunk)
  328. shutil.move(tmp_fullname, fullname)
  329. return fullname
  330. def _download_dist(url, path, md5sum=None):
  331. env = os.environ
  332. if 'PADDLE_TRAINERS_NUM' in env and 'PADDLE_TRAINER_ID' in env:
  333. trainer_id = int(env['PADDLE_TRAINER_ID'])
  334. num_trainers = int(env['PADDLE_TRAINERS_NUM'])
  335. if num_trainers <= 1:
  336. return _download(url, path, md5sum)
  337. else:
  338. fname = osp.split(url)[-1]
  339. fullname = osp.join(path, fname)
  340. lock_path = fullname + '.download.lock'
  341. if not osp.isdir(path):
  342. os.makedirs(path)
  343. if not osp.exists(fullname):
  344. from paddle.distributed import ParallelEnv
  345. unique_endpoints = _get_unique_endpoints(ParallelEnv()
  346. .trainer_endpoints[:])
  347. with open(lock_path, 'w'): # touch
  348. os.utime(lock_path, None)
  349. if ParallelEnv().current_endpoint in unique_endpoints:
  350. _download(url, path, md5sum)
  351. os.remove(lock_path)
  352. else:
  353. while os.path.exists(lock_path):
  354. time.sleep(0.5)
  355. return fullname
  356. else:
  357. return _download(url, path, md5sum)
  358. def _check_exist_file_md5(filename, md5sum, url):
  359. # if md5sum is None, and file to check is weights file,
  360. # read md5um from url and check, else check md5sum directly
  361. return _md5check_from_url(filename, url) if md5sum is None \
  362. and filename.endswith('pdparams') \
  363. else _md5check(filename, md5sum)
  364. def _md5check_from_url(filename, url):
  365. # For weights in bcebos URLs, MD5 value is contained
  366. # in request header as 'content_md5'
  367. req = requests.get(url, stream=True)
  368. content_md5 = req.headers.get('content-md5')
  369. req.close()
  370. if not content_md5 or _md5check(
  371. filename,
  372. binascii.hexlify(base64.b64decode(content_md5.strip('"'))).decode(
  373. )):
  374. return True
  375. else:
  376. return False
  377. def _md5check(fullname, md5sum=None):
  378. if md5sum is None:
  379. return True
  380. logger.debug("File {} md5 checking...".format(fullname))
  381. md5 = hashlib.md5()
  382. with open(fullname, 'rb') as f:
  383. for chunk in iter(lambda: f.read(4096), b""):
  384. md5.update(chunk)
  385. calc_md5sum = md5.hexdigest()
  386. if calc_md5sum != md5sum:
  387. logger.warning("File {} md5 check failed, {}(calc) != "
  388. "{}(base)".format(fullname, calc_md5sum, md5sum))
  389. return False
  390. return True
  391. def _decompress(fname):
  392. """
  393. Decompress for zip and tar file
  394. """
  395. logger.info("Decompressing {}...".format(fname))
  396. # For protecting decompressing interupted,
  397. # decompress to fpath_tmp directory firstly, if decompress
  398. # successed, move decompress files to fpath and delete
  399. # fpath_tmp and remove download compress file.
  400. fpath = osp.split(fname)[0]
  401. fpath_tmp = osp.join(fpath, 'tmp')
  402. if osp.isdir(fpath_tmp):
  403. shutil.rmtree(fpath_tmp)
  404. os.makedirs(fpath_tmp)
  405. if fname.find('tar') >= 0:
  406. with tarfile.open(fname) as tf:
  407. tf.extractall(path=fpath_tmp)
  408. elif fname.find('zip') >= 0:
  409. with zipfile.ZipFile(fname) as zf:
  410. zf.extractall(path=fpath_tmp)
  411. elif fname.find('.txt') >= 0:
  412. return
  413. else:
  414. raise TypeError("Unsupport compress file type {}".format(fname))
  415. for f in os.listdir(fpath_tmp):
  416. src_dir = osp.join(fpath_tmp, f)
  417. dst_dir = osp.join(fpath, f)
  418. _move_and_merge_tree(src_dir, dst_dir)
  419. shutil.rmtree(fpath_tmp)
  420. os.remove(fname)
  421. def _decompress_dist(fname):
  422. env = os.environ
  423. if 'PADDLE_TRAINERS_NUM' in env and 'PADDLE_TRAINER_ID' in env:
  424. trainer_id = int(env['PADDLE_TRAINER_ID'])
  425. num_trainers = int(env['PADDLE_TRAINERS_NUM'])
  426. if num_trainers <= 1:
  427. _decompress(fname)
  428. else:
  429. lock_path = fname + '.decompress.lock'
  430. from paddle.distributed import ParallelEnv
  431. unique_endpoints = _get_unique_endpoints(ParallelEnv()
  432. .trainer_endpoints[:])
  433. # NOTE(dkp): _decompress_dist always performed after
  434. # _download_dist, in _download_dist sub-trainers is waiting
  435. # for download lock file release with sleeping, if decompress
  436. # prograss is very fast and finished with in the sleeping gap
  437. # time, e.g in tiny dataset such as coco_ce, spine_coco, main
  438. # trainer may finish decompress and release lock file, so we
  439. # only craete lock file in main trainer and all sub-trainer
  440. # wait 1s for main trainer to create lock file, for 1s is
  441. # twice as sleeping gap, this waiting time can keep all
  442. # trainer pipeline in order
  443. # **change this if you have more elegent methods**
  444. if ParallelEnv().current_endpoint in unique_endpoints:
  445. with open(lock_path, 'w'): # touch
  446. os.utime(lock_path, None)
  447. _decompress(fname)
  448. os.remove(lock_path)
  449. else:
  450. time.sleep(1)
  451. while os.path.exists(lock_path):
  452. time.sleep(0.5)
  453. else:
  454. _decompress(fname)
  455. def _move_and_merge_tree(src, dst):
  456. """
  457. Move src directory to dst, if dst is already exists,
  458. merge src to dst
  459. """
  460. if not osp.exists(dst):
  461. shutil.move(src, dst)
  462. elif osp.isfile(src):
  463. shutil.move(src, dst)
  464. else:
  465. for fp in os.listdir(src):
  466. src_fp = osp.join(src, fp)
  467. dst_fp = osp.join(dst, fp)
  468. if osp.isdir(src_fp):
  469. if osp.isdir(dst_fp):
  470. _move_and_merge_tree(src_fp, dst_fp)
  471. else:
  472. shutil.move(src_fp, dst_fp)
  473. elif osp.isfile(src_fp) and \
  474. not osp.isfile(dst_fp):
  475. shutil.move(src_fp, dst_fp)