download_models.py 14 KB

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