| 24 | |
| 25 | |
| 26 | def _download(url: str, root: str = os.path.expanduser("~/.cache/clip")): |
| 27 | os.makedirs(root, exist_ok=True) |
| 28 | filename = os.path.basename(url) |
| 29 | |
| 30 | expected_sha256 = url.split("/")[-2] |
| 31 | download_target = os.path.join(root, filename) |
| 32 | |
| 33 | if os.path.exists(download_target) and not os.path.isfile(download_target): |
| 34 | raise RuntimeError(f"{download_target} exists and is not a regular file") |
| 35 | |
| 36 | if os.path.isfile(download_target): |
| 37 | if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256: |
| 38 | return download_target |
| 39 | else: |
| 40 | warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file") |
| 41 | |
| 42 | with urllib.request.urlopen(url) as source, open(download_target, "wb") as output: |
| 43 | with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True) as loop: |
| 44 | while True: |
| 45 | buffer = source.read(8192) |
| 46 | if not buffer: |
| 47 | break |
| 48 | |
| 49 | output.write(buffer) |
| 50 | loop.update(len(buffer)) |
| 51 | |
| 52 | if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256: |
| 53 | raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match") |
| 54 | |
| 55 | return download_target |
| 56 | |
| 57 | |
| 58 | def _transform(n_px): |