Skip to content

Commit 8f7d0d0

Browse files
authored
Parse file size in get_hf_file_metadata (#1179)
* Parse file size in get_hf_file_metadata * quality
1 parent 7839da3 commit 8f7d0d0

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

src/huggingface_hub/file_download.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,11 +145,14 @@ class HfFileMetadata:
145145
Etag of the file on the server.
146146
location (`str`):
147147
Location where to download the file. Can be a Hub url or not (CDN).
148+
size (`size`):
149+
Size of the file.
148150
"""
149151

150152
commit_hash: Optional[str]
151153
etag: Optional[str]
152154
location: str
155+
size: Optional[int]
153156

154157

155158
@validate_hf_hub_args
@@ -1351,7 +1354,7 @@ def get_hf_file_metadata(
13511354
How many seconds to wait for the server to send metadata before giving up.
13521355
13531356
Returns:
1354-
A [`HfFileMetadata`] object containing metadata such as location, etag and
1357+
A [`HfFileMetadata`] object containing metadata such as location, etag, size and
13551358
commit_hash.
13561359
"""
13571360
headers = build_hf_headers(token=token)
@@ -1381,4 +1384,12 @@ def get_hf_file_metadata(
13811384
# Do not use directly `url`, as `_request_wrapper` might have followed relative
13821385
# redirects.
13831386
location=r.headers.get("Location") or r.request.url, # type: ignore
1387+
size=_int_or_none(r.headers.get("Content-Length")),
13841388
)
1389+
1390+
1391+
def _int_or_none(value: Optional[str]) -> Optional[int]:
1392+
try:
1393+
return int(value) # type: ignore
1394+
except (TypeError, ValueError):
1395+
return None

tests/test_file_download.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,7 @@ def test_get_hf_file_metadata_basic(self) -> None:
359359
)
360360
self.assertIsNotNone(metadata.etag) # example: "85c2fc2dcdd86563aaa85ef4911..."
361361
self.assertEqual(metadata.location, url) # no redirect
362+
self.assertEqual(metadata.size, 851)
362363

363364
def test_get_hf_file_metadata_from_a_renamed_repo(self) -> None:
364365
"""Test getting metadata from a file in a renamed repo on the Hub."""

0 commit comments

Comments
 (0)