|
| 1 | +# coding=utf-8 |
| 2 | +# Copyright 2019-present, the HuggingFace Inc. team. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +"""Git LFS related utilities""" |
| 16 | + |
| 17 | +import io |
| 18 | +import os |
| 19 | +from contextlib import AbstractContextManager |
| 20 | +from typing import BinaryIO |
| 21 | + |
| 22 | + |
| 23 | +class SliceFileObj(AbstractContextManager): |
| 24 | + """ |
| 25 | + Utility context manager to read a *slice* of a seekable file-like object as a seekable, file-like object. |
| 26 | +
|
| 27 | + This is NOT thread safe |
| 28 | +
|
| 29 | + Inspired by stackoverflow.com/a/29838711/593036 |
| 30 | +
|
| 31 | + Credits to @julien-c |
| 32 | +
|
| 33 | + Args: |
| 34 | + fileobj (`BinaryIO`): |
| 35 | + A file-like object to slice. MUST implement `tell()` and `seek()` (and `read()` of course). |
| 36 | + `fileobj` will be reset to its original position when exiting the context manager. |
| 37 | + seek_from (`int`): |
| 38 | + The start of the slice (offset from position 0 in bytes). |
| 39 | + read_limit (`int`): |
| 40 | + The maximum number of bytes to read from the slice. |
| 41 | +
|
| 42 | + Attributes: |
| 43 | + previous_position (`int`): |
| 44 | + The previous position |
| 45 | +
|
| 46 | + Examples: |
| 47 | +
|
| 48 | + Reading 200 bytes with an offset of 128 bytes from a file (ie bytes 128 to 327): |
| 49 | + ```python |
| 50 | + >>> with open("path/to/file", "rb") as file: |
| 51 | + ... with SliceFileObj(file, seek_from=128, read_limit=200) as fslice: |
| 52 | + ... fslice.read(...) |
| 53 | + ``` |
| 54 | +
|
| 55 | + Reading a file in chunks of 512 bytes |
| 56 | + ```python |
| 57 | + >>> import os |
| 58 | + >>> chunk_size = 512 |
| 59 | + >>> file_size = os.getsize("path/to/file") |
| 60 | + >>> with open("path/to/file", "rb") as file: |
| 61 | + ... for chunk_idx in range(ceil(file_size / chunk_size)): |
| 62 | + ... with SliceFileObj(file, seek_from=chunk_idx * chunk_size, read_limit=chunk_size) as fslice: |
| 63 | + ... chunk = fslice.read(...) |
| 64 | +
|
| 65 | + ``` |
| 66 | + """ |
| 67 | + |
| 68 | + def __init__(self, fileobj: BinaryIO, seek_from: int, read_limit: int): |
| 69 | + self.fileobj = fileobj |
| 70 | + self.seek_from = seek_from |
| 71 | + self.read_limit = read_limit |
| 72 | + |
| 73 | + def __enter__(self): |
| 74 | + self._previous_position = self.fileobj.tell() |
| 75 | + end_of_stream = self.fileobj.seek(0, os.SEEK_END) |
| 76 | + self._len = min(self.read_limit, end_of_stream - self.seek_from) |
| 77 | + # ^^ The actual number of bytes that can be read from the slice |
| 78 | + self.fileobj.seek(self.seek_from, io.SEEK_SET) |
| 79 | + return self |
| 80 | + |
| 81 | + def __exit__(self, exc_type, exc_value, traceback): |
| 82 | + self.fileobj.seek(self._previous_position, io.SEEK_SET) |
| 83 | + |
| 84 | + def read(self, n: int = -1): |
| 85 | + pos = self.tell() |
| 86 | + if pos >= self._len: |
| 87 | + return b"" |
| 88 | + remaining_amount = self._len - pos |
| 89 | + data = self.fileobj.read(remaining_amount if n < 0 else min(n, remaining_amount)) |
| 90 | + return data |
| 91 | + |
| 92 | + def tell(self) -> int: |
| 93 | + return self.fileobj.tell() - self.seek_from |
| 94 | + |
| 95 | + def seek(self, offset: int, whence: int = os.SEEK_SET) -> int: |
| 96 | + start = self.seek_from |
| 97 | + end = start + self._len |
| 98 | + if whence in (os.SEEK_SET, os.SEEK_END): |
| 99 | + offset = start + offset if whence == os.SEEK_SET else end + offset |
| 100 | + offset = max(start, min(offset, end)) |
| 101 | + whence = os.SEEK_SET |
| 102 | + elif whence == os.SEEK_CUR: |
| 103 | + cur_pos = self.fileobj.tell() |
| 104 | + offset = max(start - cur_pos, min(offset, end - cur_pos)) |
| 105 | + else: |
| 106 | + raise ValueError(f"whence value {whence} is not supported") |
| 107 | + return self.fileobj.seek(offset, whence) - self.seek_from |
| 108 | + |
| 109 | + def __iter__(self): |
| 110 | + yield self.read(n=4 * 1024 * 1024) |
0 commit comments