Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/dnn/face_detector/download_weights.py
16337 views
1
#!/usr/bin/env python
2
3
from __future__ import print_function
4
import hashlib
5
import time
6
import sys
7
import xml.etree.ElementTree as ET
8
if sys.version_info[0] < 3:
9
from urllib2 import urlopen
10
else:
11
from urllib.request import urlopen
12
13
class HashMismatchException(Exception):
14
def __init__(self, expected, actual):
15
Exception.__init__(self)
16
self.expected = expected
17
self.actual = actual
18
def __str__(self):
19
return 'Hash mismatch: {} vs {}'.format(self.expected, self.actual)
20
21
class MetalinkDownloader(object):
22
BUFSIZE = 10*1024*1024
23
NS = {'ml': 'urn:ietf:params:xml:ns:metalink'}
24
tick = 0
25
26
def download(self, metalink_file):
27
status = True
28
for file_elem in ET.parse(metalink_file).getroot().findall('ml:file', self.NS):
29
url = file_elem.find('ml:url', self.NS).text
30
fname = file_elem.attrib['name']
31
hash_sum = file_elem.find('ml:hash', self.NS).text
32
print('*** {}'.format(fname))
33
try:
34
self.verify(hash_sum, fname)
35
except Exception as ex:
36
print(' {}'.format(ex))
37
try:
38
print(' {}'.format(url))
39
with open(fname, 'wb') as file_stream:
40
self.buffered_read(urlopen(url), file_stream.write)
41
self.verify(hash_sum, fname)
42
except Exception as ex:
43
print(' {}'.format(ex))
44
print(' FAILURE')
45
status = False
46
continue
47
print(' SUCCESS')
48
return status
49
50
def print_progress(self, msg, timeout = 0):
51
if time.time() - self.tick > timeout:
52
print(msg, end='')
53
sys.stdout.flush()
54
self.tick = time.time()
55
56
def buffered_read(self, in_stream, processing):
57
self.print_progress(' >')
58
while True:
59
buf = in_stream.read(self.BUFSIZE)
60
if not buf:
61
break
62
processing(buf)
63
self.print_progress('>', 5)
64
print(' done')
65
66
def verify(self, hash_sum, fname):
67
sha = hashlib.sha1()
68
with open(fname, 'rb') as file_stream:
69
self.buffered_read(file_stream, sha.update)
70
if hash_sum != sha.hexdigest():
71
raise HashMismatchException(hash_sum, sha.hexdigest())
72
73
if __name__ == '__main__':
74
sys.exit(0 if MetalinkDownloader().download('weights.meta4') else 1)
75
76