-
Notifications
You must be signed in to change notification settings - Fork 571
/
hf_api.py
9780 lines (8619 loc) · 419 KB
/
hf_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
# Copyright 2019-present, the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import inspect
import json
import re
import struct
import warnings
from collections import defaultdict
from concurrent.futures import Future, ThreadPoolExecutor
from dataclasses import asdict, dataclass, field
from datetime import datetime
from functools import wraps
from itertools import islice
from pathlib import Path
from typing import (
Any,
BinaryIO,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Optional,
Tuple,
TypeVar,
Union,
overload,
)
from urllib.parse import quote
import requests
from requests.exceptions import HTTPError
from tqdm.auto import tqdm as base_tqdm
from tqdm.contrib.concurrent import thread_map
from . import constants
from ._commit_api import (
CommitOperation,
CommitOperationAdd,
CommitOperationCopy,
CommitOperationDelete,
_fetch_files_to_copy,
_fetch_upload_modes,
_prepare_commit_payload,
_upload_lfs_files,
_warn_on_overwriting_operations,
)
from ._inference_endpoints import InferenceEndpoint, InferenceEndpointType
from ._multi_commits import (
MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_BAD_REQUEST_TEMPLATE,
MULTI_COMMIT_PR_CLOSE_COMMENT_FAILURE_NO_CHANGES_TEMPLATE,
MULTI_COMMIT_PR_CLOSING_COMMENT_TEMPLATE,
MULTI_COMMIT_PR_COMPLETION_COMMENT_TEMPLATE,
MultiCommitException,
MultiCommitStep,
MultiCommitStrategy,
multi_commit_create_pull_request,
multi_commit_generate_comment,
multi_commit_parse_pr_description,
plan_multi_commits,
)
from ._space_api import SpaceHardware, SpaceRuntime, SpaceStorage, SpaceVariable
from ._upload_large_folder import upload_large_folder_internal
from .community import (
Discussion,
DiscussionComment,
DiscussionStatusChange,
DiscussionTitleChange,
DiscussionWithDetails,
deserialize_event,
)
from .constants import (
DEFAULT_ETAG_TIMEOUT, # noqa: F401 # kept for backward compatibility
DEFAULT_REQUEST_TIMEOUT, # noqa: F401 # kept for backward compatibility
DEFAULT_REVISION, # noqa: F401 # kept for backward compatibility
DISCUSSION_STATUS, # noqa: F401 # kept for backward compatibility
DISCUSSION_TYPES, # noqa: F401 # kept for backward compatibility
ENDPOINT, # noqa: F401 # kept for backward compatibility
INFERENCE_ENDPOINTS_ENDPOINT, # noqa: F401 # kept for backward compatibility
REGEX_COMMIT_OID, # noqa: F401 # kept for backward compatibility
REPO_TYPE_MODEL, # noqa: F401 # kept for backward compatibility
REPO_TYPES, # noqa: F401 # kept for backward compatibility
REPO_TYPES_MAPPING, # noqa: F401 # kept for backward compatibility
REPO_TYPES_URL_PREFIXES, # noqa: F401 # kept for backward compatibility
SAFETENSORS_INDEX_FILE, # noqa: F401 # kept for backward compatibility
SAFETENSORS_MAX_HEADER_LENGTH, # noqa: F401 # kept for backward compatibility
SAFETENSORS_SINGLE_FILE, # noqa: F401 # kept for backward compatibility
SPACES_SDK_TYPES, # noqa: F401 # kept for backward compatibility
WEBHOOK_DOMAIN_T, # noqa: F401 # kept for backward compatibility
DiscussionStatusFilter, # noqa: F401 # kept for backward compatibility
DiscussionTypeFilter, # noqa: F401 # kept for backward compatibility
)
from .errors import (
BadRequestError,
EntryNotFoundError,
GatedRepoError,
HfHubHTTPError,
RepositoryNotFoundError,
RevisionNotFoundError,
)
from .file_download import HfFileMetadata, get_hf_file_metadata, hf_hub_url
from .repocard_data import DatasetCardData, ModelCardData, SpaceCardData
from .utils import (
DEFAULT_IGNORE_PATTERNS,
HfFolder, # noqa: F401 # kept for backward compatibility
LocalTokenNotFoundError,
NotASafetensorsRepoError,
SafetensorsFileMetadata,
SafetensorsParsingError,
SafetensorsRepoMetadata,
TensorInfo,
build_hf_headers,
experimental,
filter_repo_objects,
fix_hf_endpoint_in_url,
get_session,
hf_raise_for_status,
logging,
paginate,
parse_datetime,
validate_hf_hub_args,
)
from .utils import tqdm as hf_tqdm
from .utils._typing import CallableT
from .utils.endpoint_helpers import _is_emission_within_threshold
R = TypeVar("R") # Return type
CollectionItemType_T = Literal["model", "dataset", "space", "paper"]
ExpandModelProperty_T = Literal[
"author",
"baseModels",
"cardData",
"childrenModelCount",
"config",
"createdAt",
"disabled",
"downloads",
"downloadsAllTime",
"gated",
"inference",
"lastModified",
"library_name",
"likes",
"mask_token",
"model-index",
"pipeline_tag",
"private",
"safetensors",
"sha",
"siblings",
"spaces",
"tags",
"transformersInfo",
"trendingScore",
"widgetData",
]
ExpandDatasetProperty_T = Literal[
"author",
"cardData",
"citation",
"createdAt",
"disabled",
"description",
"downloads",
"downloadsAllTime",
"gated",
"lastModified",
"likes",
"paperswithcode_id",
"private",
"siblings",
"sha",
"trendingScore",
"tags",
]
ExpandSpaceProperty_T = Literal[
"author",
"cardData",
"createdAt",
"datasets",
"disabled",
"lastModified",
"likes",
"models",
"private",
"runtime",
"sdk",
"siblings",
"sha",
"subdomain",
"tags",
"trendingScore",
]
USERNAME_PLACEHOLDER = "hf_user"
_REGEX_DISCUSSION_URL = re.compile(r".*/discussions/(\d+)$")
_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE = (
"\nNote: Creating a commit assumes that the repo already exists on the"
" Huggingface Hub. Please use `create_repo` if it's not the case."
)
_AUTH_CHECK_NO_REPO_ERROR_MESSAGE = (
"\nNote: The repository either does not exist or you do not have access rights."
" Please check the repository ID and your access permissions."
" If this is a private repository, ensure that your token is correct."
)
logger = logging.get_logger(__name__)
def repo_type_and_id_from_hf_id(hf_id: str, hub_url: Optional[str] = None) -> Tuple[Optional[str], Optional[str], str]:
"""
Returns the repo type and ID from a huggingface.co URL linking to a
repository
Args:
hf_id (`str`):
An URL or ID of a repository on the HF hub. Accepted values are:
- https://huggingface.co/<repo_type>/<namespace>/<repo_id>
- https://huggingface.co/<namespace>/<repo_id>
- hf://<repo_type>/<namespace>/<repo_id>
- hf://<namespace>/<repo_id>
- <repo_type>/<namespace>/<repo_id>
- <namespace>/<repo_id>
- <repo_id>
hub_url (`str`, *optional*):
The URL of the HuggingFace Hub, defaults to https://huggingface.co
Returns:
A tuple with three items: repo_type (`str` or `None`), namespace (`str` or
`None`) and repo_id (`str`).
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If URL cannot be parsed.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If `repo_type` is unknown.
"""
input_hf_id = hf_id
hub_url = re.sub(r"https?://", "", hub_url if hub_url is not None else constants.ENDPOINT)
is_hf_url = hub_url in hf_id and "@" not in hf_id
HFFS_PREFIX = "hf://"
if hf_id.startswith(HFFS_PREFIX): # Remove "hf://" prefix if exists
hf_id = hf_id[len(HFFS_PREFIX) :]
url_segments = hf_id.split("/")
is_hf_id = len(url_segments) <= 3
namespace: Optional[str]
if is_hf_url:
namespace, repo_id = url_segments[-2:]
if namespace == hub_url:
namespace = None
if len(url_segments) > 2 and hub_url not in url_segments[-3]:
repo_type = url_segments[-3]
elif namespace in constants.REPO_TYPES_MAPPING:
# Mean canonical dataset or model
repo_type = constants.REPO_TYPES_MAPPING[namespace]
namespace = None
else:
repo_type = None
elif is_hf_id:
if len(url_segments) == 3:
# Passed <repo_type>/<user>/<model_id> or <repo_type>/<org>/<model_id>
repo_type, namespace, repo_id = url_segments[-3:]
elif len(url_segments) == 2:
if url_segments[0] in constants.REPO_TYPES_MAPPING:
# Passed '<model_id>' or 'datasets/<dataset_id>' for a canonical model or dataset
repo_type = constants.REPO_TYPES_MAPPING[url_segments[0]]
namespace = None
repo_id = hf_id.split("/")[-1]
else:
# Passed <user>/<model_id> or <org>/<model_id>
namespace, repo_id = hf_id.split("/")[-2:]
repo_type = None
else:
# Passed <model_id>
repo_id = url_segments[0]
namespace, repo_type = None, None
else:
raise ValueError(f"Unable to retrieve user and repo ID from the passed HF ID: {hf_id}")
# Check if repo type is known (mapping "spaces" => "space" + empty value => `None`)
if repo_type in constants.REPO_TYPES_MAPPING:
repo_type = constants.REPO_TYPES_MAPPING[repo_type]
if repo_type == "":
repo_type = None
if repo_type not in constants.REPO_TYPES:
raise ValueError(f"Unknown `repo_type`: '{repo_type}' ('{input_hf_id}')")
return repo_type, namespace, repo_id
@dataclass
class LastCommitInfo(dict):
oid: str
title: str
date: datetime
def __post_init__(self): # hack to make LastCommitInfo backward compatible
self.update(asdict(self))
@dataclass
class BlobLfsInfo(dict):
size: int
sha256: str
pointer_size: int
def __post_init__(self): # hack to make BlobLfsInfo backward compatible
self.update(asdict(self))
@dataclass
class BlobSecurityInfo(dict):
safe: bool
av_scan: Optional[Dict]
pickle_import_scan: Optional[Dict]
def __post_init__(self): # hack to make BlogSecurityInfo backward compatible
self.update(asdict(self))
@dataclass
class TransformersInfo(dict):
auto_model: str
custom_class: Optional[str] = None
# possible `pipeline_tag` values: https://github.com/huggingface/huggingface.js/blob/3ee32554b8620644a6287e786b2a83bf5caf559c/packages/tasks/src/pipelines.ts#L72
pipeline_tag: Optional[str] = None
processor: Optional[str] = None
def __post_init__(self): # hack to make TransformersInfo backward compatible
self.update(asdict(self))
@dataclass
class SafeTensorsInfo(dict):
parameters: List[Dict[str, int]]
total: int
def __post_init__(self): # hack to make SafeTensorsInfo backward compatible
self.update(asdict(self))
@dataclass
class CommitInfo(str):
"""Data structure containing information about a newly created commit.
Returned by any method that creates a commit on the Hub: [`create_commit`], [`upload_file`], [`upload_folder`],
[`delete_file`], [`delete_folder`]. It inherits from `str` for backward compatibility but using methods specific
to `str` is deprecated.
Attributes:
commit_url (`str`):
Url where to find the commit.
commit_message (`str`):
The summary (first line) of the commit that has been created.
commit_description (`str`):
Description of the commit that has been created. Can be empty.
oid (`str`):
Commit hash id. Example: `"91c54ad1727ee830252e457677f467be0bfd8a57"`.
pr_url (`str`, *optional*):
Url to the PR that has been created, if any. Populated when `create_pr=True`
is passed.
pr_revision (`str`, *optional*):
Revision of the PR that has been created, if any. Populated when
`create_pr=True` is passed. Example: `"refs/pr/1"`.
pr_num (`int`, *optional*):
Number of the PR discussion that has been created, if any. Populated when
`create_pr=True` is passed. Can be passed as `discussion_num` in
[`get_discussion_details`]. Example: `1`.
repo_url (`RepoUrl`):
Repo URL of the commit containing info like repo_id, repo_type, etc.
_url (`str`, *optional*):
Legacy url for `str` compatibility. Can be the url to the uploaded file on the Hub (if returned by
[`upload_file`]), to the uploaded folder on the Hub (if returned by [`upload_folder`]) or to the commit on
the Hub (if returned by [`create_commit`]). Defaults to `commit_url`. It is deprecated to use this
attribute. Please use `commit_url` instead.
"""
commit_url: str
commit_message: str
commit_description: str
oid: str
pr_url: Optional[str] = None
# Computed from `commit_url` in `__post_init__`
repo_url: RepoUrl = field(init=False)
# Computed from `pr_url` in `__post_init__`
pr_revision: Optional[str] = field(init=False)
pr_num: Optional[str] = field(init=False)
# legacy url for `str` compatibility (ex: url to uploaded file, url to uploaded folder, url to PR, etc.)
_url: str = field(repr=False, default=None) # type: ignore # defaults to `commit_url`
def __new__(cls, *args, commit_url: str, _url: Optional[str] = None, **kwargs):
return str.__new__(cls, _url or commit_url)
def __post_init__(self):
"""Populate pr-related fields after initialization.
See https://docs.python.org/3.10/library/dataclasses.html#post-init-processing.
"""
# Repo info
self.repo_url = RepoUrl(self.commit_url.split("/commit/")[0])
# PR info
if self.pr_url is not None:
self.pr_revision = _parse_revision_from_pr_url(self.pr_url)
self.pr_num = int(self.pr_revision.split("/")[-1])
else:
self.pr_revision = None
self.pr_num = None
@dataclass
class AccessRequest:
"""Data structure containing information about a user access request.
Attributes:
username (`str`):
Username of the user who requested access.
fullname (`str`):
Fullname of the user who requested access.
email (`Optional[str]`):
Email of the user who requested access.
Can only be `None` in the /accepted list if the user was granted access manually.
timestamp (`datetime`):
Timestamp of the request.
status (`Literal["pending", "accepted", "rejected"]`):
Status of the request. Can be one of `["pending", "accepted", "rejected"]`.
fields (`Dict[str, Any]`, *optional*):
Additional fields filled by the user in the gate form.
"""
username: str
fullname: str
email: Optional[str]
timestamp: datetime
status: Literal["pending", "accepted", "rejected"]
# Additional fields filled by the user in the gate form
fields: Optional[Dict[str, Any]] = None
@dataclass
class WebhookWatchedItem:
"""Data structure containing information about the items watched by a webhook.
Attributes:
type (`Literal["dataset", "model", "org", "space", "user"]`):
Type of the item to be watched. Can be one of `["dataset", "model", "org", "space", "user"]`.
name (`str`):
Name of the item to be watched. Can be the username, organization name, model name, dataset name or space name.
"""
type: Literal["dataset", "model", "org", "space", "user"]
name: str
@dataclass
class WebhookInfo:
"""Data structure containing information about a webhook.
Attributes:
id (`str`):
ID of the webhook.
url (`str`):
URL of the webhook.
watched (`List[WebhookWatchedItem]`):
List of items watched by the webhook, see [`WebhookWatchedItem`].
domains (`List[WEBHOOK_DOMAIN_T]`):
List of domains the webhook is watching. Can be one of `["repo", "discussions"]`.
secret (`str`, *optional*):
Secret of the webhook.
disabled (`bool`):
Whether the webhook is disabled or not.
"""
id: str
url: str
watched: List[WebhookWatchedItem]
domains: List[constants.WEBHOOK_DOMAIN_T]
secret: Optional[str]
disabled: bool
class RepoUrl(str):
"""Subclass of `str` describing a repo URL on the Hub.
`RepoUrl` is returned by `HfApi.create_repo`. It inherits from `str` for backward
compatibility. At initialization, the URL is parsed to populate properties:
- endpoint (`str`)
- namespace (`Optional[str]`)
- repo_name (`str`)
- repo_id (`str`)
- repo_type (`Literal["model", "dataset", "space"]`)
- url (`str`)
Args:
url (`Any`):
String value of the repo url.
endpoint (`str`, *optional*):
Endpoint of the Hub. Defaults to <https://huggingface.co>.
Example:
```py
>>> RepoUrl('https://huggingface.co/gpt2')
RepoUrl('https://huggingface.co/gpt2', endpoint='https://huggingface.co', repo_type='model', repo_id='gpt2')
>>> RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co')
RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co', repo_type='dataset', repo_id='dummy_user/dummy_dataset')
>>> RepoUrl('hf://datasets/my-user/my-dataset')
RepoUrl('hf://datasets/my-user/my-dataset', endpoint='https://huggingface.co', repo_type='dataset', repo_id='user/dataset')
>>> HfApi.create_repo("dummy_model")
RepoUrl('https://huggingface.co/Wauplin/dummy_model', endpoint='https://huggingface.co', repo_type='model', repo_id='Wauplin/dummy_model')
```
Raises:
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If URL cannot be parsed.
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
If `repo_type` is unknown.
"""
def __new__(cls, url: Any, endpoint: Optional[str] = None):
url = fix_hf_endpoint_in_url(url, endpoint=endpoint)
return super(RepoUrl, cls).__new__(cls, url)
def __init__(self, url: Any, endpoint: Optional[str] = None) -> None:
super().__init__()
# Parse URL
self.endpoint = endpoint or constants.ENDPOINT
repo_type, namespace, repo_name = repo_type_and_id_from_hf_id(self, hub_url=self.endpoint)
# Populate fields
self.namespace = namespace
self.repo_name = repo_name
self.repo_id = repo_name if namespace is None else f"{namespace}/{repo_name}"
self.repo_type = repo_type or constants.REPO_TYPE_MODEL
self.url = str(self) # just in case it's needed
def __repr__(self) -> str:
return f"RepoUrl('{self}', endpoint='{self.endpoint}', repo_type='{self.repo_type}', repo_id='{self.repo_id}')"
@dataclass
class RepoSibling:
"""
Contains basic information about a repo file inside a repo on the Hub.
<Tip>
All attributes of this class are optional except `rfilename`. This is because only the file names are returned when
listing repositories on the Hub (with [`list_models`], [`list_datasets`] or [`list_spaces`]). If you need more
information like file size, blob id or lfs details, you must request them specifically from one repo at a time
(using [`model_info`], [`dataset_info`] or [`space_info`]) as it adds more constraints on the backend server to
retrieve these.
</Tip>
Attributes:
rfilename (str):
file name, relative to the repo root.
size (`int`, *optional*):
The file's size, in bytes. This attribute is defined when `files_metadata` argument of [`repo_info`] is set
to `True`. It's `None` otherwise.
blob_id (`str`, *optional*):
The file's git OID. This attribute is defined when `files_metadata` argument of [`repo_info`] is set to
`True`. It's `None` otherwise.
lfs (`BlobLfsInfo`, *optional*):
The file's LFS metadata. This attribute is defined when`files_metadata` argument of [`repo_info`] is set to
`True` and the file is stored with Git LFS. It's `None` otherwise.
"""
rfilename: str
size: Optional[int] = None
blob_id: Optional[str] = None
lfs: Optional[BlobLfsInfo] = None
@dataclass
class RepoFile:
"""
Contains information about a file on the Hub.
Attributes:
path (str):
file path relative to the repo root.
size (`int`):
The file's size, in bytes.
blob_id (`str`):
The file's git OID.
lfs (`BlobLfsInfo`):
The file's LFS metadata.
last_commit (`LastCommitInfo`, *optional*):
The file's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
are called with `expand=True`.
security (`BlobSecurityInfo`, *optional*):
The file's security scan metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
are called with `expand=True`.
"""
path: str
size: int
blob_id: str
lfs: Optional[BlobLfsInfo] = None
last_commit: Optional[LastCommitInfo] = None
security: Optional[BlobSecurityInfo] = None
def __init__(self, **kwargs):
self.path = kwargs.pop("path")
self.size = kwargs.pop("size")
self.blob_id = kwargs.pop("oid")
lfs = kwargs.pop("lfs", None)
if lfs is not None:
lfs = BlobLfsInfo(size=lfs["size"], sha256=lfs["oid"], pointer_size=lfs["pointerSize"])
self.lfs = lfs
last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None)
if last_commit is not None:
last_commit = LastCommitInfo(
oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"])
)
self.last_commit = last_commit
security = kwargs.pop("security", None)
if security is not None:
security = BlobSecurityInfo(
safe=security["safe"], av_scan=security["avScan"], pickle_import_scan=security["pickleImportScan"]
)
self.security = security
# backwards compatibility
self.rfilename = self.path
self.lastCommit = self.last_commit
@dataclass
class RepoFolder:
"""
Contains information about a folder on the Hub.
Attributes:
path (str):
folder path relative to the repo root.
tree_id (`str`):
The folder's git OID.
last_commit (`LastCommitInfo`, *optional*):
The folder's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`]
are called with `expand=True`.
"""
path: str
tree_id: str
last_commit: Optional[LastCommitInfo] = None
def __init__(self, **kwargs):
self.path = kwargs.pop("path")
self.tree_id = kwargs.pop("oid")
last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None)
if last_commit is not None:
last_commit = LastCommitInfo(
oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"])
)
self.last_commit = last_commit
@dataclass
class ModelInfo:
"""
Contains information about a model on the Hub.
<Tip>
Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
In general, the more specific the query, the more information is returned. On the contrary, when listing models
using [`list_models`] only a subset of the attributes are returned.
</Tip>
Attributes:
id (`str`):
ID of model.
author (`str`, *optional*):
Author of the model.
sha (`str`, *optional*):
Repo SHA at this particular revision.
created_at (`datetime`, *optional*):
Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
corresponding to the date when we began to store creation dates.
last_modified (`datetime`, *optional*):
Date of last commit to the repo.
private (`bool`):
Is the repo private.
disabled (`bool`, *optional*):
Is the repo disabled.
downloads (`int`):
Number of downloads of the model over the last 30 days.
downloads_all_time (`int`):
Cumulated number of downloads of the model since its creation.
gated (`Literal["auto", "manual", False]`, *optional*):
Is the repo gated.
If so, whether there is manual or automatic approval.
inference (`Literal["cold", "frozen", "warm"]`, *optional*):
Status of the model on the inference API.
Warm models are available for immediate use. Cold models will be loaded on first inference call.
Frozen models are not available in Inference API.
likes (`int`):
Number of likes of the model.
library_name (`str`, *optional*):
Library associated with the model.
tags (`List[str]`):
List of tags of the model. Compared to `card_data.tags`, contains extra tags computed by the Hub
(e.g. supported libraries, model's arXiv).
pipeline_tag (`str`, *optional*):
Pipeline tag associated with the model.
mask_token (`str`, *optional*):
Mask token used by the model.
widget_data (`Any`, *optional*):
Widget data associated with the model.
model_index (`Dict`, *optional*):
Model index for evaluation.
config (`Dict`, *optional*):
Model configuration.
transformers_info (`TransformersInfo`, *optional*):
Transformers-specific info (auto class, processor, etc.) associated with the model.
trending_score (`int`, *optional*):
Trending score of the model.
card_data (`ModelCardData`, *optional*):
Model Card Metadata as a [`huggingface_hub.repocard_data.ModelCardData`] object.
siblings (`List[RepoSibling]`):
List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the model.
spaces (`List[str]`, *optional*):
List of spaces using the model.
safetensors (`SafeTensorsInfo`, *optional*):
Model's safetensors information.
"""
id: str
author: Optional[str]
sha: Optional[str]
created_at: Optional[datetime]
last_modified: Optional[datetime]
private: Optional[bool]
disabled: Optional[bool]
downloads: Optional[int]
downloads_all_time: Optional[int]
gated: Optional[Literal["auto", "manual", False]]
inference: Optional[Literal["warm", "cold", "frozen"]]
likes: Optional[int]
library_name: Optional[str]
tags: Optional[List[str]]
pipeline_tag: Optional[str]
mask_token: Optional[str]
card_data: Optional[ModelCardData]
widget_data: Optional[Any]
model_index: Optional[Dict]
config: Optional[Dict]
transformers_info: Optional[TransformersInfo]
trending_score: Optional[int]
siblings: Optional[List[RepoSibling]]
spaces: Optional[List[str]]
safetensors: Optional[SafeTensorsInfo]
def __init__(self, **kwargs):
self.id = kwargs.pop("id")
self.author = kwargs.pop("author", None)
self.sha = kwargs.pop("sha", None)
last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
self.last_modified = parse_datetime(last_modified) if last_modified else None
created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
self.created_at = parse_datetime(created_at) if created_at else None
self.private = kwargs.pop("private", None)
self.gated = kwargs.pop("gated", None)
self.disabled = kwargs.pop("disabled", None)
self.downloads = kwargs.pop("downloads", None)
self.downloads_all_time = kwargs.pop("downloadsAllTime", None)
self.likes = kwargs.pop("likes", None)
self.library_name = kwargs.pop("library_name", None)
self.inference = kwargs.pop("inference", None)
self.tags = kwargs.pop("tags", None)
self.pipeline_tag = kwargs.pop("pipeline_tag", None)
self.mask_token = kwargs.pop("mask_token", None)
self.trending_score = kwargs.pop("trendingScore", None)
card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
self.card_data = (
ModelCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
)
self.widget_data = kwargs.pop("widgetData", None)
self.model_index = kwargs.pop("model-index", None) or kwargs.pop("model_index", None)
self.config = kwargs.pop("config", None)
transformers_info = kwargs.pop("transformersInfo", None) or kwargs.pop("transformers_info", None)
self.transformers_info = TransformersInfo(**transformers_info) if transformers_info else None
siblings = kwargs.pop("siblings", None)
self.siblings = (
[
RepoSibling(
rfilename=sibling["rfilename"],
size=sibling.get("size"),
blob_id=sibling.get("blobId"),
lfs=(
BlobLfsInfo(
size=sibling["lfs"]["size"],
sha256=sibling["lfs"]["sha256"],
pointer_size=sibling["lfs"]["pointerSize"],
)
if sibling.get("lfs")
else None
),
)
for sibling in siblings
]
if siblings is not None
else None
)
self.spaces = kwargs.pop("spaces", None)
safetensors = kwargs.pop("safetensors", None)
self.safetensors = (
SafeTensorsInfo(
parameters=safetensors["parameters"],
total=safetensors["total"],
)
if safetensors
else None
)
# backwards compatibility
self.lastModified = self.last_modified
self.cardData = self.card_data
self.transformersInfo = self.transformers_info
self.__dict__.update(**kwargs)
@dataclass
class DatasetInfo:
"""
Contains information about a dataset on the Hub.
<Tip>
Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
In general, the more specific the query, the more information is returned. On the contrary, when listing datasets
using [`list_datasets`] only a subset of the attributes are returned.
</Tip>
Attributes:
id (`str`):
ID of dataset.
author (`str`):
Author of the dataset.
sha (`str`):
Repo SHA at this particular revision.
created_at (`datetime`, *optional*):
Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`,
corresponding to the date when we began to store creation dates.
last_modified (`datetime`, *optional*):
Date of last commit to the repo.
private (`bool`):
Is the repo private.
disabled (`bool`, *optional*):
Is the repo disabled.
gated (`Literal["auto", "manual", False]`, *optional*):
Is the repo gated.
If so, whether there is manual or automatic approval.
downloads (`int`):
Number of downloads of the dataset over the last 30 days.
downloads_all_time (`int`):
Cumulated number of downloads of the model since its creation.
likes (`int`):
Number of likes of the dataset.
tags (`List[str]`):
List of tags of the dataset.
card_data (`DatasetCardData`, *optional*):
Model Card Metadata as a [`huggingface_hub.repocard_data.DatasetCardData`] object.
siblings (`List[RepoSibling]`):
List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the dataset.
paperswithcode_id (`str`, *optional*):
Papers with code ID of the dataset.
trending_score (`int`, *optional*):
Trending score of the dataset.
"""
id: str
author: Optional[str]
sha: Optional[str]
created_at: Optional[datetime]
last_modified: Optional[datetime]
private: Optional[bool]
gated: Optional[Literal["auto", "manual", False]]
disabled: Optional[bool]
downloads: Optional[int]
downloads_all_time: Optional[int]
likes: Optional[int]
paperswithcode_id: Optional[str]
tags: Optional[List[str]]
trending_score: Optional[int]
card_data: Optional[DatasetCardData]
siblings: Optional[List[RepoSibling]]
def __init__(self, **kwargs):
self.id = kwargs.pop("id")
self.author = kwargs.pop("author", None)
self.sha = kwargs.pop("sha", None)
created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None)
self.created_at = parse_datetime(created_at) if created_at else None
last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None)
self.last_modified = parse_datetime(last_modified) if last_modified else None
self.private = kwargs.pop("private", None)
self.gated = kwargs.pop("gated", None)
self.disabled = kwargs.pop("disabled", None)
self.downloads = kwargs.pop("downloads", None)
self.downloads_all_time = kwargs.pop("downloadsAllTime", None)
self.likes = kwargs.pop("likes", None)
self.paperswithcode_id = kwargs.pop("paperswithcode_id", None)
self.tags = kwargs.pop("tags", None)
self.trending_score = kwargs.pop("trendingScore", None)
card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None)
self.card_data = (
DatasetCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data
)
siblings = kwargs.pop("siblings", None)
self.siblings = (
[
RepoSibling(
rfilename=sibling["rfilename"],
size=sibling.get("size"),
blob_id=sibling.get("blobId"),
lfs=(
BlobLfsInfo(
size=sibling["lfs"]["size"],
sha256=sibling["lfs"]["sha256"],
pointer_size=sibling["lfs"]["pointerSize"],
)
if sibling.get("lfs")
else None
),
)
for sibling in siblings
]
if siblings is not None
else None
)
# backwards compatibility
self.lastModified = self.last_modified
self.cardData = self.card_data
self.__dict__.update(**kwargs)
@dataclass
class SpaceInfo:
"""
Contains information about a Space on the Hub.
<Tip>
Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made.
In general, the more specific the query, the more information is returned. On the contrary, when listing spaces
using [`list_spaces`] only a subset of the attributes are returned.
</Tip>
Attributes:
id (`str`):
ID of the Space.