Skip to content

[HfFileSystem] Fix end-of-file read() #3080

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/huggingface_hub/hf_file_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -1009,7 +1009,9 @@ def read(self, length=-1):
"""
if self.mode == "rb" and (length is None or length == -1) and self.loc == 0:
with self.fs.open(self.path, "rb", block_size=0) as f: # block_size=0 enables fast streaming
return f.read()
out = f.read()
self.loc += len(out)
return out
return super().read(length)

def url(self) -> str:
Expand Down Expand Up @@ -1057,7 +1059,7 @@ def seek(self, loc: int, whence: int = 0):

def read(self, length: int = -1):
read_args = (length,) if length >= 0 else ()
if self.response is None or self.response.raw.isclosed():
if self.response is None:
url = hf_hub_url(
repo_id=self.resolved_path.repo_id,
revision=self.resolved_path.revision,
Expand Down
2 changes: 2 additions & 0 deletions tests/test_hf_file_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,13 @@ def test_read_file(self):
self.assertIsInstance(f, io.TextIOWrapper)
self.assertIsInstance(f.buffer, HfFileSystemFile)
self.assertEqual(f.read(), "dummy text data")
self.assertEqual(f.read(), "")

def test_stream_file(self):
with self.hffs.open(self.hf_path + "/data/binary_data.bin", block_size=0) as f:
self.assertIsInstance(f, HfFileSystemStreamFile)
self.assertEqual(f.read(), b"dummy binary data")
self.assertEqual(f.read(), b"")

def test_stream_file_retry(self):
with self.hffs.open(self.hf_path + "/data/binary_data.bin", block_size=0) as f:
Expand Down