Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't hard-require tqdm for downloads #102

Merged
merged 2 commits into from
May 23, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 30 additions & 24 deletions valohai/internals/download.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,41 @@
import contextlib
import os
import tempfile


# TODO: This is close to valohai-local-run. Possibility to merge.
def download_url(url: str, path: str, force_download: bool = False) -> str:
if not os.path.isfile(path) or force_download:
try:
import requests
from tqdm import tqdm
except ImportError as ie:
raise RuntimeError(
f"The `requests` and `tqdm` modules must be available "
f"for download support (attempting to download {url})"
) from ie

tmp_path = tempfile.NamedTemporaryFile().name
print(f"Downloading {url} -> {path}") # noqa
r = requests.get(url, stream=True)
r.raise_for_status()
total = (
int(r.headers["content-length"]) if "content-length" in r.headers else None
)

with tqdm(total=total, unit="iB", unit_scale=True) as t, open(
tmp_path, "wb"
) as f:
for data in r.iter_content(1048576):
t.update(len(data))
f.write(data)
os.replace(tmp_path, path)
_do_download(url, path)
else:
print(f"Using cached {path}") # noqa

return path


def _do_download(url: str, path: str) -> None:
try:
import requests
except ImportError as ie:
raise RuntimeError(
f"The `requests` module must be available for download support (attempting to download {url})"
) from ie

tmp_path = tempfile.NamedTemporaryFile().name
print(f"Downloading {url} -> {path}") # noqa
r = requests.get(url, stream=True)
r.raise_for_status()
total = int(r.headers["content-length"]) if "content-length" in r.headers else None
try:
from tqdm import tqdm

prog = tqdm(total=total, unit="iB", unit_scale=True)
except ImportError:
prog = contextlib.nullcontext()

with prog, open(tmp_path, "wb") as f:
for chunk in r.iter_content(1048576):
if prog:
prog.update(len(chunk))
f.write(chunk)
os.replace(tmp_path, path)