from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

try:
    from urllib.request import urlopen  # python 3
except ImportError:
    from urllib2 import urlopen  # python 2
import os
import tarfile
import tempfile
import shutil

dataset = 'images'  # Stanford Dog dataset is called images.tar
url = "http://vision.stanford.edu/aditya86/ImageNetDogs/%s.tar" % dataset
with tempfile.TemporaryFile() as tmp:
    print("downloading", url)
    shutil.copyfileobj(urlopen(url), tmp)
    print("extracting")
    tmp.seek(0)
    tar = tarfile.open(fileobj=tmp)
    tar.extractall()
    tar.close()
    if not os.path.exists('data/'):  # check if data folder does not exist
        os.mkdir('data/')
    print("moving images to data folder")
    folders = os.listdir('Images/')
    for folder in folders:
        files = os.listdir('Images/' + folder + '/')
        for image in files:
            shutil.move('Images/' + folder + '/' + image, 'data/')
        os.rmdir('Images/' + folder + '/')
    os.rmdir('Images/')
    print("done")
