|
| 1 | +# ****************************************************************************** |
| 2 | +# Copyright 2017-2018 Intel Corporation |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# ****************************************************************************** |
| 16 | +""" |
| 17 | +Utilities for working with the local dataset cache. |
| 18 | +""" |
| 19 | +import os |
| 20 | +import logging |
| 21 | +import shutil |
| 22 | +import tempfile |
| 23 | +import json |
| 24 | +from urllib.parse import urlparse |
| 25 | +from pathlib import Path |
| 26 | +from typing import Tuple, Union, IO |
| 27 | +from hashlib import sha256 |
| 28 | + |
| 29 | +from nlp_architect import LIBRARY_OUT |
| 30 | +from nlp_architect.utils.io import load_json_file |
| 31 | + |
| 32 | +import requests |
| 33 | + |
| 34 | +logger = logging.getLogger(__name__) # pylint: disable=invalid-name |
| 35 | + |
| 36 | +MODEL_CACHE = LIBRARY_OUT / 'pretrained_models' |
| 37 | + |
| 38 | + |
| 39 | +def cached_path(url_or_filename: Union[str, Path], cache_dir: str = None) -> str: |
| 40 | + """ |
| 41 | + Given something that might be a URL (or might be a local path), |
| 42 | + determine which. If it's a URL, download the file and cache it, and |
| 43 | + return the path to the cached file. If it's already a local path, |
| 44 | + make sure the file exists and then return the path. |
| 45 | + """ |
| 46 | + if cache_dir is None: |
| 47 | + cache_dir = MODEL_CACHE |
| 48 | + else: |
| 49 | + cache_dir = cache_dir |
| 50 | + if isinstance(url_or_filename, Path): |
| 51 | + url_or_filename = str(url_or_filename) |
| 52 | + |
| 53 | + parsed = urlparse(url_or_filename) |
| 54 | + |
| 55 | + if parsed.scheme in ('http', 'https'): |
| 56 | + # URL, so get it from the cache (downloading if necessary) |
| 57 | + return get_from_cache(url_or_filename, cache_dir) |
| 58 | + if os.path.exists(url_or_filename): |
| 59 | + # File, and it exists. |
| 60 | + print("File already exists. No further processing needed.") |
| 61 | + return url_or_filename |
| 62 | + if parsed.scheme == '': |
| 63 | + # File, but it doesn't exist. |
| 64 | + raise FileNotFoundError("file {} not found".format(url_or_filename)) |
| 65 | + |
| 66 | + # Something unknown |
| 67 | + raise ValueError("unable to parse {} as a URL or as a local path".format(url_or_filename)) |
| 68 | + |
| 69 | + |
| 70 | +def url_to_filename(url: str, etag: str = None) -> str: |
| 71 | + """ |
| 72 | + Convert `url` into a hashed filename in a repeatable way. |
| 73 | + If `etag` is specified, append its hash to the url's, delimited |
| 74 | + by a period. |
| 75 | + """ |
| 76 | + if url.split('/')[-1].endswith('zip'): |
| 77 | + url_bytes = url.encode('utf-8') |
| 78 | + url_hash = sha256(url_bytes) |
| 79 | + filename = url_hash.hexdigest() |
| 80 | + if etag: |
| 81 | + etag_bytes = etag.encode('utf-8') |
| 82 | + etag_hash = sha256(etag_bytes) |
| 83 | + filename += '.' + etag_hash.hexdigest() |
| 84 | + else: |
| 85 | + filename = url.split('/')[-1] |
| 86 | + |
| 87 | + return filename |
| 88 | + |
| 89 | + |
| 90 | +def filename_to_url(filename: str, cache_dir: str = None) -> Tuple[str, str]: |
| 91 | + """ |
| 92 | + Return the url and etag (which may be ``None``) stored for `filename`. |
| 93 | + Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist. |
| 94 | + """ |
| 95 | + if cache_dir is None: |
| 96 | + cache_dir = MODEL_CACHE |
| 97 | + |
| 98 | + cache_path = os.path.join(cache_dir, filename) |
| 99 | + if not os.path.exists(cache_path): |
| 100 | + raise FileNotFoundError("file {} not found".format(cache_path)) |
| 101 | + |
| 102 | + meta_path = cache_path + '.json' |
| 103 | + if not os.path.exists(meta_path): |
| 104 | + raise FileNotFoundError("file {} not found".format(meta_path)) |
| 105 | + |
| 106 | + with open(meta_path) as meta_file: |
| 107 | + metadata = json.load(meta_file) |
| 108 | + url = metadata['url'] |
| 109 | + etag = metadata['etag'] |
| 110 | + |
| 111 | + return url, etag |
| 112 | + |
| 113 | + |
| 114 | +def http_get(url: str, temp_file: IO) -> None: |
| 115 | + req = requests.get(url, stream=True) |
| 116 | + for chunk in req.iter_content(chunk_size=1024): |
| 117 | + if chunk: # filter out keep-alive new chunks |
| 118 | + temp_file.write(chunk) |
| 119 | + |
| 120 | + |
| 121 | +def get_from_cache(url: str, cache_dir: str = None) -> str: |
| 122 | + """ |
| 123 | + Given a URL, look for the corresponding dataset in the local cache. |
| 124 | + If it's not there, download it. Then return the path to the cached file. |
| 125 | + """ |
| 126 | + if cache_dir is None: |
| 127 | + cache_dir = MODEL_CACHE |
| 128 | + |
| 129 | + os.makedirs(cache_dir, exist_ok=True) |
| 130 | + |
| 131 | + response = requests.head(url, allow_redirects=True) |
| 132 | + if response.status_code != 200: |
| 133 | + raise IOError("HEAD request failed for url {} with status code {}" |
| 134 | + .format(url, response.status_code)) |
| 135 | + etag = response.headers.get("ETag") |
| 136 | + |
| 137 | + filename = url_to_filename(url, etag) |
| 138 | + |
| 139 | + # get cache path to put the file |
| 140 | + cache_path = os.path.join(cache_dir, filename) |
| 141 | + |
| 142 | + need_downloading = True |
| 143 | + |
| 144 | + if os.path.exists(cache_path): |
| 145 | + # check if etag has changed comparing with the metadata |
| 146 | + if url.split('/')[-1].endswith('zip'): |
| 147 | + meta_path = cache_path + '.json' |
| 148 | + else: |
| 149 | + meta_path = cache_path + '_meta_' + '.json' |
| 150 | + meta = load_json_file(meta_path) |
| 151 | + if meta['etag'] == etag: |
| 152 | + print('file already present') |
| 153 | + need_downloading = False |
| 154 | + |
| 155 | + if need_downloading: |
| 156 | + print("File not present or etag changed") |
| 157 | + # Download to temporary file, then copy to cache dir once finished. |
| 158 | + # Otherwise you get corrupt cache entries if the download gets interrupted. |
| 159 | + with tempfile.NamedTemporaryFile() as temp_file: |
| 160 | + logger.info("%s not found in cache, downloading to %s", url, temp_file.name) |
| 161 | + |
| 162 | + # GET file object |
| 163 | + http_get(url, temp_file) |
| 164 | + |
| 165 | + # we are copying the file before closing it, so flush to avoid truncation |
| 166 | + temp_file.flush() |
| 167 | + # shutil.copyfileobj() starts at the current position, so go to the start |
| 168 | + temp_file.seek(0) |
| 169 | + |
| 170 | + logger.info("copying %s to cache at %s", temp_file.name, cache_path) |
| 171 | + with open(cache_path, 'wb') as cache_file: |
| 172 | + shutil.copyfileobj(temp_file, cache_file) |
| 173 | + |
| 174 | + logger.info("creating metadata file for %s", cache_path) |
| 175 | + meta = {'url': url, 'etag': etag} |
| 176 | + if url.split('/')[-1].endswith('zip'): |
| 177 | + meta_path = cache_path + '.json' |
| 178 | + else: |
| 179 | + meta_path = cache_path + '_meta_' + '.json' |
| 180 | + with open(meta_path, 'w') as meta_file: |
| 181 | + json.dump(meta, meta_file) |
| 182 | + |
| 183 | + logger.info("removing temp file %s", temp_file.name) |
| 184 | + |
| 185 | + return cache_path, need_downloading |
0 commit comments