Debian Codegraph @

imageio/core/fetching.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Based on code from the vispy project
3 # Distributed under the (new) BSD License. See LICENSE.txt for more info.
4
5 """Data downloading and reading functions"""
6
7 from math import log
8 import os
9 from os import path as op
10 import sys
11 import shutil
12 import time
13
14 from . import appdata_dir, resource_dirs
15 from . import StdoutProgressIndicator, urlopen
16
17
18 class InternetNotAllowedError(IOError):
19 """Plugins that need resources can just use get_remote_file(), but
20 should catch this error and silently ignore it.
21 """
22
23 pass
24
25
26 class NeedDownloadError(IOError):
27 """Is raised when a remote file is requested that is not locally
28 available, but which needs to be explicitly downloaded by the user.
29 """
30
31
32 def get_remote_file(fname, directory=None, force_download=False, auto=True):
33 """Get a the filename for the local version of a file from the web
34
35 Parameters
36 ----------
37 fname : str
38 The relative filename on the remote data repository to download.
39 These correspond to paths on
40 ``https://github.com/imageio/imageio-binaries/``.
41 directory : str | None
42 The directory where the file will be cached if a download was
43 required to obtain the file. By default, the appdata directory
44 is used. This is also the first directory that is checked for
45 a local version of the file. If the directory does not exist,
46 it will be created.
47 force_download : bool | str
48 If True, the file will be downloaded even if a local copy exists
49 (and this copy will be overwritten). Can also be a YYYY-MM-DD date
50 to ensure a file is up-to-date (modified date of a file on disk,
51 if present, is checked).
52 auto : bool
53 Whether to auto-download the file if its not present locally. Default
54 True. If False and a download is needed, raises NeedDownloadError.
55
56 Returns
57 -------
58 fname : str
59 The path to the file on the local system.
60 """
61 _url_root = "https://github.com/imageio/imageio-binaries/raw/master/"
62 url = _url_root + fname
63 nfname = op.normcase(fname) # convert to native
64 # Get dirs to look for the resource
65 given_directory = directory
66 directory = given_directory or appdata_dir("imageio")
67 dirs = resource_dirs()
68 dirs.insert(0, directory) # Given dir has preference
69 # Try to find the resource locally
70 for dir in dirs:
71 filename = op.join(dir, nfname)
72 if op.isfile(filename):
73 if not force_download: # we're done
74 if given_directory and given_directory != dir:
75 filename2 = os.path.join(given_directory, nfname)
76 # Make sure the output directory exists
77 if not op.isdir(op.dirname(filename2)):
78 os.makedirs(op.abspath(op.dirname(filename2)))
79 shutil.copy(filename, filename2)
80 return filename2
81 return filename
82 if isinstance(force_download, str):
83 ntime = time.strptime(force_download, "%Y-%m-%d")
84 ftime = time.gmtime(op.getctime(filename))
85 if ftime >= ntime:
86 if given_directory and given_directory != dir:
87 filename2 = os.path.join(given_directory, nfname)
88 # Make sure the output directory exists
89 if not op.isdir(op.dirname(filename2)):
90 os.makedirs(op.abspath(op.dirname(filename2)))
91 shutil.copy(filename, filename2)
92 return filename2
93 return filename
94 else:
95 print("File older than %s, updating..." % force_download)
96 break
97
98 # If we get here, we're going to try to download the file
99 if os.getenv("IMAGEIO_NO_INTERNET", "").lower() in ("1", "true", "yes"):
100 raise InternetNotAllowedError(
101 "Will not download resource from the "
102 "internet because environment variable "
103 "IMAGEIO_NO_INTERNET is set."
104 )
105
106 # Can we proceed with auto-download?
107 if not auto:
108 raise NeedDownloadError()
109
110 # Get filename to store to and make sure the dir exists
111 filename = op.join(directory, nfname)
112 if not op.isdir(op.dirname(filename)):
113 os.makedirs(op.abspath(op.dirname(filename)))
114 # let's go get the file
115 if os.getenv("CI"): # pragma: no cover
116 # On CI, we retry a few times ...
117 for i in range(2):
118 try:
119 _fetch_file(url, filename)
120 return filename
121 except IOError:
122 time.sleep(0.5)
123 else:
124 _fetch_file(url, filename)
125 return filename
126 else: # pragma: no cover
127 _fetch_file(url, filename)
128 return filename
129
130
131 def _fetch_file(url, file_name, print_destination=True):
132 """Load requested file, downloading it if needed or requested
133
134 Parameters
135 ----------
136 url: string
137 The url of file to be downloaded.
138 file_name: string
139 Name, along with the path, of where downloaded file will be saved.
140 print_destination: bool, optional
141 If true, destination of where file was saved will be printed after
142 download finishes.
143 resume: bool, optional
144 If true, try to resume partially downloaded files.
145 """
146 # Adapted from NISL:
147 # https://github.com/nisl/tutorial/blob/master/nisl/datasets.py
148
149 print(
150 "Imageio: %r was not found on your computer; "
151 "downloading it now." % os.path.basename(file_name)
152 )
153
154 temp_file_name = file_name + ".part"
155 local_file = None
156 initial_size = 0
157 errors = []
158 for tries in range(4):
159 try:
160 # Checking file size and displaying it alongside the download url
161 remote_file = urlopen(url, timeout=5.0)
162 file_size = int(remote_file.headers["Content-Length"].strip())
163 size_str = _sizeof_fmt(file_size)
164 print("Try %i. Download from %s (%s)" % (tries + 1, url, size_str))
165 # Downloading data (can be extended to resume if need be)
166 local_file = open(temp_file_name, "wb")
167 _chunk_read(remote_file, local_file, initial_size=initial_size)
168 # temp file must be closed prior to the move
169 if not local_file.closed:
170 local_file.close()
171 shutil.move(temp_file_name, file_name)
172 if print_destination is True:
173 sys.stdout.write("File saved as %s.\n" % file_name)
174 break
175 except Exception as e:
176 errors.append(e)
177 print("Error while fetching file: %s." % str(e))
178 finally:
179 if local_file is not None:
180 if not local_file.closed:
181 local_file.close()
182 else:
183 raise IOError(
184 "Unable to download %r. Perhaps there is no internet "
185 "connection? If there is, please report this problem."
186 % os.path.basename(file_name)
187 )
188
189
190 def _chunk_read(response, local_file, chunk_size=8192, initial_size=0):
191 """Download a file chunk by chunk and show advancement
192
193 Can also be used when resuming downloads over http.
194
195 Parameters
196 ----------
197 response: urllib.response.addinfourl
198 Response to the download request in order to get file size.
199 local_file: file
200 Hard disk file where data should be written.
201 chunk_size: integer, optional
202 Size of downloaded chunks. Default: 8192
203 initial_size: int, optional
204 If resuming, indicate the initial size of the file.
205 """
206 # Adapted from NISL:
207 # https://github.com/nisl/tutorial/blob/master/nisl/datasets.py
208
209 bytes_so_far = initial_size
210 # Returns only amount left to download when resuming, not the size of the
211 # entire file
212 total_size = int(response.headers["Content-Length"].strip())
213 total_size += initial_size
214
215 progress = StdoutProgressIndicator("Downloading")
216 progress.start("", "bytes", total_size)
217
218 while True:
219 chunk = response.read(chunk_size)
220 bytes_so_far += len(chunk)
221 if not chunk:
222 break
223 _chunk_write(chunk, local_file, progress)
224 progress.finish("Done")
225
226
227 def _chunk_write(chunk, local_file, progress):
228 """Write a chunk to file and update the progress bar"""
229 local_file.write(chunk)
230 progress.increase_progress(len(chunk))
231 time.sleep(0) # Give other threads a chance, e.g. those that handle stdout pipes
232
233
234 def _sizeof_fmt(num):
235 """Turn number of bytes into human-readable str"""
236 units = ["bytes", "kB", "MB", "GB", "TB", "PB"]
237 decimals = [0, 0, 1, 2, 2, 2]
238 """Human friendly file size"""
239 if num > 1:
240 exponent = min(int(log(num, 1024)), len(units) - 1)
241 quotient = float(num) / 1024**exponent
242 unit = units[exponent]
243 num_decimals = decimals[exponent]
244 format_string = "{0:.%sf} {1}" % num_decimals
245 return format_string.format(quotient, unit)
246 return "0 bytes" if num == 0 else "1 byte"