# AUTOGENERATED! DO NOT EDIT! File to edit: ../01_io.ipynb.

# %% auto 0
__all__ = ['download_from_url']

# %% ../01_io.ipynb 3
import httpx
from pathlib import Path

import rich.progress

# %% ../01_io.ipynb 4
def download_from_url(
    url: str, # url to download
    dst: Path, # the path of the destination file
    chunk_size=2048 # optional chunk_size for response.iter_bytes
) -> int:  # the file size
    if dst.exists():
        file_size = dst.stat().st_size
        if file_size > 0:
            # return early if file was already downloaded
            return file_size
        
    with dst.open("ab") as download_file:
        with httpx.stream("GET", url) as response:
            total = int(response.headers["Content-Length"])
    
            with rich.progress.Progress(
                "[progress.percentage]{task.percentage:>3.0f}%",
                rich.progress.BarColumn(bar_width=None),
                rich.progress.DownloadColumn(),
                rich.progress.TransferSpeedColumn(),
                refresh_per_second=5,
            ) as progress:
                download_task = progress.add_task("Download", total=total)
                for chunk in response.iter_bytes(chunk_size=chunk_size):
                    download_file.write(chunk)
                    progress.update(download_task, completed=response.num_bytes_downloaded, refresh=True)
    return response.num_bytes_downloaded
