# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/01m_utils.download.ipynb.

# %% auto 0
__all__ = ['download', 'download_and_extract', 'download_gdrive', 'download_and_extract_gdrive']

# %% ../../nbs/01m_utils.download.ipynb 2
from fastcore.all import *
import polvo as pv

# %% ../../nbs/01m_utils.download.ipynb 4
def download(url, save_dir, chunk_size=1024):
    """Download file from url"""
    import requests
    r = requests.get(url, stream=True)
    save_path = Path(save_dir)/Path(url).name
    with open(str(save_path), "wb") as f:
        bar_total = r.headers.get("Content-Length")
        bar = pv.pbar(unit="B", total=int(bar_total) if bar_total else None)
        for chunk in r.iter_content(chunk_size=chunk_size):
            if chunk:  # filter out keep-alive new chunks
                bar.update(len(chunk))
                f.write(chunk)
    return save_path

# %% ../../nbs/01m_utils.download.ipynb 5
def download_and_extract(url, save_dir, chunk_size=1024):
    save_path = download(url=str(url), save_dir=save_dir, chunk_size=chunk_size)
    import shutil; shutil.unpack_archive(filename=str(save_path), extract_dir=str(save_dir))
    return save_dir

# %% ../../nbs/01m_utils.download.ipynb 7
def download_gdrive(url):
    """Download from gdrive, passing virus scan for big files."""
    import gdown
    return gdown.download(url=str(url), quiet=False)

# %% ../../nbs/01m_utils.download.ipynb 8
def download_and_extract_gdrive(url, extract_dir):
    extract_dir = Path(extract_dir)
    extract_dir.mkdir(exist_ok=True, parents=True)

    filename = download_gdrive(url=url)
    import shutil; shutil.unpack_archive(filename=filename, extract_dir=str(extract_dir))
