_lfs.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. import io
  17. import os
  18. from contextlib import AbstractContextManager
  19. from typing import BinaryIO
  20. class SliceFileObj(AbstractContextManager):
  21. """
  22. Utility context manager to read a *slice* of a seekable file-like object as a seekable, file-like object.
  23. This is NOT thread safe
  24. Inspired by stackoverflow.com/a/29838711/593036
  25. Credits to @julien-c
  26. Args:
  27. fileobj (`BinaryIO`):
  28. A file-like object to slice. MUST implement `tell()` and `seek()` (and `read()` of course).
  29. `fileobj` will be reset to its original position when exiting the context manager.
  30. seek_from (`int`):
  31. The start of the slice (offset from position 0 in bytes).
  32. read_limit (`int`):
  33. The maximum number of bytes to read from the slice.
  34. Attributes:
  35. previous_position (`int`):
  36. The previous position
  37. Examples:
  38. Reading 200 bytes with an offset of 128 bytes from a file (ie bytes 128 to 327):
  39. ```python
  40. >>> with open("path/to/file", "rb") as file:
  41. ... with SliceFileObj(file, seek_from=128, read_limit=200) as fslice:
  42. ... fslice.read(...)
  43. ```
  44. Reading a file in chunks of 512 bytes
  45. ```python
  46. >>> import os
  47. >>> chunk_size = 512
  48. >>> file_size = os.getsize("path/to/file")
  49. >>> with open("path/to/file", "rb") as file:
  50. ... for chunk_idx in range(ceil(file_size / chunk_size)):
  51. ... with SliceFileObj(file, seek_from=chunk_idx * chunk_size, read_limit=chunk_size) as fslice:
  52. ... chunk = fslice.read(...)
  53. ```
  54. """
  55. def __init__(self, fileobj: BinaryIO, seek_from: int, read_limit: int):
  56. self.fileobj = fileobj
  57. self.seek_from = seek_from
  58. self.read_limit = read_limit
  59. def __enter__(self):
  60. self._previous_position = self.fileobj.tell()
  61. end_of_stream = self.fileobj.seek(0, os.SEEK_END)
  62. self._len = min(self.read_limit, end_of_stream - self.seek_from)
  63. # ^^ The actual number of bytes that can be read from the slice
  64. self.fileobj.seek(self.seek_from, io.SEEK_SET)
  65. return self
  66. def __exit__(self, exc_type, exc_value, traceback):
  67. self.fileobj.seek(self._previous_position, io.SEEK_SET)
  68. def read(self, n: int = -1):
  69. pos = self.tell()
  70. if pos >= self._len:
  71. return b""
  72. remaining_amount = self._len - pos
  73. data = self.fileobj.read(remaining_amount if n < 0 else min(n, remaining_amount))
  74. return data
  75. def tell(self) -> int:
  76. return self.fileobj.tell() - self.seek_from
  77. def seek(self, offset: int, whence: int = os.SEEK_SET) -> int:
  78. start = self.seek_from
  79. end = start + self._len
  80. if whence in (os.SEEK_SET, os.SEEK_END):
  81. offset = start + offset if whence == os.SEEK_SET else end + offset
  82. offset = max(start, min(offset, end))
  83. whence = os.SEEK_SET
  84. elif whence == os.SEEK_CUR:
  85. cur_pos = self.fileobj.tell()
  86. offset = max(start - cur_pos, min(offset, end - cur_pos))
  87. else:
  88. raise ValueError(f"whence value {whence} is not supported")
  89. return self.fileobj.seek(offset, whence) - self.seek_from
  90. def __iter__(self):
  91. yield self.read(n=4 * 1024 * 1024)