Skip to content

blockdownload API Documentation

check

Check

check a download

Source code in bdown/check.py
 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
class Check:
    """
    check a download
    """

    def __init__(self, args):
        self.args = args
        self.size1 = os.path.getsize(args.file1)
        self.size2 = os.path.getsize(args.file2)
        self.blocksize = args.blocksize
        self.max_mb = min(self.size1, self.size2) // (1024 * 1024) - 1
        self.offsets = self.calculate_offsets()
        self.status_counter = Counter()
        self.quiet = len(self.offsets) > 20

    def calculate_offsets(self):
        start = self.args.start
        step = self.args.step
        count = self.args.count
        factor = self.args.factor
        mode = self.args.mode

        if mode in ("linear", "log"):
            if step is None:
                sys.exit("Error: --step is required for linear/log mode")
            i = 0
            offsets = []
            while True:
                if mode == "linear":
                    mb = start + int(i * step)
                else:
                    base = factor if factor is not None else step
                    mb = start + int(round(base**i))
                if count is not None and i >= count:
                    break
                if mb > self.max_mb:
                    break
                offsets.append(mb)
                i += 1
            return [mb * 1024 * 1024 for mb in offsets]

        elif mode == "full":
            return [mb * 1024 * 1024 for mb in range(0, self.max_mb + 1)]

        else:
            sys.exit(f"Unsupported mode: {mode}")

    def is_zero_block(self, data):
        return all(b == 0 for b in data)

    def read_block(self, f, offset):
        f.seek(offset)
        return f.read(self.blocksize)

    def status(self, index, symbol, offset_mb, message):
        self.status_counter[symbol] += 1
        if not self.quiet:
            print(f"[{index:3}] {offset_mb:7,} MB  {symbol}  {message}")

    def run(self):
        with open(self.args.file1, "rb") as f1, open(self.args.file2, "rb") as f2:
            iterator = enumerate(self.offsets)
            if self.quiet and tqdm:
                iterator = tqdm(iterator, total=len(self.offsets))
            for i, offset in iterator:
                offset_mb = offset // (1024 * 1024)
                b1 = self.read_block(f1, offset)
                b2 = self.read_block(f2, offset)

                if (
                    not b1
                    or not b2
                    or len(b1) < self.blocksize
                    or len(b2) < self.blocksize
                ):
                    self.status(i, FAIL, offset_mb, "could not read full block")
                    continue

                zero1 = self.is_zero_block(b1)
                zero2 = self.is_zero_block(b2)
                if zero1 or zero2:
                    who = []
                    if zero1:
                        who.append("file1")
                    if zero2:
                        who.append("file2")
                    self.status(i, WARN, offset_mb, f"zero block in {', '.join(who)}")
                    continue

                md5_1 = hashlib.md5(b1).hexdigest()
                md5_2 = hashlib.md5(b2).hexdigest()
                if md5_1 == md5_2:
                    self.status(i, CHECK, offset_mb, "MD5 match")
                else:
                    self.status(i, FAIL, offset_mb, "MD5 mismatch")
                    if not self.quiet:
                        print(f"           file1: {md5_1}")
                        print(f"           file2: {md5_2}")

        print()
        print("Summary:", dict(self.status_counter))

download

Created on 2025-05-05

@author: wf

Block

A single download block.

Source code in bdown/download.py
 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
@lod_storable
class Block:
    """
    A single download block.
    """

    block: int
    path: str
    offset: int
    md5: str = None  # full md5 hash
    md5_head: str = None  # hash of first chunk

    def calc_md5(self, base_path: str, chunk_size: int = 8192, chunk_limit: int = None) -> str:
        """
        Calculate the MD5 checksum of this block's file.

        Args:
            base_path: Directory where the block's relative path is located.
            chunk_size: Bytes per read operation (default: 8192).
            chunk_limit: Maximum number of chunks to read (e.g. 1 for md5_head).

        Returns:
            str: The MD5 hexadecimal digest.
        """
        full_path = os.path.join(base_path, self.path)
        hash_md5 = hashlib.md5()
        index = 0

        with open(full_path, "rb") as f:
            for chunk in iter(lambda: f.read(chunk_size), b""):
                hash_md5.update(chunk)
                index += 1
                if chunk_limit is not None and index >= chunk_limit:
                    break

        return hash_md5.hexdigest()


    @classmethod
    def ofResponse(
        cls,
        block_index: int,
        offset: int,
        chunk_size: int,
        target_path: str,
        response: requests.Response,
        progress_bar=None,
    ) -> "Block":
        """
        Create a Block from a download HTTP response.

        Args:
            block_index: Index of the block.
            offset: Byte offset within the full file.
            target_path: Path to the .part file to write.
            response: The HTTP response streaming the content.
            progress_bar: optional progress_bar for reporting download progress.

        Returns:
            Block: The constructed block with calculated md5.
        """
        hash_md5 = hashlib.md5()
        hash_head = hashlib.md5()
        first = True
        block_path=os.path.basename(target_path)
        if progress_bar:
            progress_bar.set_description(block_path)
        with open(target_path, "wb") as f:
            for chunk in response.iter_content(chunk_size=chunk_size):
                f.write(chunk)
                hash_md5.update(chunk)
                if first:
                    hash_head.update(chunk)
                    first = False
                if progress_bar:
                    progress_bar.update(len(chunk))
        block = cls(
            block=block_index,
            path=block_path,
            offset=offset,
            md5=hash_md5.hexdigest(),
            md5_head=hash_head.hexdigest(),
        )
        return block

calc_md5(base_path, chunk_size=8192, chunk_limit=None)

Calculate the MD5 checksum of this block's file.

Parameters:

Name Type Description Default
base_path str

Directory where the block's relative path is located.

required
chunk_size int

Bytes per read operation (default: 8192).

8192
chunk_limit int

Maximum number of chunks to read (e.g. 1 for md5_head).

None

Returns:

Name Type Description
str str

The MD5 hexadecimal digest.

Source code in bdown/download.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def calc_md5(self, base_path: str, chunk_size: int = 8192, chunk_limit: int = None) -> str:
    """
    Calculate the MD5 checksum of this block's file.

    Args:
        base_path: Directory where the block's relative path is located.
        chunk_size: Bytes per read operation (default: 8192).
        chunk_limit: Maximum number of chunks to read (e.g. 1 for md5_head).

    Returns:
        str: The MD5 hexadecimal digest.
    """
    full_path = os.path.join(base_path, self.path)
    hash_md5 = hashlib.md5()
    index = 0

    with open(full_path, "rb") as f:
        for chunk in iter(lambda: f.read(chunk_size), b""):
            hash_md5.update(chunk)
            index += 1
            if chunk_limit is not None and index >= chunk_limit:
                break

    return hash_md5.hexdigest()

ofResponse(block_index, offset, chunk_size, target_path, response, progress_bar=None) classmethod

Create a Block from a download HTTP response.

Parameters:

Name Type Description Default
block_index int

Index of the block.

required
offset int

Byte offset within the full file.

required
target_path str

Path to the .part file to write.

required
response Response

The HTTP response streaming the content.

required
progress_bar

optional progress_bar for reporting download progress.

None

Returns:

Name Type Description
Block Block

The constructed block with calculated md5.

Source code in bdown/download.py
 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
@classmethod
def ofResponse(
    cls,
    block_index: int,
    offset: int,
    chunk_size: int,
    target_path: str,
    response: requests.Response,
    progress_bar=None,
) -> "Block":
    """
    Create a Block from a download HTTP response.

    Args:
        block_index: Index of the block.
        offset: Byte offset within the full file.
        target_path: Path to the .part file to write.
        response: The HTTP response streaming the content.
        progress_bar: optional progress_bar for reporting download progress.

    Returns:
        Block: The constructed block with calculated md5.
    """
    hash_md5 = hashlib.md5()
    hash_head = hashlib.md5()
    first = True
    block_path=os.path.basename(target_path)
    if progress_bar:
        progress_bar.set_description(block_path)
    with open(target_path, "wb") as f:
        for chunk in response.iter_content(chunk_size=chunk_size):
            f.write(chunk)
            hash_md5.update(chunk)
            if first:
                hash_head.update(chunk)
                first = False
            if progress_bar:
                progress_bar.update(len(chunk))
    block = cls(
        block=block_index,
        path=block_path,
        offset=offset,
        md5=hash_md5.hexdigest(),
        md5_head=hash_head.hexdigest(),
    )
    return block

BlockDownload

Source code in bdown/download.py
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
@lod_storable
class BlockDownload:
    name: str
    url: str
    blocksize: int
    chunk_size: int = 8192  # size of a response chunk
    size: int = None
    unit: str = "MB"  # KB, MB, or GB
    md5: str = ""
    blocks: List[Block] = field(default_factory=list)

    def __post_init__(self):
        self.unit_multipliers = {
            "KB": 1024,
            "MB": 1024 * 1024,
            "GB": 1024 * 1024 * 1024,
        }
        if self.unit not in self.unit_multipliers:
            raise ValueError(f"Unsupported unit: {self.unit} - must be KB, MB or GB")
        self.lock = Lock()
        self.active_blocks = set()
        self.progress_lock = Lock()

    @property
    def blocksize_bytes(self) -> int:
        return self.blocksize * self.unit_multipliers[self.unit]

    def block_range_str(self) -> str:
        if not self.active_blocks:
            range_str="∅"
        else:
            min_block = min(self.active_blocks)
            max_block = max(self.active_blocks)
            range_str=f"{min_block}" if min_block == max_block else f"{min_block}{max_block}"
        return range_str

    @classmethod
    def ofYamlPath(cls, yaml_path: str):
        block_download = cls.load_from_yaml_file(yaml_path)
        block_download.yaml_path = yaml_path
        return block_download

    def save(self):
        if hasattr(self, "yaml_path") and self.yaml_path:
            self.save_to_yaml_file(self.yaml_path)

    def _get_remote_file_size(self) -> int:
        response = requests.head(self.url, allow_redirects=True)
        response.raise_for_status()
        return int(response.headers.get("Content-Length", 0))

    def block_ranges(
        self, from_block: int, to_block: int
    ) -> List[Tuple[int, int, int]]:
        """
        Generate a list of (index, start, end) tuples for the given block range.

        Args:
            from_block: Index of first block.
            to_block: Index of last block (inclusive).

        Returns:
            List of (index, start, end).
        """
        if self.size is None:
            self.size = self._get_remote_file_size()
        result = []
        block_size = self.blocksize_bytes
        for index in range(from_block, to_block + 1):
            start = index * block_size
            end = min(start + block_size - 1, self.size - 1)
            result.append((index, start, end))
        return result

    def compute_total_bytes(
        self, from_block: int, to_block: int=None
    ) -> Tuple[int, int, int]:
        """
        Compute the total number of bytes to download for a block range.

        Args:
            from_block: First block index.
            to_block: Last block index (inclusive), or None for all blocks.

        Returns:
            Tuple of (from_block, to_block, total_bytes).
        """
        if self.size is None:
            self.size = self._get_remote_file_size()
        total_blocks = (self.size + self.blocksize_bytes - 1) // self.blocksize_bytes
        if to_block is None or to_block >= total_blocks:
            to_block = total_blocks - 1

        total_bytes = 0
        for _, start, end in self.block_ranges(from_block, to_block):
            total_bytes += end - start + 1

        return from_block, to_block, total_bytes

    def download(
        self,
        target: str,
        from_block: int = 0,
        to_block: int = None,
        boost: int = 1,
        progress_bar=None,
    ):
        """
        Download selected blocks and save them to individual .part files.

        Args:
            target: Directory to store .part files.
            from_block: Index of the first block to download.
            to_block: Index of the last block (inclusive), or None to download until end.
            boost: Number of parallel download threads to use (default: 1 = serial).
            progress_bar: Optional tqdm-compatible progress bar for visual feedback.
        """
        if self.size is None:
            self.size = self._get_remote_file_size()
        os.makedirs(target, exist_ok=True)

        if to_block is None:
            total_blocks = (self.size + self.blocksize_bytes - 1) // self.blocksize_bytes
            to_block = total_blocks - 1

        block_specs = self.block_ranges(from_block, to_block)

        if boost == 1:
            for index, start, end in block_specs:
                self._download_block(index, start, end, target, progress_bar)
        else:
            with ThreadPoolExecutor(max_workers=boost) as executor:
                for index, start, end in block_specs:
                    executor.submit(self._download_block, index, start, end, target, progress_bar)


    def update_progress(self,progress_bar,index:int):
        with self.progress_lock:
            if index>0:
                self.active_blocks.add(index)
            else:
                self.active_blocks.remove(-index)
            if progress_bar:
                progress_bar.set_description(f"Blocks {self.block_range_str()}")

    def _download_block(self, index: int, start: int, end: int, target: str, progress_bar):
        part_name = f"{self.name}-{index:04d}.part"
        part_file = os.path.join(target, part_name)

        if index < len(self.blocks):
            existing = self.blocks[index]
            if os.path.exists(part_file) and existing.md5_head:
                actual_head = existing.calc_md5(
                    base_path=target,
                    chunk_size=self.chunk_size,
                    chunk_limit=1
                )
                if actual_head == existing.md5_head:
                    if progress_bar:
                        progress_bar.set_description(part_name)
                        progress_bar.update(end - start + 1)
                    return

        self.update_progress(progress_bar, index+1)
        headers = {"Range": f"bytes={start}-{end}"}
        response = requests.get(self.url, headers=headers, stream=True)
        if response.status_code not in (200, 206):
            raise Exception(f"HTTP {response.status_code}: {response.text}")

        block = Block.ofResponse(
            block_index=index,
            offset=start,
            chunk_size=self.chunk_size,
            target_path=part_file,
            response=response,
            progress_bar=progress_bar,
        )

        with self.lock:
            if index < len(self.blocks):
                self.blocks[index] = block
            else:
                self.blocks.append(block)
            self.save()
        self.update_progress(progress_bar, -(index+1))

    def get_progress_bar(self, from_block: int, to_block: int):
        _, _, total_bytes = self.compute_total_bytes(from_block, to_block)
        progress_bar = tqdm(total=total_bytes, unit="B", unit_scale=True)
        return progress_bar

block_ranges(from_block, to_block)

Generate a list of (index, start, end) tuples for the given block range.

Parameters:

Name Type Description Default
from_block int

Index of first block.

required
to_block int

Index of last block (inclusive).

required

Returns:

Type Description
List[Tuple[int, int, int]]

List of (index, start, end).

Source code in bdown/download.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def block_ranges(
    self, from_block: int, to_block: int
) -> List[Tuple[int, int, int]]:
    """
    Generate a list of (index, start, end) tuples for the given block range.

    Args:
        from_block: Index of first block.
        to_block: Index of last block (inclusive).

    Returns:
        List of (index, start, end).
    """
    if self.size is None:
        self.size = self._get_remote_file_size()
    result = []
    block_size = self.blocksize_bytes
    for index in range(from_block, to_block + 1):
        start = index * block_size
        end = min(start + block_size - 1, self.size - 1)
        result.append((index, start, end))
    return result

compute_total_bytes(from_block, to_block=None)

Compute the total number of bytes to download for a block range.

Parameters:

Name Type Description Default
from_block int

First block index.

required
to_block int

Last block index (inclusive), or None for all blocks.

None

Returns:

Type Description
Tuple[int, int, int]

Tuple of (from_block, to_block, total_bytes).

Source code in bdown/download.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def compute_total_bytes(
    self, from_block: int, to_block: int=None
) -> Tuple[int, int, int]:
    """
    Compute the total number of bytes to download for a block range.

    Args:
        from_block: First block index.
        to_block: Last block index (inclusive), or None for all blocks.

    Returns:
        Tuple of (from_block, to_block, total_bytes).
    """
    if self.size is None:
        self.size = self._get_remote_file_size()
    total_blocks = (self.size + self.blocksize_bytes - 1) // self.blocksize_bytes
    if to_block is None or to_block >= total_blocks:
        to_block = total_blocks - 1

    total_bytes = 0
    for _, start, end in self.block_ranges(from_block, to_block):
        total_bytes += end - start + 1

    return from_block, to_block, total_bytes

download(target, from_block=0, to_block=None, boost=1, progress_bar=None)

Download selected blocks and save them to individual .part files.

Parameters:

Name Type Description Default
target str

Directory to store .part files.

required
from_block int

Index of the first block to download.

0
to_block int

Index of the last block (inclusive), or None to download until end.

None
boost int

Number of parallel download threads to use (default: 1 = serial).

1
progress_bar

Optional tqdm-compatible progress bar for visual feedback.

None
Source code in bdown/download.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def download(
    self,
    target: str,
    from_block: int = 0,
    to_block: int = None,
    boost: int = 1,
    progress_bar=None,
):
    """
    Download selected blocks and save them to individual .part files.

    Args:
        target: Directory to store .part files.
        from_block: Index of the first block to download.
        to_block: Index of the last block (inclusive), or None to download until end.
        boost: Number of parallel download threads to use (default: 1 = serial).
        progress_bar: Optional tqdm-compatible progress bar for visual feedback.
    """
    if self.size is None:
        self.size = self._get_remote_file_size()
    os.makedirs(target, exist_ok=True)

    if to_block is None:
        total_blocks = (self.size + self.blocksize_bytes - 1) // self.blocksize_bytes
        to_block = total_blocks - 1

    block_specs = self.block_ranges(from_block, to_block)

    if boost == 1:
        for index, start, end in block_specs:
            self._download_block(index, start, end, target, progress_bar)
    else:
        with ThreadPoolExecutor(max_workers=boost) as executor:
            for index, start, end in block_specs:
                executor.submit(self._download_block, index, start, end, target, progress_bar)

download_cmd

Command-line interface for BlockDownload

Created on 2025-05-05

@author: wf