huggingface-hub 0.27.0rc1__py3-none-any.whl → 0.28.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of huggingface-hub might be problematic. Click here for more details.

Files changed (40) hide show
  1. huggingface_hub/__init__.py +418 -12
  2. huggingface_hub/_commit_api.py +33 -4
  3. huggingface_hub/_inference_endpoints.py +8 -2
  4. huggingface_hub/_local_folder.py +14 -3
  5. huggingface_hub/commands/scan_cache.py +1 -1
  6. huggingface_hub/commands/upload_large_folder.py +1 -1
  7. huggingface_hub/constants.py +7 -2
  8. huggingface_hub/file_download.py +1 -2
  9. huggingface_hub/hf_api.py +65 -84
  10. huggingface_hub/hub_mixin.py +12 -9
  11. huggingface_hub/inference/_client.py +706 -450
  12. huggingface_hub/inference/_common.py +32 -64
  13. huggingface_hub/inference/_generated/_async_client.py +722 -470
  14. huggingface_hub/inference/_generated/types/__init__.py +1 -0
  15. huggingface_hub/inference/_generated/types/image_to_image.py +3 -3
  16. huggingface_hub/inference/_generated/types/text_to_audio.py +1 -2
  17. huggingface_hub/inference/_generated/types/text_to_image.py +3 -3
  18. huggingface_hub/inference/_generated/types/text_to_speech.py +3 -6
  19. huggingface_hub/inference/_generated/types/text_to_video.py +47 -0
  20. huggingface_hub/inference/_generated/types/visual_question_answering.py +1 -1
  21. huggingface_hub/inference/_providers/__init__.py +89 -0
  22. huggingface_hub/inference/_providers/fal_ai.py +159 -0
  23. huggingface_hub/inference/_providers/hf_inference.py +202 -0
  24. huggingface_hub/inference/_providers/replicate.py +148 -0
  25. huggingface_hub/inference/_providers/sambanova.py +89 -0
  26. huggingface_hub/inference/_providers/together.py +153 -0
  27. huggingface_hub/py.typed +0 -0
  28. huggingface_hub/repocard.py +1 -1
  29. huggingface_hub/repocard_data.py +2 -1
  30. huggingface_hub/serialization/_base.py +1 -1
  31. huggingface_hub/serialization/_torch.py +1 -1
  32. huggingface_hub/utils/_fixes.py +25 -13
  33. huggingface_hub/utils/_http.py +3 -3
  34. huggingface_hub/utils/logging.py +1 -1
  35. {huggingface_hub-0.27.0rc1.dist-info → huggingface_hub-0.28.0.dist-info}/METADATA +4 -4
  36. {huggingface_hub-0.27.0rc1.dist-info → huggingface_hub-0.28.0.dist-info}/RECORD +40 -32
  37. {huggingface_hub-0.27.0rc1.dist-info → huggingface_hub-0.28.0.dist-info}/LICENSE +0 -0
  38. {huggingface_hub-0.27.0rc1.dist-info → huggingface_hub-0.28.0.dist-info}/WHEEL +0 -0
  39. {huggingface_hub-0.27.0rc1.dist-info → huggingface_hub-0.28.0.dist-info}/entry_points.txt +0 -0
  40. {huggingface_hub-0.27.0rc1.dist-info → huggingface_hub-0.28.0.dist-info}/top_level.txt +0 -0
@@ -2,6 +2,7 @@ import os
2
2
  import re
3
3
  import typing
4
4
  from typing import Literal, Optional, Tuple
5
+ from urllib.parse import urljoin
5
6
 
6
7
 
7
8
  # Possible values for env variables
@@ -63,9 +64,11 @@ _staging_mode = _is_true(os.environ.get("HUGGINGFACE_CO_STAGING"))
63
64
 
64
65
  _HF_DEFAULT_ENDPOINT = "https://huggingface.co"
65
66
  _HF_DEFAULT_STAGING_ENDPOINT = "https://hub-ci.huggingface.co"
66
- ENDPOINT = os.getenv("HF_ENDPOINT") or (_HF_DEFAULT_STAGING_ENDPOINT if _staging_mode else _HF_DEFAULT_ENDPOINT)
67
+ ENDPOINT = os.getenv("HF_ENDPOINT", "").rstrip("/") or (
68
+ _HF_DEFAULT_STAGING_ENDPOINT if _staging_mode else _HF_DEFAULT_ENDPOINT
69
+ )
67
70
 
68
- HUGGINGFACE_CO_URL_TEMPLATE = ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
71
+ HUGGINGFACE_CO_URL_TEMPLATE = urljoin(ENDPOINT, "/{repo_id}/resolve/{revision}/{filename}")
69
72
  HUGGINGFACE_HEADER_X_REPO_COMMIT = "X-Repo-Commit"
70
73
  HUGGINGFACE_HEADER_X_LINKED_ETAG = "X-Linked-Etag"
71
74
  HUGGINGFACE_HEADER_X_LINKED_SIZE = "X-Linked-Size"
@@ -75,6 +78,8 @@ INFERENCE_ENDPOINT = os.environ.get("HF_INFERENCE_ENDPOINT", "https://api-infere
75
78
  # See https://huggingface.co/docs/inference-endpoints/index
76
79
  INFERENCE_ENDPOINTS_ENDPOINT = "https://api.endpoints.huggingface.cloud/v2"
77
80
 
81
+ # Proxy for third-party providers
82
+ INFERENCE_PROXY_TEMPLATE = urljoin(ENDPOINT, "/api/inference-proxy/{provider}")
78
83
 
79
84
  REPO_ID_SEPARATOR = "--"
80
85
  # ^ this substring is not allowed in repo_ids on hf.co
@@ -1581,8 +1581,7 @@ def _chmod_and_move(src: Path, dst: Path) -> None:
1581
1581
  os.chmod(str(src), stat.S_IMODE(cache_dir_mode))
1582
1582
  except OSError as e:
1583
1583
  logger.warning(
1584
- f"Could not set the permissions on the file '{src}'. "
1585
- f"Error: {e}.\nContinuing without setting permissions."
1584
+ f"Could not set the permissions on the file '{src}'. Error: {e}.\nContinuing without setting permissions."
1586
1585
  )
1587
1586
  finally:
1588
1587
  try:
huggingface_hub/hf_api.py CHANGED
@@ -158,6 +158,8 @@ ExpandModelProperty_T = Literal[
158
158
  "transformersInfo",
159
159
  "trendingScore",
160
160
  "widgetData",
161
+ "usedStorage",
162
+ "resourceGroup",
161
163
  ]
162
164
 
163
165
  ExpandDatasetProperty_T = Literal[
@@ -178,6 +180,8 @@ ExpandDatasetProperty_T = Literal[
178
180
  "sha",
179
181
  "trendingScore",
180
182
  "tags",
183
+ "usedStorage",
184
+ "resourceGroup",
181
185
  ]
182
186
 
183
187
  ExpandSpaceProperty_T = Literal[
@@ -197,6 +201,8 @@ ExpandSpaceProperty_T = Literal[
197
201
  "subdomain",
198
202
  "tags",
199
203
  "trendingScore",
204
+ "usedStorage",
205
+ "resourceGroup",
200
206
  ]
201
207
 
202
208
  USERNAME_PLACEHOLDER = "hf_user"
@@ -1782,7 +1788,7 @@ class HfApi:
1782
1788
  expand (`List[ExpandModelProperty_T]`, *optional*):
1783
1789
  List properties to return in the response. When used, only the properties in the list will be returned.
1784
1790
  This parameter cannot be used if `full`, `cardData` or `fetch_config` are passed.
1785
- Possible values are `"author"`, `"baseModels"`, `"cardData"`, `"childrenModelCount"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"gguf"`, `"inference"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"` and `"widgetData"`.
1791
+ Possible values are `"author"`, `"baseModels"`, `"cardData"`, `"childrenModelCount"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"gguf"`, `"inference"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, `"usedStorage"` and `"resourceGroup"`.
1786
1792
  full (`bool`, *optional*):
1787
1793
  Whether to fetch all model data, including the `last_modified`,
1788
1794
  the `sha`, the files and the `tags`. This is set to `True` by
@@ -2002,7 +2008,7 @@ class HfApi:
2002
2008
  expand (`List[ExpandDatasetProperty_T]`, *optional*):
2003
2009
  List properties to return in the response. When used, only the properties in the list will be returned.
2004
2010
  This parameter cannot be used if `full` is passed.
2005
- Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"` and `"trendingScore"`.
2011
+ Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`, `"usedStorage"` and `"resourceGroup"`.
2006
2012
  full (`bool`, *optional*):
2007
2013
  Whether to fetch all dataset data, including the `last_modified`,
2008
2014
  the `card_data` and the files. Can contain useful information such as the
@@ -2180,7 +2186,7 @@ class HfApi:
2180
2186
  expand (`List[ExpandSpaceProperty_T]`, *optional*):
2181
2187
  List properties to return in the response. When used, only the properties in the list will be returned.
2182
2188
  This parameter cannot be used if `full` is passed.
2183
- Possible values are `"author"`, `"cardData"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"createdAt"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"` and `"trendingScore"`.
2189
+ Possible values are `"author"`, `"cardData"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"createdAt"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"` and `"resourceGroup"`.
2184
2190
  full (`bool`, *optional*):
2185
2191
  Whether to fetch all Spaces data, including the `last_modified`, `siblings`
2186
2192
  and `card_data` fields.
@@ -2240,57 +2246,6 @@ class HfApi:
2240
2246
  item["siblings"] = None
2241
2247
  yield SpaceInfo(**item)
2242
2248
 
2243
- @validate_hf_hub_args
2244
- def like(
2245
- self,
2246
- repo_id: str,
2247
- *,
2248
- token: Union[bool, str, None] = None,
2249
- repo_type: Optional[str] = None,
2250
- ) -> None:
2251
- """
2252
- Like a given repo on the Hub (e.g. set as favorite).
2253
-
2254
- See also [`unlike`] and [`list_liked_repos`].
2255
-
2256
- Args:
2257
- repo_id (`str`):
2258
- The repository to like. Example: `"user/my-cool-model"`.
2259
-
2260
- token (Union[bool, str, None], optional):
2261
- A valid user access token (string). Defaults to the locally saved
2262
- token, which is the recommended method for authentication (see
2263
- https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
2264
- To disable authentication, pass `False`.
2265
-
2266
- repo_type (`str`, *optional*):
2267
- Set to `"dataset"` or `"space"` if liking a dataset or space, `None` or
2268
- `"model"` if liking a model. Default is `None`.
2269
-
2270
- Raises:
2271
- [`~utils.RepositoryNotFoundError`]:
2272
- If repository is not found (error 404): wrong repo_id/repo_type, private
2273
- but not authenticated or repo does not exist.
2274
-
2275
- Example:
2276
- ```python
2277
- >>> from huggingface_hub import like, list_liked_repos, unlike
2278
- >>> like("gpt2")
2279
- >>> "gpt2" in list_liked_repos().models
2280
- True
2281
- >>> unlike("gpt2")
2282
- >>> "gpt2" in list_liked_repos().models
2283
- False
2284
- ```
2285
- """
2286
- if repo_type is None:
2287
- repo_type = constants.REPO_TYPE_MODEL
2288
- response = get_session().post(
2289
- url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/like",
2290
- headers=self._build_hf_headers(token=token),
2291
- )
2292
- hf_raise_for_status(response)
2293
-
2294
2249
  @validate_hf_hub_args
2295
2250
  def unlike(
2296
2251
  self,
@@ -2302,7 +2257,9 @@ class HfApi:
2302
2257
  """
2303
2258
  Unlike a given repo on the Hub (e.g. remove from favorite list).
2304
2259
 
2305
- See also [`like`] and [`list_liked_repos`].
2260
+ To prevent spam usage, it is not possible to `like` a repository from a script.
2261
+
2262
+ See also [`list_liked_repos`].
2306
2263
 
2307
2264
  Args:
2308
2265
  repo_id (`str`):
@@ -2325,9 +2282,8 @@ class HfApi:
2325
2282
 
2326
2283
  Example:
2327
2284
  ```python
2328
- >>> from huggingface_hub import like, list_liked_repos, unlike
2329
- >>> like("gpt2")
2330
- >>> "gpt2" in list_liked_repos().models
2285
+ >>> from huggingface_hub import list_liked_repos, unlike
2286
+ >>> "gpt2" in list_liked_repos().models # we assume you have already liked gpt2
2331
2287
  True
2332
2288
  >>> unlike("gpt2")
2333
2289
  >>> "gpt2" in list_liked_repos().models
@@ -2354,7 +2310,7 @@ class HfApi:
2354
2310
  This list is public so token is optional. If `user` is not passed, it defaults to
2355
2311
  the logged in user.
2356
2312
 
2357
- See also [`like`] and [`unlike`].
2313
+ See also [`unlike`].
2358
2314
 
2359
2315
  Args:
2360
2316
  user (`str`, *optional*):
@@ -2428,7 +2384,7 @@ class HfApi:
2428
2384
  """
2429
2385
  List all users who liked a given repo on the hugging Face Hub.
2430
2386
 
2431
- See also [`like`] and [`list_liked_repos`].
2387
+ See also [`list_liked_repos`].
2432
2388
 
2433
2389
  Args:
2434
2390
  repo_id (`str`):
@@ -2491,7 +2447,7 @@ class HfApi:
2491
2447
  expand (`List[ExpandModelProperty_T]`, *optional*):
2492
2448
  List properties to return in the response. When used, only the properties in the list will be returned.
2493
2449
  This parameter cannot be used if `securityStatus` or `files_metadata` are passed.
2494
- Possible values are `"author"`, `"baseModels"`, `"cardData"`, `"childrenModelCount"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"gguf"`, `"inference"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"` and `"widgetData"`.
2450
+ Possible values are `"author"`, `"baseModels"`, `"cardData"`, `"childrenModelCount"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"gguf"`, `"inference"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, `"usedStorage"` and `"resourceGroup"`.
2495
2451
  token (Union[bool, str, None], optional):
2496
2452
  A valid user access token (string). Defaults to the locally saved
2497
2453
  token, which is the recommended method for authentication (see
@@ -2565,7 +2521,7 @@ class HfApi:
2565
2521
  expand (`List[ExpandDatasetProperty_T]`, *optional*):
2566
2522
  List properties to return in the response. When used, only the properties in the list will be returned.
2567
2523
  This parameter cannot be used if `files_metadata` is passed.
2568
- Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"` and `"trendingScore"`.
2524
+ Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`,`"usedStorage"` and `"resourceGroup"`.
2569
2525
  token (Union[bool, str, None], optional):
2570
2526
  A valid user access token (string). Defaults to the locally saved
2571
2527
  token, which is the recommended method for authentication (see
@@ -2615,7 +2571,7 @@ class HfApi:
2615
2571
  revision: Optional[str] = None,
2616
2572
  timeout: Optional[float] = None,
2617
2573
  files_metadata: bool = False,
2618
- expand: Optional[List[ExpandModelProperty_T]] = None,
2574
+ expand: Optional[List[ExpandSpaceProperty_T]] = None,
2619
2575
  token: Union[bool, str, None] = None,
2620
2576
  ) -> SpaceInfo:
2621
2577
  """
@@ -2638,7 +2594,7 @@ class HfApi:
2638
2594
  expand (`List[ExpandSpaceProperty_T]`, *optional*):
2639
2595
  List properties to return in the response. When used, only the properties in the list will be returned.
2640
2596
  This parameter cannot be used if `full` is passed.
2641
- Possible values are `"author"`, `"cardData"`, `"createdAt"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"` and `"trendingScore"`.
2597
+ Possible values are `"author"`, `"cardData"`, `"createdAt"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"` and `"resourceGroup"`.
2642
2598
  token (Union[bool, str, None], optional):
2643
2599
  A valid user access token (string). Defaults to the locally saved
2644
2600
  token, which is the recommended method for authentication (see
@@ -2919,7 +2875,7 @@ class HfApi:
2919
2875
  repo_id (`str`):
2920
2876
  A namespace (user or an organization) and a repo name separated by a `/`.
2921
2877
  revision (`str`, *optional*):
2922
- The revision of the model repository from which to get the information.
2878
+ The revision of the repository from which to get the information.
2923
2879
  repo_type (`str`, *optional*):
2924
2880
  Set to `"dataset"` or `"space"` if uploading to a dataset or space, `None` or `"model"` if uploading to
2925
2881
  a model. Default is `None`.
@@ -3385,7 +3341,7 @@ class HfApi:
3385
3341
  branch = constants.DEFAULT_REVISION
3386
3342
 
3387
3343
  # Prepare request
3388
- url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/super-squash/{branch}"
3344
+ url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/super-squash/{quote(branch, safe='')}"
3389
3345
  headers = self._build_hf_headers(token=token)
3390
3346
  commit_message = commit_message or f"Super-squash branch '{branch}' using huggingface_hub"
3391
3347
 
@@ -3610,7 +3566,7 @@ class HfApi:
3610
3566
  repo_id (`str`, *optional*):
3611
3567
  A namespace (user or an organization) and a repo name separated by a `/`.
3612
3568
  private (`bool`, *optional*, defaults to `False`):
3613
- Whether the model repo should be private.
3569
+ Whether the repository should be private.
3614
3570
  token (Union[bool, str, None], optional):
3615
3571
  A valid user access token (string). Defaults to the locally saved
3616
3572
  token, which is the recommended method for authentication (see
@@ -3672,7 +3628,7 @@ class HfApi:
3672
3628
  * "manual": The repository is gated, and access requests require manual approval.
3673
3629
  * False : The repository is not gated, and anyone can access it.
3674
3630
  private (`bool`, *optional*):
3675
- Whether the model repo should be private.
3631
+ Whether the repository should be private.
3676
3632
  token (`Union[str, bool, None]`, *optional*):
3677
3633
  A valid user access token (string). Defaults to the locally saved token,
3678
3634
  which is the recommended method for authentication (see
@@ -4013,6 +3969,14 @@ class HfApi:
4013
3969
  free_memory=False, # do not remove `CommitOperationAdd.path_or_fileobj` on LFS files for "normal" users
4014
3970
  )
4015
3971
 
3972
+ files_to_copy = _fetch_files_to_copy(
3973
+ copies=copies,
3974
+ repo_type=repo_type,
3975
+ repo_id=repo_id,
3976
+ headers=headers,
3977
+ revision=unquoted_revision,
3978
+ endpoint=self.endpoint,
3979
+ )
4016
3980
  # Remove no-op operations (files that have not changed)
4017
3981
  operations_without_no_op = []
4018
3982
  for operation in operations:
@@ -4024,6 +3988,16 @@ class HfApi:
4024
3988
  # File already exists on the Hub and has not changed: we can skip it.
4025
3989
  logger.debug(f"Skipping upload for '{operation.path_in_repo}' as the file has not changed.")
4026
3990
  continue
3991
+ if (
3992
+ isinstance(operation, CommitOperationCopy)
3993
+ and operation._dest_oid is not None
3994
+ and operation._dest_oid == operation._src_oid
3995
+ ):
3996
+ # Source and destination files are identical - skip
3997
+ logger.debug(
3998
+ f"Skipping copy for '{operation.src_path_in_repo}' -> '{operation.path_in_repo}' as the content of the source file is the same as the destination file."
3999
+ )
4000
+ continue
4027
4001
  operations_without_no_op.append(operation)
4028
4002
  if len(operations) != len(operations_without_no_op):
4029
4003
  logger.info(
@@ -4052,14 +4026,6 @@ class HfApi:
4052
4026
  oid=info.sha, # type: ignore[arg-type]
4053
4027
  )
4054
4028
 
4055
- files_to_copy = _fetch_files_to_copy(
4056
- copies=copies,
4057
- repo_type=repo_type,
4058
- repo_id=repo_id,
4059
- headers=headers,
4060
- revision=unquoted_revision,
4061
- endpoint=self.endpoint,
4062
- )
4063
4029
  commit_payload = _prepare_commit_payload(
4064
4030
  operations=operations,
4065
4031
  files_to_copy=files_to_copy,
@@ -5194,7 +5160,7 @@ class HfApi:
5194
5160
  filename (`str`):
5195
5161
  The name of the file in the repo.
5196
5162
  subfolder (`str`, *optional*):
5197
- An optional value corresponding to a folder inside the model repo.
5163
+ An optional value corresponding to a folder inside the repository.
5198
5164
  repo_type (`str`, *optional*):
5199
5165
  Set to `"dataset"` or `"space"` if downloading from a dataset or space,
5200
5166
  `None` or `"model"` if downloading from a model. Default is `None`.
@@ -5419,8 +5385,6 @@ class HfApi:
5419
5385
  Args:
5420
5386
  repo_id (`str`):
5421
5387
  A user or an organization name and a repo name separated by a `/`.
5422
- filename (`str`):
5423
- The name of the file in the repo.
5424
5388
  repo_type (`str`, *optional*):
5425
5389
  Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a
5426
5390
  model. Default is `None`.
@@ -5608,7 +5572,7 @@ class HfApi:
5608
5572
  if metadata_size <= 100000:
5609
5573
  metadata_as_bytes = response.content[8 : 8 + metadata_size]
5610
5574
  else: # 3.b. Request full metadata
5611
- response = get_session().get(url, headers={**_headers, "range": f"bytes=8-{metadata_size+7}"})
5575
+ response = get_session().get(url, headers={**_headers, "range": f"bytes=8-{metadata_size + 7}"})
5612
5576
  hf_raise_for_status(response)
5613
5577
  metadata_as_bytes = response.content
5614
5578
 
@@ -8571,7 +8535,13 @@ class HfApi:
8571
8535
 
8572
8536
  @validate_hf_hub_args
8573
8537
  def reject_access_request(
8574
- self, repo_id: str, user: str, *, repo_type: Optional[str] = None, token: Union[bool, str, None] = None
8538
+ self,
8539
+ repo_id: str,
8540
+ user: str,
8541
+ *,
8542
+ repo_type: Optional[str] = None,
8543
+ rejection_reason: Optional[str],
8544
+ token: Union[bool, str, None] = None,
8575
8545
  ) -> None:
8576
8546
  """
8577
8547
  Reject an access request from a user for a given gated repo.
@@ -8590,6 +8560,8 @@ class HfApi:
8590
8560
  repo_type (`str`, *optional*):
8591
8561
  The type of the repo to reject access request for. Must be one of `model`, `dataset` or `space`.
8592
8562
  Defaults to `model`.
8563
+ rejection_reason (`str`, *optional*):
8564
+ Optional rejection reason that will be visible to the user (max 200 characters).
8593
8565
  token (Union[bool, str, None], optional):
8594
8566
  A valid user access token (string). Defaults to the locally saved
8595
8567
  token, which is the recommended method for authentication (see
@@ -8609,7 +8581,9 @@ class HfApi:
8609
8581
  [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError):
8610
8582
  HTTP 404 if the user access request is already in the rejected list.
8611
8583
  """
8612
- self._handle_access_request(repo_id, user, "rejected", repo_type=repo_type, token=token)
8584
+ self._handle_access_request(
8585
+ repo_id, user, "rejected", repo_type=repo_type, rejection_reason=rejection_reason, token=token
8586
+ )
8613
8587
 
8614
8588
  @validate_hf_hub_args
8615
8589
  def _handle_access_request(
@@ -8618,6 +8592,7 @@ class HfApi:
8618
8592
  user: str,
8619
8593
  status: Literal["accepted", "rejected", "pending"],
8620
8594
  repo_type: Optional[str] = None,
8595
+ rejection_reason: Optional[str] = None,
8621
8596
  token: Union[bool, str, None] = None,
8622
8597
  ) -> None:
8623
8598
  if repo_type not in constants.REPO_TYPES:
@@ -8625,10 +8600,17 @@ class HfApi:
8625
8600
  if repo_type is None:
8626
8601
  repo_type = constants.REPO_TYPE_MODEL
8627
8602
 
8603
+ payload = {"user": user, "status": status}
8604
+
8605
+ if rejection_reason is not None:
8606
+ if status != "rejected":
8607
+ raise ValueError("`rejection_reason` can only be passed when rejecting an access request.")
8608
+ payload["rejectionReason"] = rejection_reason
8609
+
8628
8610
  response = get_session().post(
8629
8611
  f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/handle",
8630
8612
  headers=self._build_hf_headers(token=token),
8631
- json={"user": user, "status": status},
8613
+ json=payload,
8632
8614
  )
8633
8615
  hf_raise_for_status(response)
8634
8616
 
@@ -9558,7 +9540,6 @@ run_as_future = api.run_as_future
9558
9540
  # Activity API
9559
9541
  list_liked_repos = api.list_liked_repos
9560
9542
  list_repo_likers = api.list_repo_likers
9561
- like = api.like
9562
9543
  unlike = api.unlike
9563
9544
 
9564
9545
  # Community API
@@ -1,9 +1,9 @@
1
1
  import inspect
2
2
  import json
3
3
  import os
4
- from dataclasses import asdict, dataclass, is_dataclass
4
+ from dataclasses import Field, asdict, dataclass, is_dataclass
5
5
  from pathlib import Path
6
- from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, TypeVar, Union
6
+ from typing import Any, Callable, ClassVar, Dict, List, Optional, Protocol, Tuple, Type, TypeVar, Union
7
7
 
8
8
  import packaging.version
9
9
 
@@ -24,9 +24,6 @@ from .utils import (
24
24
  )
25
25
 
26
26
 
27
- if TYPE_CHECKING:
28
- from _typeshed import DataclassInstance
29
-
30
27
  if is_torch_available():
31
28
  import torch # type: ignore
32
29
 
@@ -38,6 +35,12 @@ if is_safetensors_available():
38
35
 
39
36
  logger = logging.get_logger(__name__)
40
37
 
38
+
39
+ # Type alias for dataclass instances, copied from https://github.com/python/typeshed/blob/9f28171658b9ca6c32a7cb93fbb99fc92b17858b/stdlib/_typeshed/__init__.pyi#L349
40
+ class DataclassInstance(Protocol):
41
+ __dataclass_fields__: ClassVar[Dict[str, Field]]
42
+
43
+
41
44
  # Generic variable that is either ModelHubMixin or a subclass thereof
42
45
  T = TypeVar("T", bound="ModelHubMixin")
43
46
  # Generic variable to represent an args type
@@ -175,7 +178,7 @@ class ModelHubMixin:
175
178
  ```
176
179
  """
177
180
 
178
- _hub_mixin_config: Optional[Union[dict, "DataclassInstance"]] = None
181
+ _hub_mixin_config: Optional[Union[dict, DataclassInstance]] = None
179
182
  # ^ optional config attribute automatically set in `from_pretrained`
180
183
  _hub_mixin_info: MixinInfo
181
184
  # ^ information about the library integrating ModelHubMixin (used to generate model card)
@@ -366,7 +369,7 @@ class ModelHubMixin:
366
369
  self,
367
370
  save_directory: Union[str, Path],
368
371
  *,
369
- config: Optional[Union[dict, "DataclassInstance"]] = None,
372
+ config: Optional[Union[dict, DataclassInstance]] = None,
370
373
  repo_id: Optional[str] = None,
371
374
  push_to_hub: bool = False,
372
375
  model_card_kwargs: Optional[Dict[str, Any]] = None,
@@ -618,7 +621,7 @@ class ModelHubMixin:
618
621
  self,
619
622
  repo_id: str,
620
623
  *,
621
- config: Optional[Union[dict, "DataclassInstance"]] = None,
624
+ config: Optional[Union[dict, DataclassInstance]] = None,
622
625
  commit_message: str = "Push model using huggingface_hub.",
623
626
  private: Optional[bool] = None,
624
627
  token: Optional[str] = None,
@@ -825,7 +828,7 @@ class PyTorchModelHubMixin(ModelHubMixin):
825
828
  return model
826
829
 
827
830
 
828
- def _load_dataclass(datacls: Type["DataclassInstance"], data: dict) -> "DataclassInstance":
831
+ def _load_dataclass(datacls: Type[DataclassInstance], data: dict) -> DataclassInstance:
829
832
  """Load a dataclass instance from a dictionary.
830
833
 
831
834
  Fields not expected by the dataclass are ignored.