_lfs.py 3.8 KB

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