Skip to content
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

Fix caching error when offline and no refs dir #1307

Merged
merged 1 commit into from
Jan 25, 2023
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
22 changes: 14 additions & 8 deletions src/huggingface_hub/file_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -1177,18 +1177,24 @@ def hf_hub_download(
"We have no connection or you passed local_files_only, so"
" force_download is not an accepted option."
)

# Try to get "commit_hash" from "revision"
commit_hash = None
if REGEX_COMMIT_HASH.match(revision):
commit_hash = revision
else:
ref_path = os.path.join(storage_folder, "refs", revision)
with open(ref_path) as f:
commit_hash = f.read()

pointer_path = os.path.join(
storage_folder, "snapshots", commit_hash, relative_filename
)
if os.path.exists(pointer_path):
return pointer_path
if os.path.isfile(ref_path):
with open(ref_path) as f:
commit_hash = f.read()

# Return pointer file if exists
if commit_hash is not None:
pointer_path = os.path.join(
storage_folder, "snapshots", commit_hash, relative_filename
)
if os.path.exists(pointer_path):
return pointer_path

# If we couldn't find an appropriate file on disk,
# raise an error.
Expand Down
18 changes: 18 additions & 0 deletions tests/test_file_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,24 @@ def test_hf_hub_download_with_empty_subfolder(self):
self.assertEqual(filepath.name, CONFIG_NAME)
self.assertEqual(Path(filepath).parent.parent.name, "snapshots")

def test_hf_hub_download_offline_no_refs(self):
"""Regression test for #1305.

If "refs/" dir did not exists on "local_files_only" (or connection broken), a
non-explicit `FileNotFoundError` was raised (for the "/refs/revision" file) instead
of the documented `LocalEntryNotFoundError` (for the actual searched file).

See https://github.com/huggingface/huggingface_hub/issues/1305.
"""
with SoftTemporaryDirectory() as cache_dir:
with self.assertRaises(LocalEntryNotFoundError):
hf_hub_download(
DUMMY_MODEL_ID,
filename=CONFIG_NAME,
local_files_only=True,
cache_dir=cache_dir,
)

def test_hf_hub_url_with_empty_subfolder(self):
"""
Check subfolder arg is processed correctly when empty string is passed to
Expand Down