Path: blob/master/samples/dnn/face_detector/download_weights.py
16337 views
#!/usr/bin/env python12from __future__ import print_function3import hashlib4import time5import sys6import xml.etree.ElementTree as ET7if sys.version_info[0] < 3:8from urllib2 import urlopen9else:10from urllib.request import urlopen1112class HashMismatchException(Exception):13def __init__(self, expected, actual):14Exception.__init__(self)15self.expected = expected16self.actual = actual17def __str__(self):18return 'Hash mismatch: {} vs {}'.format(self.expected, self.actual)1920class MetalinkDownloader(object):21BUFSIZE = 10*1024*102422NS = {'ml': 'urn:ietf:params:xml:ns:metalink'}23tick = 02425def download(self, metalink_file):26status = True27for file_elem in ET.parse(metalink_file).getroot().findall('ml:file', self.NS):28url = file_elem.find('ml:url', self.NS).text29fname = file_elem.attrib['name']30hash_sum = file_elem.find('ml:hash', self.NS).text31print('*** {}'.format(fname))32try:33self.verify(hash_sum, fname)34except Exception as ex:35print(' {}'.format(ex))36try:37print(' {}'.format(url))38with open(fname, 'wb') as file_stream:39self.buffered_read(urlopen(url), file_stream.write)40self.verify(hash_sum, fname)41except Exception as ex:42print(' {}'.format(ex))43print(' FAILURE')44status = False45continue46print(' SUCCESS')47return status4849def print_progress(self, msg, timeout = 0):50if time.time() - self.tick > timeout:51print(msg, end='')52sys.stdout.flush()53self.tick = time.time()5455def buffered_read(self, in_stream, processing):56self.print_progress(' >')57while True:58buf = in_stream.read(self.BUFSIZE)59if not buf:60break61processing(buf)62self.print_progress('>', 5)63print(' done')6465def verify(self, hash_sum, fname):66sha = hashlib.sha1()67with open(fname, 'rb') as file_stream:68self.buffered_read(file_stream, sha.update)69if hash_sum != sha.hexdigest():70raise HashMismatchException(hash_sum, sha.hexdigest())7172if __name__ == '__main__':73sys.exit(0 if MetalinkDownloader().download('weights.meta4') else 1)747576