def download_file(url, binary=True): if sys.version_info < (3, ): from urlparse import urlsplit import urllib2 request = urllib2 error = urllib2 else: from urllib.parse import urlsplit from urllib import request, error filename = os.path.basename(urlsplit(url)[2]) data_dir = get_writable_path( os.path.join(os.path.dirname(__file__), 'data')) path = os.path.join(data_dir, filename) if os.path.exists(path): return path try: data = request.urlopen(url, timeout=15).read() with open(path, 'wb' if binary else 'w') as f: f.write(data) return path except error.URLError: msg = "could not download test file '{}'".format(url) warnings.warn(msg, RuntimeWarning) raise unittest.SkipTest(msg)
def download_file(url, binary=True): if sys.version_info < (3,): from urlparse import urlsplit import urllib2 request = urllib2 error = urllib2 else: from urllib.parse import urlsplit from urllib import request, error filename = os.path.basename(urlsplit(url)[2]) data_dir = get_writable_path(os.path.join(os.path.dirname(__file__), 'data')) path = os.path.join(data_dir, filename) if os.path.exists(path): return path try: data = request.urlopen(url, timeout=15).read() with open(path, 'wb' if binary else 'w') as f: f.write(data) return path except error.URLError: msg = "could not download test file '{}'".format(url) warnings.warn(msg, RuntimeWarning) raise unittest.SkipTest(msg)
def get_image_from_url(self, url, size=(300, 200)): import os from urllib.parse import urlsplit from urllib import request from PIL import Image from torchvision import transforms from torch._utils_internal import get_writable_path filename = os.path.basename(urlsplit(url)[2]) data_dir = get_writable_path(os.path.join(os.path.dirname(__file__))) path = os.path.join(data_dir, filename) data = request.urlopen(url, timeout=15).read() with open(path, 'wb') as f: f.write(data) image = Image.open(path).convert("RGB") image = image.resize(size, Image.BILINEAR) to_tensor = transforms.ToTensor() return to_tensor(image)