download_models.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. '''
  2. Helper module to download extra data from Internet
  3. '''
  4. from __future__ import print_function
  5. import os
  6. import sys
  7. import yaml
  8. import argparse
  9. import tarfile
  10. import platform
  11. import tempfile
  12. import hashlib
  13. import requests
  14. import shutil
  15. from pathlib import Path
  16. from datetime import datetime
  17. if sys.version_info[0] < 3:
  18. from urllib2 import urlopen
  19. else:
  20. from urllib.request import urlopen
  21. import xml.etree.ElementTree as ET
  22. __all__ = ["downloadFile"]
  23. class HashMismatchException(Exception):
  24. def __init__(self, expected, actual):
  25. Exception.__init__(self)
  26. self.expected = expected
  27. self.actual = actual
  28. def __str__(self):
  29. return 'Hash mismatch: expected {} vs actual of {}'.format(self.expected, self.actual)
  30. def getHashsumFromFile(filepath):
  31. sha = hashlib.sha1()
  32. if os.path.exists(filepath):
  33. print(' there is already a file with the same name')
  34. with open(filepath, 'rb') as f:
  35. while True:
  36. buf = f.read(10*1024*1024)
  37. if not buf:
  38. break
  39. sha.update(buf)
  40. hashsum = sha.hexdigest()
  41. return hashsum
  42. def checkHashsum(expected_sha, filepath, silent=True):
  43. print(' expected SHA1: {}'.format(expected_sha))
  44. actual_sha = getHashsumFromFile(filepath)
  45. print(' actual SHA1:{}'.format(actual_sha))
  46. hashes_matched = expected_sha == actual_sha
  47. if not hashes_matched and not silent:
  48. raise HashMismatchException(expected_sha, actual_sha)
  49. return hashes_matched
  50. def isArchive(filepath):
  51. return tarfile.is_tarfile(filepath)
  52. class DownloadInstance:
  53. def __init__(self, **kwargs):
  54. self.name = kwargs.pop('name')
  55. self.filename = kwargs.pop('filename')
  56. self.loader = kwargs.pop('loader', None)
  57. self.save_dir = kwargs.pop('save_dir')
  58. self.sha = kwargs.pop('sha', None)
  59. def __str__(self):
  60. return 'DownloadInstance <{}>'.format(self.name)
  61. def get(self):
  62. print(" Working on " + self.name)
  63. print(" Getting file " + self.filename)
  64. if self.sha is None:
  65. print(' No expected hashsum provided, loading file')
  66. else:
  67. filepath = os.path.join(self.save_dir, self.sha, self.filename)
  68. if checkHashsum(self.sha, filepath):
  69. print(' hash match - file already exists, skipping')
  70. return filepath
  71. else:
  72. print(' hash didn\'t match, loading file')
  73. if not os.path.exists(self.save_dir):
  74. print(' creating directory: ' + self.save_dir)
  75. os.makedirs(self.save_dir)
  76. print(' hash check failed - loading')
  77. assert self.loader
  78. try:
  79. self.loader.load(self.filename, self.sha, self.save_dir)
  80. print(' done')
  81. print(' file {}'.format(self.filename))
  82. if self.sha is None:
  83. download_path = os.path.join(self.save_dir, self.filename)
  84. self.sha = getHashsumFromFile(download_path)
  85. new_dir = os.path.join(self.save_dir, self.sha)
  86. if not os.path.exists(new_dir):
  87. os.makedirs(new_dir)
  88. filepath = os.path.join(new_dir, self.filename)
  89. if not (os.path.exists(filepath)):
  90. shutil.move(download_path, new_dir)
  91. print(' No expected hashsum provided, actual SHA is {}'.format(self.sha))
  92. else:
  93. checkHashsum(self.sha, filepath, silent=False)
  94. except Exception as e:
  95. print(" There was some problem with loading file {} for {}".format(self.filename, self.name))
  96. print(" Exception: {}".format(e))
  97. return
  98. print(" Finished " + self.name)
  99. return filepath
  100. class Loader(object):
  101. MB = 1024*1024
  102. BUFSIZE = 10*MB
  103. def __init__(self, download_name, download_sha, archive_member = None):
  104. self.download_name = download_name
  105. self.download_sha = download_sha
  106. self.archive_member = archive_member
  107. def load(self, requested_file, sha, save_dir):
  108. if self.download_sha is None:
  109. download_dir = save_dir
  110. else:
  111. # create a new folder in save_dir to avoid possible name conflicts
  112. download_dir = os.path.join(save_dir, self.download_sha)
  113. if not os.path.exists(download_dir):
  114. os.makedirs(download_dir)
  115. download_path = os.path.join(download_dir, self.download_name)
  116. print(" Preparing to download file " + self.download_name)
  117. if checkHashsum(self.download_sha, download_path):
  118. print(' hash match - file already exists, no need to download')
  119. else:
  120. filesize = self.download(download_path)
  121. print(' Downloaded {} with size {} Mb'.format(self.download_name, filesize/self.MB))
  122. if self.download_sha is not None:
  123. checkHashsum(self.download_sha, download_path, silent=False)
  124. if self.download_name == requested_file:
  125. return
  126. else:
  127. if isArchive(download_path):
  128. if sha is not None:
  129. extract_dir = os.path.join(save_dir, sha)
  130. else:
  131. extract_dir = save_dir
  132. if not os.path.exists(extract_dir):
  133. os.makedirs(extract_dir)
  134. self.extract(requested_file, download_path, extract_dir)
  135. else:
  136. raise Exception("Downloaded file has different name")
  137. def download(self, filepath):
  138. print("Warning: download is not implemented, this is a base class")
  139. return 0
  140. def extract(self, requested_file, archive_path, save_dir):
  141. filepath = os.path.join(save_dir, requested_file)
  142. try:
  143. with tarfile.open(archive_path) as f:
  144. if self.archive_member is None:
  145. pathDict = dict((os.path.split(elem)[1], os.path.split(elem)[0]) for elem in f.getnames())
  146. self.archive_member = pathDict[requested_file]
  147. assert self.archive_member in f.getnames()
  148. self.save(filepath, f.extractfile(self.archive_member))
  149. except Exception as e:
  150. print(' catch {}'.format(e))
  151. def save(self, filepath, r):
  152. with open(filepath, 'wb') as f:
  153. print(' progress ', end="")
  154. sys.stdout.flush()
  155. while True:
  156. buf = r.read(self.BUFSIZE)
  157. if not buf:
  158. break
  159. f.write(buf)
  160. print('>', end="")
  161. sys.stdout.flush()
  162. class URLLoader(Loader):
  163. def __init__(self, download_name, download_sha, url, archive_member = None):
  164. super(URLLoader, self).__init__(download_name, download_sha, archive_member)
  165. self.download_name = download_name
  166. self.download_sha = download_sha
  167. self.url = url
  168. def download(self, filepath):
  169. r = urlopen(self.url, timeout=60)
  170. self.printRequest(r)
  171. self.save(filepath, r)
  172. return os.path.getsize(filepath)
  173. def printRequest(self, r):
  174. def getMB(r):
  175. d = dict(r.info())
  176. for c in ['content-length', 'Content-Length']:
  177. if c in d:
  178. return int(d[c]) / self.MB
  179. return '<unknown>'
  180. print(' {} {} [{} Mb]'.format(r.getcode(), r.msg, getMB(r)))
  181. class GDriveLoader(Loader):
  182. BUFSIZE = 1024 * 1024
  183. PROGRESS_SIZE = 10 * 1024 * 1024
  184. def __init__(self, download_name, download_sha, gid, archive_member = None):
  185. super(GDriveLoader, self).__init__(download_name, download_sha, archive_member)
  186. self.download_name = download_name
  187. self.download_sha = download_sha
  188. self.gid = gid
  189. def download(self, filepath):
  190. session = requests.Session() # re-use cookies
  191. URL = "https://docs.google.com/uc?export=download"
  192. response = session.get(URL, params = { 'id' : self.gid }, stream = True)
  193. def get_confirm_token(response): # in case of large files
  194. for key, value in response.cookies.items():
  195. if key.startswith('download_warning'):
  196. return value
  197. return None
  198. token = get_confirm_token(response)
  199. if token:
  200. params = { 'id' : self.gid, 'confirm' : token }
  201. response = session.get(URL, params = params, stream = True)
  202. sz = 0
  203. progress_sz = self.PROGRESS_SIZE
  204. with open(filepath, "wb") as f:
  205. for chunk in response.iter_content(self.BUFSIZE):
  206. if not chunk:
  207. continue # keep-alive
  208. f.write(chunk)
  209. sz += len(chunk)
  210. if sz >= progress_sz:
  211. progress_sz += self.PROGRESS_SIZE
  212. print('>', end='')
  213. sys.stdout.flush()
  214. print('')
  215. return sz
  216. def produceDownloadInstance(instance_name, filename, sha, url, save_dir, download_name=None, download_sha=None, archive_member=None):
  217. spec_param = url
  218. loader = URLLoader
  219. if download_name is None:
  220. download_name = filename
  221. if download_sha is None:
  222. download_sha = sha
  223. if "drive.google.com" in url:
  224. token = ""
  225. token_part = url.rsplit('/', 1)[-1]
  226. if "&id=" not in token_part:
  227. token_part = url.rsplit('/', 1)[-2]
  228. for param in token_part.split("&"):
  229. if param.startswith("id="):
  230. token = param[3:]
  231. if token:
  232. loader = GDriveLoader
  233. spec_param = token
  234. else:
  235. print("Warning: possibly wrong Google Drive link")
  236. return DownloadInstance(
  237. name=instance_name,
  238. filename=filename,
  239. sha=sha,
  240. save_dir=save_dir,
  241. loader=loader(download_name, download_sha, spec_param, archive_member)
  242. )
  243. def getSaveDir():
  244. env_path = os.environ.get("OPENCV_DOWNLOAD_DATA_PATH", None)
  245. if env_path:
  246. save_dir = env_path
  247. else:
  248. # TODO reuse binding function cv2.utils.fs.getCacheDirectory when issue #19011 is fixed
  249. if platform.system() == "Darwin":
  250. #On Apple devices
  251. temp_env = os.environ.get("TMPDIR", None)
  252. if temp_env is None or not os.path.isdir(temp_env):
  253. temp_dir = Path("/tmp")
  254. print("Using world accessible cache directory. This may be not secure: ", temp_dir)
  255. else:
  256. temp_dir = temp_env
  257. elif platform.system() == "Windows":
  258. temp_dir = tempfile.gettempdir()
  259. else:
  260. xdg_cache_env = os.environ.get("XDG_CACHE_HOME", None)
  261. if (xdg_cache_env and xdg_cache_env[0] and os.path.isdir(xdg_cache_env)):
  262. temp_dir = xdg_cache_env
  263. else:
  264. home_env = os.environ.get("HOME", None)
  265. if (home_env and home_env[0] and os.path.isdir(home_env)):
  266. home_path = os.path.join(home_env, ".cache/")
  267. if os.path.isdir(home_path):
  268. temp_dir = home_path
  269. else:
  270. temp_dir = tempfile.gettempdir()
  271. print("Using world accessible cache directory. This may be not secure: ", temp_dir)
  272. save_dir = os.path.join(temp_dir, "downloads")
  273. if not os.path.exists(save_dir):
  274. os.makedirs(save_dir)
  275. return save_dir
  276. def downloadFile(url, sha=None, save_dir=None, filename=None):
  277. if save_dir is None:
  278. save_dir = getSaveDir()
  279. if filename is None:
  280. filename = "download_" + datetime.now().__str__()
  281. name = filename
  282. return produceDownloadInstance(name, filename, sha, url, save_dir).get()
  283. def parseMetalinkFile(metalink_filepath, save_dir):
  284. NS = {'ml': 'urn:ietf:params:xml:ns:metalink'}
  285. models = []
  286. for file_elem in ET.parse(metalink_filepath).getroot().findall('ml:file', NS):
  287. url = file_elem.find('ml:url', NS).text
  288. fname = file_elem.attrib['name']
  289. name = file_elem.find('ml:identity', NS).text
  290. hash_sum = file_elem.find('ml:hash', NS).text
  291. models.append(produceDownloadInstance(name, fname, hash_sum, url, save_dir))
  292. return models
  293. def parseYAMLFile(yaml_filepath, save_dir):
  294. models = []
  295. with open(yaml_filepath, 'r') as stream:
  296. data_loaded = yaml.safe_load(stream)
  297. for name, params in data_loaded.items():
  298. load_info = params.get("load_info", None)
  299. if load_info:
  300. fname = os.path.basename(params.get("model"))
  301. hash_sum = load_info.get("sha1")
  302. url = load_info.get("url")
  303. download_sha = load_info.get("download_sha")
  304. download_name = load_info.get("download_name")
  305. archive_member = load_info.get("member")
  306. models.append(produceDownloadInstance(name, fname, hash_sum, url, save_dir,
  307. download_name=download_name, download_sha=download_sha, archive_member=archive_member))
  308. return models
  309. if __name__ == '__main__':
  310. parser = argparse.ArgumentParser(description='This is a utility script for downloading DNN models for samples.')
  311. parser.add_argument('--save_dir', action="store", default=os.getcwd(),
  312. help='Path to the directory to store downloaded files')
  313. parser.add_argument('model_name', type=str, default="", nargs='?', action="store",
  314. help='name of the model to download')
  315. args = parser.parse_args()
  316. models = []
  317. save_dir = args.save_dir
  318. selected_model_name = args.model_name
  319. models.extend(parseMetalinkFile('face_detector/weights.meta4', save_dir))
  320. models.extend(parseYAMLFile('models.yml', save_dir))
  321. for m in models:
  322. print(m)
  323. if selected_model_name and not m.name.startswith(selected_model_name):
  324. continue
  325. print('Model: ' + selected_model_name)
  326. m.get()