File size: 6,963 Bytes
15c46ce
 
 
 
 
 
 
 
1c9b5b6
15c46ce
 
 
 
 
 
 
 
 
 
 
 
1c9b5b6
15c46ce
 
 
1c9b5b6
15c46ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c9b5b6
 
 
 
 
 
 
15c46ce
1c9b5b6
 
 
15c46ce
 
 
 
 
 
1c9b5b6
15c46ce
1c9b5b6
 
 
15c46ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c9b5b6
15c46ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c9b5b6
15c46ce
 
1c9b5b6
 
 
 
 
 
 
 
 
 
15c46ce
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
"""Resumable parallel public downloads, with trusted SHA verification before rename."""
import concurrent.futures
import hashlib
import json
import math
import threading
import time
from pathlib import Path
from urllib.parse import urlparse

import requests

LOCAL = threading.local()


def session():
    if not hasattr(LOCAL, "session"):
        LOCAL.session = requests.Session()
    return LOCAL.session


def download(url, target, size, sha256=None, git_sha1=None, workers=6, seed_prefix=None, fallback_url=None, s3_etag=None):
    target = Path(target)
    target.parent.mkdir(parents=True, exist_ok=True)
    if target.is_file() and target.stat().st_size == size:
        verify(target, size, sha256, git_sha1, s3_etag)
        print("Verified existing " + target.name, flush=True)
        return
    parts = target.parent / (target.name + ".parts8")
    parts.mkdir(exist_ok=True)
    chunk_size = 8 * 1024 * 1024
    count = math.ceil(size/chunk_size)
    old_parts = target.parent / (target.name + ".parts")
    if old_parts.is_dir():
        # Reuse ranges fetched by the earlier 64 MiB layout.
        for old_piece in old_parts.iterdir():
            if not old_piece.name.isdigit():
                continue
            first = int(old_piece.name)*8
            with old_piece.open('rb') as source:
                for offset in range(8):
                    block = source.read(chunk_size)
                    if not block:
                        break
                    piece = parts / f"{first+offset:06d}"
                    if not piece.exists() or piece.stat().st_size < len(block):
                        piece.write_bytes(block)
    if seed_prefix:
        with Path(seed_prefix).open("rb") as source:
            for i in range(min(count, Path(seed_prefix).stat().st_size//chunk_size)):
                piece = parts / f"{i:06d}"
                if piece.is_file() and piece.stat().st_size == chunk_size:
                    source.seek(chunk_size, 1)
                else:
                    piece.write_bytes(source.read(chunk_size))

    def transfer(i):
        start = i*chunk_size
        end = min(size, start+chunk_size)-1
        piece = parts / f"{i:06d}"
        if piece.is_file() and piece.stat().st_size == end-start+1:
            return i
        for retry in range(12):
            try:
                completed = piece.stat().st_size if piece.exists() else 0
                if completed > end-start+1:
                    completed = 0
                if completed == end-start+1:
                    return i
                range_start = start+completed
                active_url = fallback_url if fallback_url and retry % 2 else url
                headers = {"Range": f"bytes={range_start}-{end}"}
                if urlparse(active_url).hostname == 'huggingface.co':
                    from huggingface_hub import get_token
                    token = get_token()
                    if token:
                        headers['Authorization'] = 'Bearer '+token
                # Anonymous request: no cached HF token is forwarded to mirrors.
                request_start = time.monotonic()
                with session().get(active_url + ("&" if "?" in active_url else "?") + f"range_part={i}_{range_start}_{retry}",
                                   headers=headers, stream=True, timeout=(30, 30)) as response:
                    response.raise_for_status()
                    expected = f"bytes {range_start}-{end}/{size}"
                    full_response = range_start == 0 and end == size-1 and response.status_code == 200
                    if not full_response and (response.status_code != 206 or response.headers.get("Content-Range") != expected):
                        raise IOError("Server returned an unexpected byte range")
                    with piece.open("ab" if completed else "wb") as output:
                        for block in response.iter_content(64*1024):
                            output.write(block)
                            completed += len(block)
                            if time.monotonic()-request_start > 45 and completed < end-start+1:
                                raise TimeoutError('Refreshing a slow range connection; partial bytes retained')
                if piece.stat().st_size != end-start+1:
                    raise IOError("Truncated byte range")
                print(f"{target.name}: part {i+1}/{count} complete", flush=True)
                return i
            except Exception as exc:
                print(f"{target.name}: retry {retry+1} part {i+1}: {type(exc).__name__}: {exc}", flush=True)
                if retry == 11:
                    raise
                time.sleep(2)

    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
        list(pool.map(transfer, range(count)))
    partial = target.with_name(target.name + ".verified-part")
    with partial.open("wb") as output:
        for i in range(count):
            with (parts / f"{i:06d}").open("rb") as source:
                while True:
                    block = source.read(8*1024*1024)
                    if not block:
                        break
                    output.write(block)
    verify(partial, size, sha256, git_sha1, s3_etag)
    partial.replace(target)
    # Only remove exact temporary files created by this downloader.
    for i in range(count):
        piece = parts / f"{i:06d}"
        if piece.parent.resolve() != parts.resolve():
            raise ValueError("Unexpected cleanup path")
        piece.unlink()
    parts.rmdir()
    if old_parts.is_dir():
        for old_piece in old_parts.iterdir():
            if old_piece.name.isdigit() and old_piece.is_file():
                old_piece.unlink()
        if not any(old_parts.iterdir()):
            old_parts.rmdir()
    print("SHA verified: " + target.name, flush=True)


def verify(path, size, sha256=None, git_sha1=None, s3_etag=None):
    if Path(path).stat().st_size != size:
        raise ValueError("Unexpected file size")
    if s3_etag:
        digest = hashlib.md5()
        count = 0
        with Path(path).open('rb') as source:
            for block in iter(lambda: source.read(8*1024*1024), b''):
                digest.update(hashlib.md5(block).digest())
                count += 1
        if f'{digest.hexdigest()}-{count}' != s3_etag.strip('"'):
            raise ValueError('Official S3 multipart ETag mismatch')
        return
    digest = hashlib.sha256() if sha256 else hashlib.sha1()
    if not sha256:
        if not git_sha1:
            raise ValueError("Trusted digest is required")
        digest.update(f"blob {size}\0".encode())
    with Path(path).open("rb") as source:
        while True:
            block = source.read(8*1024*1024)
            if not block:
                break
            digest.update(block)
    if digest.hexdigest() != (sha256 or git_sha1):
        raise ValueError("Digest mismatch; file was not accepted")