Buckets:

HuggingFaceDocBuilder's picture
|
download
raw
309 kB

HfApi Client[[hfapi-client]]

아래는 허깅 페이스 Hub의 API를 위한 파이썬 래퍼인 HfApi 클래스에 대한 문서입니다.

HfApi의 모든 메서드는 패키지의 루트에서 직접 접근할 수 있습니다. 두 접근 방식은 아래에서 자세히 설명합니다.

루트 메서드를 사용하는 것이 더 간단하지만 HfApi 클래스를 사용하면 더 유연하게 사용할 수 있습니다. 특히 모든 HTTP 호출에서 재사용할 토큰을 전달할 수 있습니다. 이 방식은 토큰이 머신에 유지되지 않기 때문에 hf auth login 또는 login()를 사용하는 방식과는 다르며, 다른 엔드포인트를 제공하거나 사용자정의 에이전트를 구성할 수도 있습니다.

from huggingface_hub import HfApi, list_models

# 루트 메서드를 사용하세요.
models = list_models()

# 또는 HfApi client를 구성하세요.
hf_api = HfApi(
    endpoint="https://huggingface.co", # 비공개 Hub 엔드포인트를 지정할 수 있습니다.
    token="hf_xxx", # 토큰은 머신에 유지되지 않습니다.
)
models = hf_api.list_models()

HfApi[[huggingface_hub.HfApi]][[huggingface_hub.HfApi]]

huggingface_hub.HfApi[[huggingface_hub.HfApi]]

Source

Client to interact with the Hugging Face Hub via HTTP.

The client is initialized with some high-level settings used in all requests made to the Hub (HF endpoint, authentication, user agents...). Using the HfApi client is preferred but not mandatory as all of its public methods are exposed directly at the root of huggingface_hub.

accept_access_requesthuggingface_hub.HfApi.accept_access_requesthttps://github.com/huggingface/huggingface_hub/blob/vr_4113/src/huggingface_hub/hf_api.py#L10109[{"name": "repo_id", "val": ": str"}, {"name": "user", "val": ": str"}, {"name": "repo_type", "val": ": str | None = None"}, {"name": "token", "val": ": bool | str | None = None"}]- repo_id (str) -- The id of the repo to accept access request for.

  • user (str) -- The username of the user which access request should be accepted.
  • repo_type (str, optional) -- The type of the repo to accept access request for. Must be one of model, dataset or space. Defaults to model.
  • token (bool or str, optional) -- A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.0- HfHubHTTPError -- HTTP 400 if the repo is not gated.
  • HfHubHTTPError -- HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have write or admin role in the organization the repo belongs to or if you passed a read token.
  • HfHubHTTPError -- HTTP 404 if the user does not exist on the Hub.
  • HfHubHTTPError -- HTTP 404 if the user access request cannot be found.
  • HfHubHTTPError -- HTTP 404 if the user access request is already in the accepted list.HfHubHTTPError

Accept an access request from a user for a given gated repo.

Once the request is accepted, the user will be able to download any file of the repo and access the community tab. If the approval mode is automatic, you don't have to accept requests manually. An accepted request can be cancelled or rejected at any time using cancel_access_request() and reject_access_request().

For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

Parameters:

endpoint (str, optional) : Endpoint of the Hub. Defaults to .

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

library_name (str, optional) : The name of the library that is making the HTTP request. Will be added to the user-agent header. Example: "transformers".

library_version (str, optional) : The version of the library that is making the HTTP request. Will be added to the user-agent header. Example: "4.24.0".

user_agent (str, dict, optional) : The user agent info in the form of a dictionary or a single string. It will be completed with information about the installed packages.

headers (dict, optional) : Additional headers to be sent with each request. Example: {"X-My-Header": "value"}. Headers passed here are taking precedence over the default headers.

add_collection_item[[huggingface_hub.HfApi.add_collection_item]]

Source

Add an item to a collection on the Hub.

Returns: Collection

Example:

>>> from huggingface_hub import add_collection_item
>>> collection = add_collection_item(
...     collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
...     item_id="pierre-loic/climate-news-articles",
...     item_type="dataset"
... )
>>> collection.items[-1].item_id
"pierre-loic/climate-news-articles"
# ^item got added to the collection on last position

# Add item with a note
>>> add_collection_item(
...     collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
...     item_id="datasets/climate_fever",
...     item_type="dataset"
...     note="This dataset adopts the FEVER methodology that consists of 1,535 real-world claims regarding climate-change collected on the internet."
... )
(...)

Parameters:

collection_slug (str) : Slug of the collection to update. Example: "TheBloke/recent-models-64f9a55bb3115b4f513ec026".

item_id (str) : Id of the item to add to the collection. Use the repo_id for repos/spaces/datasets, the paper id for papers, the slug of another collection (e.g. "moonshotai/kimi-k2") or a bucket id (e.g. "namespace/bucket-name").

item_type (str) : Type of the item to add. Can be one of "model", "dataset", "space", "paper", "collection" or "bucket".

note (str, optional) : A note to attach to the item in the collection. The maximum size for a note is 500 characters.

exists_ok (bool, optional) : If True, do not raise an error if item already exists.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

add_space_secret[[huggingface_hub.HfApi.add_space_secret]]

Source

Adds or updates a secret in a Space.

Secrets allow to set secret keys or tokens to a Space without hardcoding them. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.

Parameters:

repo_id (str) : ID of the repo to update. Example: "bigcode/in-the-stack".

key (str) : Secret key. Example: "GITHUB_API_KEY"

value (str) : Secret value. Example: "your_github_api_key".

description (str, optional) : Secret description. Example: "Github API key to access the Github API".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

add_space_variable[[huggingface_hub.HfApi.add_space_variable]]

Source

Adds or updates a variable in a Space.

Variables allow to set environment variables to a Space without hardcoding them. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables

Parameters:

repo_id (str) : ID of the repo to update. Example: "bigcode/in-the-stack".

key (str) : Variable key. Example: "MODEL_REPO_ID"

value (str) : Variable value. Example: "the_model_repo_id".

description (str) : Description of the variable. Example: "Model Repo ID of the implemented model".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

auth_check[[huggingface_hub.HfApi.auth_check]]

Source

Check if the provided user token has access to a specific repository on the Hugging Face Hub.

This method verifies whether the user, authenticated via the provided token, has access to the specified repository. If the repository is not found or if the user lacks the required permissions to access it, the method raises an appropriate exception.

Example:

Check if the user has access to a repository:

>>> from huggingface_hub import auth_check
>>> from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError

try:
    auth_check("user/my-cool-model")
except GatedRepoError:
    # Handle gated repository error
    print("You do not have permission to access this gated repository.")
except RepositoryNotFoundError:
    # Handle repository not found error
    print("The repository was not found or you do not have access.")

In this example:

  • If the user has access, the method completes successfully.
  • If the repository is gated or does not exist, appropriate exceptions are raised, allowing the user to handle them accordingly.

Parameters:

repo_id (str) : The repository to check for access. Format should be "user/repo_name". Example: "user/my-cool-model".

repo_type (str, optional) : The type of the repository. Should be one of "model", "dataset", or "space". If not specified, the default is "model".

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

write (bool, optional) : If True, checks whether the user has content write permission on the repository. If False (default), only checks for read access.

batch_bucket_files[[huggingface_hub.HfApi.batch_bucket_files]]

Source

Add, copy, and/or delete files in a bucket.

This is a non-transactional operation. If an error occurs in the process, some files may have been uploaded, copied, or deleted while others haven't.

Example:

>>> from huggingface_hub import batch_bucket_files

# Upload files
>>> batch_bucket_files(
...     "username/my-bucket",
...     add=[
...         ("./model.safetensors", "models/model.safetensors"),
...         (b'{{"key": "value"}}', "config.json"),
...     ],
... )

# Copy xet files from another bucket or repo (server-side, no data transfer)
>>> batch_bucket_files(
...     "username/my-bucket",
...     copy=[
...         ("bucket", "username/source-bucket", "", "models/model.safetensors"),
...         ("model", "username/my-model", "", "models/config.safetensors"),
...     ],
... )

# Delete files
>>> batch_bucket_files("username/my-bucket", delete=["old-model.bin"])

# Upload and delete in one batch
>>> batch_bucket_files(
...     "username/my-bucket",
...     add=[("./new.txt", "new.txt")],
...     delete=["old.txt"],
... )

Parameters:

bucket_id (str) : The ID of the bucket (e.g. "username/my-bucket").

add (list of tuple, optional) : Files to upload. Each element is a (source, destination) tuple where source is a path to a local file (str or Path) or raw bytes content, and destination is the path in the bucket.

copy (list of tuple, optional) : Files to copy by xet hash. Each element is a (source_repo_type, source_repo_id, xet_hash, destination) tuple where: - source_repo_type is the type of the source repository: "model", "dataset", "space", or "bucket". - source_repo_id is the ID of the source repository or bucket (e.g. "username/my-model"). - xet_hash is the xet hash of the file to copy. - destination is the destination path in the bucket. This is a server-side operation — no data is downloaded or re-uploaded.

delete (list of str, optional) : Paths of files to delete from the bucket.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

bucket_info[[huggingface_hub.HfApi.bucket_info]]

Source

Get information about a specific bucket on the Hub.

Example:

>>> from huggingface_hub import bucket_info
>>> info = bucket_info(bucket_id="Wauplin/first-bucket")
>>> info.id
'Wauplin/first-bucket'
>>> info.private
False
>>> info.created_at
datetime.datetime(2026, 2, 6, 17, 37, 57, tzinfo=datetime.timezone.utc)
>>> info.size
551879671
>>> info.total_files
12

Parameters:

bucket_id (str) : The ID of the bucket (e.g. "username/my-bucket").

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

BucketInfo

The bucket information.

cancel_access_request[[huggingface_hub.HfApi.cancel_access_request]]

Source

Cancel an access request from a user for a given gated repo.

A cancelled request will go back to the pending list and the user will lose access to the repo.

For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

Parameters:

repo_id (str) : The id of the repo to cancel access request for.

user (str) : The username of the user which access request should be cancelled.

repo_type (str, optional) : The type of the repo to cancel access request for. Must be one of model, dataset or space. Defaults to model.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

cancel_job[[huggingface_hub.HfApi.cancel_job]]

Source

Cancel a compute Job on Hugging Face infrastructure.

Parameters:

job_id (str) : ID of the Job.

namespace (str, optional) : The namespace where the Job is running. Defaults to the current user's namespace.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

change_discussion_status[[huggingface_hub.HfApi.change_discussion_status]]

Source

Closes or re-opens a Discussion or Pull Request.

Examples:

>>> new_title = "New title, fixing a typo"
>>> HfApi().rename_discussion(
...     repo_id="username/repo_name",
...     discussion_num=34
...     new_title=new_title
... )
# DiscussionStatusChange(id='deadbeef0000000', type='status-change', ...)

Raises the following errors:

- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  if some parameter value is invalid
- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

discussion_num (int) : The number of the Discussion or Pull Request . Must be a strictly positive integer.

new_status (str) : The new status for the discussion, either "open" or "closed".

comment (str, optional) : An optional comment to post with the status change.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[DiscussionStatusChange](/docs/huggingface_hub/pr_4113/ko/package_reference/community#huggingface_hub.DiscussionStatusChange)

the status change event

comment_discussion[[huggingface_hub.HfApi.comment_discussion]]

Source

Creates a new comment on the given Discussion.

Examples:


>>> comment = """
... Hello @otheruser!
...
... # This is a title
...
... **This is bold**, *this is italic* and ~this is strikethrough~
... And [this](http://url) is a link
... """

>>> HfApi().comment_discussion(
...     repo_id="username/repo_name",
...     discussion_num=34
...     comment=comment
... )
# DiscussionComment(id='deadbeef0000000', type='comment', ...)

Raises the following errors:

- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  if some parameter value is invalid
- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

discussion_num (int) : The number of the Discussion or Pull Request . Must be a strictly positive integer.

comment (str) : The content of the comment to create. Comments support markdown formatting.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[DiscussionComment](/docs/huggingface_hub/pr_4113/ko/package_reference/community#huggingface_hub.DiscussionComment)

the newly created comment

copy_files[[huggingface_hub.HfApi.copy_files]]

Source

Copy files between locations on the Hub.

Copy files from a bucket or repository (model, dataset, space) to a bucket. Both individual files and entire folders are supported.

Currently, only bucket destinations are supported. Copying to a repository is not supported.

When copying from a repository, .gitattributes files are automatically excluded since they are git-specific metadata and not relevant in a bucket context.

Example:

>>> from huggingface_hub import copy_files

# Copy a single file between buckets
>>> copy_files("hf://buckets/my-bucket/data.bin", "hf://buckets/other-bucket/data.bin")

# Copy a folder from a bucket to another bucket
>>> copy_files("hf://buckets/my-bucket/models/", "hf://buckets/other-bucket/backup/")

# Copy a file from a model repo to a bucket
>>> copy_files("hf://username/my-model/model.safetensors", "hf://buckets/my-bucket/")

# Copy an entire dataset to a bucket
>>> copy_files("hf://datasets/username/my-dataset/", "hf://buckets/my-bucket/datasets/")

Parameters:

source (str) : Source location as an hf:// handle. Can be a bucket path (e.g. "hf://buckets/my-bucket/path/to/file") or a repo path (e.g. "hf://username/my-model/weights.bin", "hf://datasets/username/my-dataset/data/").

destination (str) : Destination location as an hf:// handle pointing to a bucket (e.g. "hf://buckets/my-bucket/target/path").

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

create_branch[[huggingface_hub.HfApi.create_branch]]

Source

Create a new branch for a repo on the Hub, starting from the specified revision (defaults to main). To find a revision suiting your needs, you can use list_repo_refs() or list_repo_commits().

Parameters:

repo_id (str) : The repository in which the branch will be created. Example: "user/my-cool-model".

branch (str) : The name of the branch to create.

revision (str, optional) : The git revision to create the branch from. It can be a branch name or the OID/SHA of a commit, as a hexadecimal string. Defaults to the head of the "main" branch.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

repo_type (str, optional) : Set to "dataset" or "space" if creating a branch on a dataset or space, None or "model" if tagging a model. Default is None.

exist_ok (bool, optional, defaults to False) : If True, do not raise an error if branch already exists.

create_bucket[[huggingface_hub.HfApi.create_bucket]]

Source

Create a bucket on the Hub.

Example:

>>> from huggingface_hub import create_bucket

>>> url = create_bucket(bucket_id="my-bucket")
>>> url.bucket_id
'user/my-bucket'
>>> url.url
'https://huggingface.co/buckets/user/my-bucket'
>>> url.handle
'hf://buckets/user/my-bucket'

>>> create_bucket(bucket_id="my-bucket", private=True, exist_ok=True)
BucketUrl(...)

Parameters:

bucket_id (str) : A namespace (user or an organization) and a bucket name separated by a /. If no namespace is provided, the bucket will be created in the current user's namespace.

private (bool, optional) : Whether to make the bucket private. If None (default), the bucket will be public unless the organization's default is private.

resource_group_id (str, optional) : Resource group in which to create the bucket. Resource groups are only available for Enterprise Hub organizations and allow to define which members of the organization can access the resource. The ID of a resource group can be found in the URL of the resource's page on the Hub (e.g. "66670e5163145ca562cb1988"). To learn more about resource groups, see https://huggingface.co/docs/hub/en/security-resource-groups.

exist_ok (bool, optional, defaults to False) : If True, do not raise an error if the bucket already exists.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

BucketUrl

URL to the newly created bucket containing attributes like endpoint, namespace, and bucket_id.

create_collection[[huggingface_hub.HfApi.create_collection]]

Source

Create a new Collection on the Hub.

Returns: Collection

Example:

>>> from huggingface_hub import create_collection
>>> collection = create_collection(
...     title="ICCV 2023",
...     description="Portfolio of models, papers and demos I presented at ICCV 2023",
... )
>>> collection.slug
"username/iccv-2023-64f9a55bb3115b4f513ec026"

Parameters:

title (str) : Title of the collection to create. Example: "Recent models".

namespace (str, optional) : Namespace of the collection to create (username or org). Will default to the owner name.

description (str, optional) : Description of the collection to create.

private (bool, optional) : Whether the collection should be private or not. Defaults to False (i.e. public collection).

exists_ok (bool, optional) : If True, do not raise an error if collection already exists.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

create_commit[[huggingface_hub.HfApi.create_commit]]

Source

Creates a commit in the given repo, deleting & uploading files as needed.

The input list of CommitOperation will be mutated during the commit process. Do not reuse the same objects for multiple commits.

create_commit assumes that the repo already exists on the Hub. If you get a Client error 404, please make sure you are authenticated, that your token has the required permissions, and that repo_id and repo_type are set correctly. If repo does not exist, create it first using create_repo().

create_commit is limited to 25k LFS files and a 1GB payload for regular files.

Parameters:

repo_id (str) : The repository in which the commit will be created, for example: "username/custom_transformers"

operations (Iterable of CommitOperation()) : An iterable of operations to include in the commit, either: - CommitOperationAdd to upload a file - CommitOperationDelete to delete a file - CommitOperationCopy to copy a file Operation objects will be mutated to include information relative to the upload. Do not reuse the same objects for multiple commits.

commit_message (str) : The summary (first line) of the commit that will be created.

commit_description (str, optional) : The description of the commit that will be created

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

revision (str, optional) : The git revision to commit from. Defaults to the head of the "main" branch.

create_pr (boolean, optional) : Whether or not to create a Pull Request with that commit. Defaults to False. If revision is not set, PR is opened against the "main" branch. If revision is set and is a branch, PR is opened against this branch. If revision is set and is not a branch name (example: a commit oid), an RevisionNotFoundError is returned by the server.

num_threads (int, optional) : Number of concurrent threads for uploading files. Defaults to 5. Setting it to 2 means at most 2 files will be uploaded concurrently.

parent_commit (str, optional) : The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. If specified and create_pr is False, the commit will fail if revision does not point to parent_commit. If specified and create_pr is True, the pull request will be created from parent_commit. Specifying parent_commit ensures the repo has not changed before committing the changes, and can be especially useful if the repo is updated / committed to concurrently.

run_as_future (bool, optional) : Whether or not to run this method in the background. Background jobs are run sequentially without blocking the main thread. Passing run_as_future=True will return a Future object. Defaults to False.

Returns:

[CommitInfo](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.CommitInfo) or Future``

Instance of CommitInfo containing information about the newly created commit (commit hash, commit url, pr url, commit message,...). If run_as_future=True is passed, returns a Future object which will contain the result when executed.

create_discussion[[huggingface_hub.HfApi.create_discussion]]

Source

Creates a Discussion or Pull Request.

Pull Requests created programmatically will be in "draft" status.

Creating a Pull Request with changes can also be done at once with HfApi.create_commit().

Returns: DiscussionWithDetails

Raises the following errors:

- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  if some parameter value is invalid
- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

title (str) : The title of the discussion. It can be up to 200 characters long, and must be at least 3 characters long. Leading and trailing whitespaces will be stripped.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

description (str, optional) : An optional description for the Pull Request. Defaults to "Discussion opened with the huggingface_hub Python library"

pull_request (bool, optional) : Whether to create a Pull Request or discussion. If True, creates a Pull Request. If False, creates a discussion. Defaults to False.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

create_inference_endpoint[[huggingface_hub.HfApi.create_inference_endpoint]]

Source

Create a new Inference Endpoint.

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.create_inference_endpoint(
...     "my-endpoint-name",
...     repository="gpt2",
...     framework="pytorch",
...     task="text-generation",
...     accelerator="cpu",
...     vendor="aws",
...     region="us-east-1",
...     type="protected",
...     instance_size="x2",
...     instance_type="intel-icl",
... )
>>> endpoint
InferenceEndpoint(name='my-endpoint-name', status="pending",...)

# Run inference on the endpoint
>>> endpoint.client.text_generation(...)
"..."
# Start an Inference Endpoint running Zephyr-7b-beta on TGI
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.create_inference_endpoint(
...     "aws-zephyr-7b-beta-0486",
...     repository="HuggingFaceH4/zephyr-7b-beta",
...     framework="pytorch",
...     task="text-generation",
...     accelerator="gpu",
...     vendor="aws",
...     region="us-east-1",
...     type="protected",
...     instance_size="x1",
...     instance_type="nvidia-a10g",
...     env={
...           "MAX_BATCH_PREFILL_TOKENS": "2048",
...           "MAX_INPUT_LENGTH": "1024",
...           "MAX_TOTAL_TOKENS": "1512",
...           "MODEL_ID": "/repository"
...         },
...     custom_image={
...         "health_route": "/health",
...         "url": "ghcr.io/huggingface/text-generation-inference:1.1.0",
...     },
...    secrets={"MY_SECRET_KEY": "secret_value"},
...    tags=["dev", "text-generation"],
... )
# Start an Inference Endpoint running ProsusAI/finbert while scaling to zero in 15 minutes
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.create_inference_endpoint(
...     "finbert-classifier",
...     repository="ProsusAI/finbert",
...     framework="pytorch",
...     task="text-classification",
...     min_replica=0,
...     scale_to_zero_timeout=15,
...     accelerator="cpu",
...     vendor="aws",
...     region="us-east-1",
...     type="protected",
...     instance_size="x2",
...     instance_type="intel-icl",
... )
>>> endpoint.wait(timeout=300)
# Run inference on the endpoint
>>> endpoint.client.text_generation(...)
TextClassificationOutputElement(label='positive', score=0.8983615040779114)

Parameters:

name (str) : The unique name for the new Inference Endpoint.

repository (str) : The name of the model repository associated with the Inference Endpoint (e.g. "gpt2").

framework (str) : The machine learning framework used for the model (e.g. "custom").

accelerator (str) : The hardware accelerator to be used for inference (e.g. "cpu").

instance_size (str) : The size or type of the instance to be used for hosting the model (e.g. "x4").

instance_type (str) : The cloud instance type where the Inference Endpoint will be deployed (e.g. "intel-icl").

region (str) : The cloud region in which the Inference Endpoint will be created (e.g. "us-east-1").

vendor (str) : The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. "aws").

account_id (str, optional) : The account ID used to link a VPC to a private Inference Endpoint (if applicable).

min_replica (int, optional) : The minimum number of replicas (instances) to keep running for the Inference Endpoint. To enable scaling to zero, set this value to 0 and adjust scale_to_zero_timeout accordingly. Defaults to 1.

max_replica (int, optional) : The maximum number of replicas (instances) to scale to for the Inference Endpoint. Defaults to 1.

scaling_metric (str or InferenceEndpointScalingMetric , optional) : The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided. Defaults to None (meaning: let the HF Endpoints service specify the metric).

scaling_threshold (float, optional) : The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided. Defaults to None (meaning: let the HF Endpoints service specify the threshold).

scale_to_zero_timeout (int, optional) : The duration in minutes before an inactive endpoint is scaled to zero, or no scaling to zero if set to None and min_replica is not 0. Defaults to None.

revision (str, optional) : The specific model revision to deploy on the Inference Endpoint (e.g. "6c0e6080953db56375760c0471a8c5f2929baf11").

task (str, optional) : The task on which to deploy the model (e.g. "text-classification").

custom_image (dict, optional) : A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an Inference Endpoint running on the text-generation-inference (TGI) framework (see examples).

env (dict[str, str], optional) : Non-secret environment variables to inject in the container environment.

secrets (dict[str, str], optional) : Secret values to inject in the container environment.

type ([InferenceEndpointType], optional) : The type of the Inference Endpoint, which can be "protected" (default), "public" or "private".

domain (str, optional) : The custom domain for the Inference Endpoint deployment, if setup the inference endpoint will be available at this domain (e.g. "my-new-domain.cool-website.woof").

path (str, optional) : The custom path to the deployed model, should start with a / (e.g. "/models/google-bert/bert-base-uncased").

cache_http_responses (bool, optional) : Whether to cache HTTP responses from the Inference Endpoint. Defaults to False.

tags (list[str], optional) : A list of tags to associate with the Inference Endpoint.

namespace (str, optional) : The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[InferenceEndpoint](/docs/huggingface_hub/pr_4113/ko/package_reference/inference_endpoints#huggingface_hub.InferenceEndpoint)

information about the updated Inference Endpoint.

create_inference_endpoint_from_catalog[[huggingface_hub.HfApi.create_inference_endpoint_from_catalog]]

Source

Create a new Inference Endpoint from a model in the Hugging Face Inference Catalog.

The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list of available models in the catalog.

create_inference_endpoint_from_catalog is experimental. Its API is subject to change in the future. Please provide feedback if you have any suggestions or requests.

Parameters:

repo_id (str) : The ID of the model in the catalog to deploy as an Inference Endpoint.

name (str, optional) : The unique name for the new Inference Endpoint. If not provided, a random name will be generated.

accelerator (str, optional) : The hardware accelerator to be used for inference. Possible values include "cpu", "gpu", and "neuron". If not provided, the server will use a default appropriate for the model.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).

namespace (str, optional) : The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace.

Returns:

[InferenceEndpoint](/docs/huggingface_hub/pr_4113/ko/package_reference/inference_endpoints#huggingface_hub.InferenceEndpoint)

information about the new Inference Endpoint.

create_pull_request[[huggingface_hub.HfApi.create_pull_request]]

Source

Creates a Pull Request . Pull Requests created programmatically will be in "draft" status.

Creating a Pull Request with changes can also be done at once with HfApi.create_commit();

This is a wrapper around HfApi.create_discussion().

Returns: DiscussionWithDetails

Raises the following errors:

- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  if some parameter value is invalid
- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

title (str) : The title of the discussion. It can be up to 200 characters long, and must be at least 3 characters long. Leading and trailing whitespaces will be stripped.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

description (str, optional) : An optional description for the Pull Request. Defaults to "Discussion opened with the huggingface_hub Python library"

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

create_repo[[huggingface_hub.HfApi.create_repo]]

Source

Create an empty repo on the HuggingFace Hub.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

private (bool, optional) : Whether to make the repo private. If None (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. Cannot be passed together with visibility.

visibility (Literal["public", "private", "protected"], optional) : Visibility of the repo. Can be "public" or "private", or "protected" for Spaces. If None (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

exist_ok (bool, optional, defaults to False) : If True, do not raise an error if repo already exists.

resource_group_id (str, optional) : Resource group in which to create the repo. Resource groups is only available for Enterprise Hub organizations and allow to define which members of the organization can access the resource. The ID of a resource group can be found in the URL of the resource's page on the Hub (e.g. "66670e5163145ca562cb1988"). To learn more about resource groups, see https://huggingface.co/docs/hub/en/security-resource-groups.

space_sdk (str, optional) : Choice of SDK to use if repo_type is "space". Can be "streamlit", "gradio", "docker", or "static".

space_hardware (SpaceHardware or str, optional) : Choice of Hardware if repo_type is "space". See SpaceHardware for a complete list.

space_storage (SpaceStorage or str, optional) : Choice of persistent storage tier. Example: "small". See SpaceStorage for a complete list.

space_sleep_time (int, optional) : Number of seconds of inactivity to wait before a Space is put to sleep. Set to -1 if you don't want your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure the sleep time (value is fixed to 48 hours of inactivity). See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.

space_secrets (list[dict[str, str]], optional) : A list of secret keys to set in your Space. Each item is in the form {"key": ..., "value": ..., "description": ...} where description is optional. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.

space_variables (list[dict[str, str]], optional) : A list of public environment variables to set in your Space. Each item is in the form {"key": ..., "value": ..., "description": ...} where description is optional. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.

space_volumes (list[Volume], optional) : A list of Volume objects to mount in the Space at creation time. Each volume has a type ("bucket", "model", "dataset", or "space"), a source (repo or bucket ID), a mount_path (path inside the container), and optional revision, read_only, and path fields. Only applicable if repo_type is "space".

Returns:

[RepoUrl](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.RepoUrl)

URL to the newly created repo. Value is a subclass of str containing attributes like endpoint, repo_type and repo_id.

create_scheduled_job[[huggingface_hub.HfApi.create_scheduled_job]]

Source

Create scheduled compute Jobs on Hugging Face infrastructure.

Example:

Create your first scheduled Job:

>>> from huggingface_hub import create_scheduled_job
>>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly")

Use a CRON schedule expression:

>>> from huggingface_hub import create_scheduled_job
>>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('this runs every 5min')"], schedule="*/5 * * * *")

Create a scheduled GPU Job:

>>> from huggingface_hub import create_scheduled_job
>>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"
>>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"]
>>> create_scheduled_job(image, command, flavor="a10g-small", schedule="@hourly")

Parameters:

image (str) : The Docker image to use. Examples: "ubuntu", "python:3.12", "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel". Example with an image from a Space: "hf.co/spaces/lhoestq/duckdb".

command (list[str]) : The command to run. Example: ["echo", "hello"].

schedule (str) : One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).

suspend (bool, optional) : If True, the scheduled Job is suspended (paused). Defaults to False.

concurrency (bool, optional) : If True, multiple instances of this Job can run concurrently. Defaults to False.

env (dict[str, Any], optional) : Defines the environment variables for the Job.

secrets (dict[str, Any], optional) : Defines the secret environment variables for the Job.

flavor (str, optional) : Flavor for the hardware, as in Hugging Face Spaces. See SpaceHardware for possible values. Defaults to "cpu-basic".

timeout (Union[int, float, str], optional) : Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days). Example: 300 or "5m" for 5 minutes.

labels (dict[str, str], optional) : Labels to attach to the job (key-value pairs).

volumes (list[Volume], optional) : Hugging Face Buckets or Repos to mount as volumes in the job container. Each volume is a Volume with type ("bucket", "model", "dataset", or "space"), source (e.g. "username/my-bucket"), and mount_path (e.g. "/data").

namespace (str, optional) : The namespace where the Job will be created. Defaults to the current user's namespace.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

create_scheduled_uv_job[[huggingface_hub.HfApi.create_scheduled_uv_job]]

Source

Run a UV script Job on Hugging Face infrastructure.

Example:

Schedule a script from a URL:

>>> from huggingface_hub import create_scheduled_uv_job
>>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
>>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
>>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")

Schedule a local script:

>>> from huggingface_hub import create_scheduled_uv_job
>>> script = "my_sft.py"
>>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
>>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")

Schedule a command:

>>> from huggingface_hub import create_scheduled_uv_job
>>> script = "lighteval"
>>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
>>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small", schedule="@weekly")

Parameters:

script (str) : Path or URL of the UV script, or a command.

script_args (list[str], optional) : Arguments to pass to the script, or a command.

schedule (str) : One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).

suspend (bool, optional) : If True, the scheduled Job is suspended (paused). Defaults to False.

concurrency (bool, optional) : If True, multiple instances of this Job can run concurrently. Defaults to False.

dependencies (list[str], optional) : Dependencies to use to run the UV script.

python (str, optional) : Use a specific Python version. Default is 3.12.

image (str, optional, defaults to "ghcr.io/astral-sh/uv --python3.12-bookworm"): Use a custom Docker image with uv installed.

env (dict[str, Any], optional) : Defines the environment variables for the Job.

secrets (dict[str, Any], optional) : Defines the secret environment variables for the Job.

flavor (str, optional) : Flavor for the hardware, as in Hugging Face Spaces. See SpaceHardware for possible values. Defaults to "cpu-basic".

timeout (Union[int, float, str], optional) : Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days). Example: 300 or "5m" for 5 minutes.

labels (dict[str, str], optional) : Labels to attach to the job (key-value pairs).

volumes (list[Volume], optional) : Hugging Face Buckets or Repos to mount as volumes in the job container. Each volume is a Volume with type ("bucket", "model", "dataset", or "space"), source (e.g. "username/my-bucket"), and mount_path (e.g. "/data").

namespace (str, optional) : The namespace where the Job will be created. Defaults to the current user's namespace.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

create_tag[[huggingface_hub.HfApi.create_tag]]

Source

Tag a given commit of a repo on the Hub.

Parameters:

repo_id (str) : The repository in which a commit will be tagged. Example: "user/my-cool-model".

tag (str) : The name of the tag to create.

tag_message (str, optional) : The description of the tag to create.

revision (str, optional) : The git revision to tag. It can be a branch name or the OID/SHA of a commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. Defaults to the head of the "main" branch.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

repo_type (str, optional) : Set to "dataset" or "space" if tagging a dataset or space, None or "model" if tagging a model. Default is None.

exist_ok (bool, optional, defaults to False) : If True, do not raise an error if tag already exists.

create_webhook[[huggingface_hub.HfApi.create_webhook]]

Source

Create a new webhook.

The webhook can either send a payload to a URL, or trigger a Job to run on Hugging Face infrastructure. This function should be called with one of url or job_id, but not both.

Example:

Create a webhook that sends a payload to a URL

>>> from huggingface_hub import create_webhook
>>> payload = create_webhook(
...     watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
...     url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
...     domains=["repo", "discussion"],
...     secret="my-secret",
... )
>>> print(payload)
WebhookInfo(
    id="654bbbc16f2ec14d77f109cc",
    url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
    job=None,
    watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
    domains=["repo", "discussion"],
    secret="my-secret",
    disabled=False,
)

Run a Job and then create a webhook that triggers this Job

>>> from huggingface_hub import create_webhook, run_job
>>> job = run_job(
...     image="ubuntu",
...     command=["bash", "-c", r"echo An event occurred in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD"],
... )
>>> payload = create_webhook(
...     watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
...     job_id=job.id,
...     domains=["repo", "discussion"],
...     secret="my-secret",
... )
>>> print(payload)
WebhookInfo(
    id="654bbbc16f2ec14d77f109cc",
    url=None,
    job=JobSpec(
        docker_image='ubuntu',
        space_id=None,
        command=['bash', '-c', 'echo An event occurred in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD'],
        arguments=[],
        environment={},
        secrets=[],
        flavor='cpu-basic',
        timeout=None,
        tags=None,
        arch=None
    ),
    watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
    domains=["repo", "discussion"],
    secret="my-secret",
    disabled=False,
)

Parameters:

url (str) : URL to send the payload to.

job_id (str) : ID of the source Job to trigger with the webhook payload in the environment variable WEBHOOK_PAYLOAD. Additional environment variables are available for convenience: WEBHOOK_REPO_ID, WEBHOOK_REPO_TYPE and WEBHOOK_SECRET.

watched (list[WebhookWatchedItem]) : List of WebhookWatchedItem to be watched by the webhook. It can be users, orgs, models, datasets or spaces. Watched items can also be provided as plain dictionaries.

domains (list[Literal["repo", "discussion"]], optional) : List of domains to watch. It can be "repo", "discussion" or both.

secret (str, optional) : A secret to sign the payload with.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

WebhookInfo

Info about the newly created webhook.

dataset_info[[huggingface_hub.HfApi.dataset_info]]

Source

Get info on one specific dataset on huggingface.co.

Dataset can be private if you pass an acceptable token.

Raises the following errors:

- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.
- [RevisionNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RevisionNotFoundError)
  If the revision to download from cannot be found.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

revision (str, optional) : The revision of the dataset repository from which to get the information.

timeout (float, optional) : Whether to set a timeout for the request to the Hub.

files_metadata (bool, optional) : Whether or not to retrieve metadata for files in the repository (size, LFS metadata, etc). Defaults to False.

expand (list[ExpandDatasetProperty_T], optional) : List properties to return in the response. When used, only the properties in the list will be returned. This parameter cannot be used if files_metadata is passed. Possible values are "author", "cardData", "citation", "createdAt", "disabled", "description", "downloads", "downloadsAllTime", "gated", "lastModified", "likes", "paperswithcode_id", "private", "siblings", "sha", "tags", "trendingScore","usedStorage", and "resourceGroup".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[hf_api.DatasetInfo](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.DatasetInfo)

The dataset repository information.

delete_branch[[huggingface_hub.HfApi.delete_branch]]

Source

Delete a branch from a repo on the Hub.

Parameters:

repo_id (str) : The repository in which a branch will be deleted. Example: "user/my-cool-model".

branch (str) : The name of the branch to delete.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

repo_type (str, optional) : Set to "dataset" or "space" if creating a branch on a dataset or space, None or "model" if tagging a model. Default is None.

delete_bucket[[huggingface_hub.HfApi.delete_bucket]]

Source

Delete a bucket from the Hub.

Example:

>>> from huggingface_hub import delete_bucket
>>> delete_bucket(bucket_id="Wauplin/first-bucket")
>>> delete_bucket(bucket_id="Wauplin/first-bucket", missing_ok=True)

Parameters:

bucket_id (str) : The ID of the bucket (e.g. "username/my-bucket").

missing_ok (bool, optional, defaults to False) : If True, do not raise an error if the bucket does not exist.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

delete_collection[[huggingface_hub.HfApi.delete_collection]]

Source

Delete a collection on the Hub.

Example:

>>> from huggingface_hub import delete_collection
>>> collection = delete_collection("username/useless-collection-64f9a55bb3115b4f513ec026", missing_ok=True)

This is a non-revertible action. A deleted collection cannot be restored.

Parameters:

collection_slug (str) : Slug of the collection to delete. Example: "TheBloke/recent-models-64f9a55bb3115b4f513ec026".

missing_ok (bool, optional) : If True, do not raise an error if collection doesn't exists.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

delete_collection_item[[huggingface_hub.HfApi.delete_collection_item]]

Source

Delete an item from a collection.

Example:

>>> from huggingface_hub import get_collection, delete_collection_item

# Get collection first
>>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")

# Delete item based on its ID
>>> delete_collection_item(
...     collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
...     item_object_id=collection.items[-1].item_object_id,
... )

Parameters:

collection_slug (str) : Slug of the collection to update. Example: "TheBloke/recent-models-64f9a55bb3115b4f513ec026".

item_object_id (str) : ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id). It must be retrieved from a CollectionItem object. Example: collection.items[0].item_object_id.

missing_ok (bool, optional) : If True, do not raise an error if item doesn't exists.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

delete_file[[huggingface_hub.HfApi.delete_file]]

Source

Deletes a file in the given repo.

Raises the following errors:

- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  if some parameter value is invalid
- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.
- [RevisionNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RevisionNotFoundError)
  If the revision to download from cannot be found.
- [EntryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.EntryNotFoundError)
  If the file to download cannot be found.

Parameters:

path_in_repo (str) : Relative filepath in the repo, for example: "checkpoints/1fec34a/weights.bin"

repo_id (str) : The repository from which the file will be deleted, for example: "username/custom_transformers"

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

repo_type (str, optional) : Set to "dataset" or "space" if the file is in a dataset or space, None or "model" if in a model. Default is None.

revision (str, optional) : The git revision to commit from. Defaults to the head of the "main" branch.

commit_message (str, optional) : The summary / title / first line of the generated commit. Defaults to f"Delete {path_in_repo} with huggingface_hub".

commit_description (str optional) : The description of the generated commit

create_pr (boolean, optional) : Whether or not to create a Pull Request with that commit. Defaults to False. If revision is not set, PR is opened against the "main" branch. If revision is set and is a branch, PR is opened against this branch. If revision is set and is not a branch name (example: a commit oid), an RevisionNotFoundError is returned by the server.

parent_commit (str, optional) : The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. If specified and create_pr is False, the commit will fail if revision does not point to parent_commit. If specified and create_pr is True, the pull request will be created from parent_commit. Specifying parent_commit ensures the repo has not changed before committing the changes, and can be especially useful if the repo is updated / committed to concurrently.

delete_files[[huggingface_hub.HfApi.delete_files]]

Source

Delete files from a repository on the Hub.

If a folder path is provided, the entire folder is deleted as well as all files it contained.

Parameters:

repo_id (str) : The repository from which the folder will be deleted, for example: "username/custom_transformers"

delete_patterns (list[str]) : List of files or folders to delete. Each string can either be a file path, a folder path, or a wildcard pattern. Patterns are Standard Wildcards (globbing patterns) as documented here. The pattern matching is based on fnmatch. Note that fnmatch matches * across path boundaries, unlike traditional Unix shell globbing. E.g. ["file.txt", "folder/", "data/*.parquet"]

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False. to the stored token.

repo_type (str, optional) : Type of the repo to delete files from. Can be "model", "dataset" or "space". Defaults to "model".

revision (str, optional) : The git revision to commit from. Defaults to the head of the "main" branch.

commit_message (str, optional) : The summary (first line) of the generated commit. Defaults to f"Delete files using huggingface_hub".

commit_description (str optional) : The description of the generated commit.

create_pr (boolean, optional) : Whether or not to create a Pull Request with that commit. Defaults to False. If revision is not set, PR is opened against the "main" branch. If revision is set and is a branch, PR is opened against this branch. If revision is set and is not a branch name (example: a commit oid), an RevisionNotFoundError is returned by the server.

parent_commit (str, optional) : The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. If specified and create_pr is False, the commit will fail if revision does not point to parent_commit. If specified and create_pr is True, the pull request will be created from parent_commit. Specifying parent_commit ensures the repo has not changed before committing the changes, and can be especially useful if the repo is updated / committed to concurrently.

delete_folder[[huggingface_hub.HfApi.delete_folder]]

Source

Deletes a folder in the given repo.

Simple wrapper around create_commit() method.

Parameters:

path_in_repo (str) : Relative folder path in the repo, for example: "checkpoints/1fec34a".

repo_id (str) : The repository from which the folder will be deleted, for example: "username/custom_transformers"

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False. to the stored token.

repo_type (str, optional) : Set to "dataset" or "space" if the folder is in a dataset or space, None or "model" if in a model. Default is None.

revision (str, optional) : The git revision to commit from. Defaults to the head of the "main" branch.

commit_message (str, optional) : The summary / title / first line of the generated commit. Defaults to f"Delete folder {path_in_repo} with huggingface_hub".

commit_description (str optional) : The description of the generated commit.

create_pr (boolean, optional) : Whether or not to create a Pull Request with that commit. Defaults to False. If revision is not set, PR is opened against the "main" branch. If revision is set and is a branch, PR is opened against this branch. If revision is set and is not a branch name (example: a commit oid), an RevisionNotFoundError is returned by the server.

parent_commit (str, optional) : The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. If specified and create_pr is False, the commit will fail if revision does not point to parent_commit. If specified and create_pr is True, the pull request will be created from parent_commit. Specifying parent_commit ensures the repo has not changed before committing the changes, and can be especially useful if the repo is updated / committed to concurrently.

delete_inference_endpoint[[huggingface_hub.HfApi.delete_inference_endpoint]]

Source

Delete an Inference Endpoint.

This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable to pause it with pause_inference_endpoint() or scale it to zero with scale_to_zero_inference_endpoint().

For convenience, you can also delete an Inference Endpoint using InferenceEndpoint.delete().

Parameters:

name (str) : The name of the Inference Endpoint to delete.

namespace (str, optional) : The namespace in which the Inference Endpoint is located. Defaults to the current user.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

delete_repo[[huggingface_hub.HfApi.delete_repo]]

Source

Delete a repo from the HuggingFace Hub. CAUTION: this is irreversible.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model.

missing_ok (bool, optional, defaults to False) : If True, do not raise an error if repo does not exist.

delete_scheduled_job[[huggingface_hub.HfApi.delete_scheduled_job]]

Source

Delete a scheduled compute Job on Hugging Face infrastructure.

Parameters:

scheduled_job_id (str) : ID of the scheduled Job.

namespace (str, optional) : The namespace where the scheduled Job is. Defaults to the current user's namespace.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

delete_space_secret[[huggingface_hub.HfApi.delete_space_secret]]

Source

Deletes a secret from a Space.

Secrets allow to set secret keys or tokens to a Space without hardcoding them. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.

Parameters:

repo_id (str) : ID of the repo to update. Example: "bigcode/in-the-stack".

key (str) : Secret key. Example: "GITHUB_API_KEY".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

delete_space_storage[[huggingface_hub.HfApi.delete_space_storage]]

Source

Delete persistent storage for a Space.

delete_space_storage is deprecated and will be removed in version 2.0. Use delete_space_volumes() instead.

Parameters:

repo_id (str) : ID of the Space to update. Example: "open-llm-leaderboard/open_llm_leaderboard".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[SpaceRuntime](/docs/huggingface_hub/pr_4113/ko/package_reference/space_runtime#huggingface_hub.SpaceRuntime)

Runtime information about a Space including Space stage and hardware.

delete_space_variable[[huggingface_hub.HfApi.delete_space_variable]]

Source

Deletes a variable from a Space.

Variables allow to set environment variables to a Space without hardcoding them. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables

Parameters:

repo_id (str) : ID of the repo to update. Example: "bigcode/in-the-stack".

key (str) : Variable key. Example: "MODEL_REPO_ID"

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

delete_space_volumes[[huggingface_hub.HfApi.delete_space_volumes]]

Source

Remove all volumes from a Space.

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.delete_space_volumes("username/my-space")

Parameters:

repo_id (str) : ID of the Space to update. Example: "username/my-space".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

delete_tag[[huggingface_hub.HfApi.delete_tag]]

Source

Delete a tag from a repo on the Hub.

Parameters:

repo_id (str) : The repository in which a tag will be deleted. Example: "user/my-cool-model".

tag (str) : The name of the tag to delete.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

repo_type (str, optional) : Set to "dataset" or "space" if tagging a dataset or space, None or "model" if tagging a model. Default is None.

delete_webhook[[huggingface_hub.HfApi.delete_webhook]]

Source

Delete a webhook.

Example:

>>> from huggingface_hub import delete_webhook
>>> delete_webhook("654bbbc16f2ec14d77f109cc")

Parameters:

webhook_id (str) : The unique identifier of the webhook to delete.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

None

disable_space_dev_mode[[huggingface_hub.HfApi.disable_space_dev_mode]]

Source

Disable dev mode on a Space.

Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you to restart your application without stopping the Space container itself. This feature is available as part of a PRO or Team & Enterprise plan. See https://huggingface.co/docs/hub/spaces-dev-mode for more details.

Parameters:

repo_id (str) : ID of the Space to disable dev mode. Example: "Salesforce/BLIP2".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[SpaceRuntime](/docs/huggingface_hub/pr_4113/ko/package_reference/space_runtime#huggingface_hub.SpaceRuntime)

Runtime information about your Space.

disable_webhook[[huggingface_hub.HfApi.disable_webhook]]

Source

Disable a webhook (makes it "disabled").

Example:

>>> from huggingface_hub import disable_webhook
>>> disabled_webhook = disable_webhook("654bbbc16f2ec14d77f109cc")
>>> disabled_webhook
WebhookInfo(
    id="654bbbc16f2ec14d77f109cc",
    url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
    jon=None,
    watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
    domains=["repo", "discussion"],
    secret="my-secret",
    disabled=True,
)

Parameters:

webhook_id (str) : The unique identifier of the webhook to disable.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

WebhookInfo

Info about the disabled webhook.

download_bucket_files[[huggingface_hub.HfApi.download_bucket_files]]

Source

Download files from a bucket.

Files input is a list of (remote file, local file) tuples where remote file is either the path of the file in the bucket or a BucketFile object, and local file is the destination path on the local filesystem. When passing a BucketFile object (obtained from list_bucket_tree()), the method will skip the metadata fetching step and directly download the files.

Example:

>>> from huggingface_hub import download_bucket_files

>>> download_bucket_files(
...     bucket_id="username/my-bucket",
...     files=[
...         ("models/model.safetensors", "./local/model.safetensors"),
...         ("config.json", "./local/config.json"),
...     ],
... )
>>> from huggingface_hub import download_bucket_files

>>> parquet_files = [file for file in list_bucket_tree(bucket_id="username/my-bucket") if file.path.endswith(".parquet")]
>>> download_bucket_files(
...     bucket_id="username/my-bucket",
...     files=[(file, f"./local/{file.path}") for file in parquet_files],
... )

Parameters:

bucket_id (str) : The ID of the bucket (e.g. "username/my-bucket").

files (list[tuple[Union[str, BucketFile], Union[str, Path]]]) : Files to download as a list of tuple (source, destination). See description above for format details.

raise_on_missing_files (bool, optional) : If True, raise an EntryNotFoundError when a requested file does not exist in the bucket. If False (default), missing files are skipped with a warning.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

duplicate_repo[[huggingface_hub.HfApi.duplicate_repo]]

Source

Duplicate a repo on the Hub (model, dataset, or Space).

This performs a server-side copy that preserves full git history and LFS objects without requiring a local download/upload round-trip.

Example:

>>> from huggingface_hub import duplicate_repo

# Duplicate a model to your account
>>> duplicate_repo("google/gemma-7b")
RepoUrl('https://huggingface.co/nateraw/gemma-7b',...)

# Duplicate a dataset with a custom name
>>> duplicate_repo("openai/gdpval", to_id="myorg/my-gdpval", repo_type="dataset")
RepoUrl('https://huggingface.co/datasets/myorg/my-gdpval',...)

# Duplicate a Space with custom hardware
>>> duplicate_repo("multimodalart/dreambooth-training", repo_type="space", space_hardware="t4-medium")
RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)

Parameters:

from_id (str) : ID of the repo to duplicate. Example: "openai/gdpval".

to_id (str, optional) : ID of the new repo. Example: "myorg/my-gdpval". If not provided, the new repo will have the same name as the original repo, but in your account.

repo_type (str, optional) : Set to "dataset" or "space" if duplicating a dataset or Space, None or "model" if duplicating a model. Default is None.

private (bool, optional) : Whether the new repo should be private or not. Defaults to the same privacy as the original repo. Cannot be passed together with visibility.

visibility (Literal["public", "private", "protected"], optional) : Visibility of the new repo. Can be "public" or "private", or "protected" for Spaces. Defaults to the same visibility as the original repo.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

exist_ok (bool, optional, defaults to False) : If True, do not raise an error if repo already exists.

space_hardware (SpaceHardware or str, optional) : Choice of Hardware if repo_type is "space". Example: "t4-medium". See SpaceHardware for a complete list.

space_storage (SpaceStorage or str, optional) : Choice of persistent storage tier if repo_type is "space". Example: "small". See SpaceStorage for a complete list.

space_sleep_time (int, optional) : Number of seconds of inactivity to wait before a Space is put to sleep. Set to -1 if you don't want your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure the sleep time (value is fixed to 48 hours of inactivity). Only applicable if repo_type is "space". See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.

space_secrets (list[dict[str, str]], optional) : A list of secret keys to set in your Space. Each item is in the form {"key": ..., "value": ..., "description": ...} where description is optional. Only applicable if repo_type is "space". For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.

space_variables (list[dict[str, str]], optional) : A list of public environment variables to set in your Space. Each item is in the form {"key": ..., "value": ..., "description": ...} where description is optional. Only applicable if repo_type is "space". For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.

space_volumes (list[Volume], optional) : A list of Volume objects to mount in the Space at duplication time. Each volume has a type ("bucket", "model", "dataset", or "space"), a source (repo or bucket ID), a mount_path (path inside the container), and optional revision, read_only, and path fields. Only applicable if repo_type is "space".

Returns:

[RepoUrl](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.RepoUrl)

URL to the newly created repo. Value is a subclass of str containing attributes like endpoint, repo_type and repo_id.

duplicate_space[[huggingface_hub.HfApi.duplicate_space]]

Source

Duplicate a Space.

Programmatically duplicate a Space. The new Space will be created in your account and will be in the same state as the original Space (running or paused). You can duplicate a Space no matter the current state of a Space.

Example:

>>> from huggingface_hub import duplicate_space

# Duplicate a Space to your account
>>> duplicate_space("multimodalart/dreambooth-training")
RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)

# Can set custom destination id and visibility flag.
>>> duplicate_space("multimodalart/dreambooth-training", to_id="my-dreambooth", visibility="private")
RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...)

duplicate_space is deprecated and will be removed in version 2.0. Use duplicate_repo() instead.

Parameters:

from_id (str) : ID of the Space to duplicate. Example: "pharma/CLIP-Interrogator".

to_id (str, optional) : ID of the new Space. Example: "dog/CLIP-Interrogator". If not provided, the new Space will have the same name as the original Space, but in your account.

private (bool, optional) : Whether the new Space should be private or not. Defaults to the same privacy as the original Space. Cannot be passed together with visibility.

visibility (Literal["public", "private", "protected"], optional) : Visibility of the new Space. Can be "public", "private", or "protected". Defaults to the same visibility as the original Space.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

exist_ok (bool, optional, defaults to False) : If True, do not raise an error if repo already exists.

hardware (SpaceHardware or str, optional) : Choice of Hardware. Example: "t4-medium". See SpaceHardware for a complete list.

storage (SpaceStorage or str, optional) : Choice of persistent storage tier. Example: "small". See SpaceStorage for a complete list.

sleep_time (int, optional) : Number of seconds of inactivity to wait before a Space is put to sleep. Set to -1 if you don't want your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure the sleep time (value is fixed to 48 hours of inactivity). See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.

secrets (list[dict[str, str]], optional) : A list of secret keys to set in your Space. Each item is in the form {"key": ..., "value": ..., "description": ...} where description is optional. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets.

variables (list[dict[str, str]], optional) : A list of public environment variables to set in your Space. Each item is in the form {"key": ..., "value": ..., "description": ...} where description is optional. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables.

Returns:

[RepoUrl](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.RepoUrl)

URL to the newly created repo. Value is a subclass of str containing attributes like endpoint, repo_type and repo_id.

edit_discussion_comment[[huggingface_hub.HfApi.edit_discussion_comment]]

Source

Edits a comment on a Discussion / Pull Request.

Raises the following errors:

- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  if some parameter value is invalid
- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

discussion_num (int) : The number of the Discussion or Pull Request . Must be a strictly positive integer.

comment_id (str) : The ID of the comment to edit.

new_content (str) : The new content of the comment. Comments support markdown formatting.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[DiscussionComment](/docs/huggingface_hub/pr_4113/ko/package_reference/community#huggingface_hub.DiscussionComment)

the edited comment

enable_space_dev_mode[[huggingface_hub.HfApi.enable_space_dev_mode]]

Source

Enable dev mode on a Space.

Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you to restart your application without stopping the Space container itself. This feature is available as part of a PRO or Team & Enterprise plan. See https://huggingface.co/docs/hub/spaces-dev-mode for more details.

Parameters:

repo_id (str) : ID of the Space to enable dev mode. Example: "Salesforce/BLIP2".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[SpaceRuntime](/docs/huggingface_hub/pr_4113/ko/package_reference/space_runtime#huggingface_hub.SpaceRuntime)

Runtime information about your Space.

enable_webhook[[huggingface_hub.HfApi.enable_webhook]]

Source

Enable a webhook (makes it "active").

Example:

>>> from huggingface_hub import enable_webhook
>>> enabled_webhook = enable_webhook("654bbbc16f2ec14d77f109cc")
>>> enabled_webhook
WebhookInfo(
    id="654bbbc16f2ec14d77f109cc",
    job=None,
    url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
    watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
    domains=["repo", "discussion"],
    secret="my-secret",
    disabled=False,
)

Parameters:

webhook_id (str) : The unique identifier of the webhook to enable.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

WebhookInfo

Info about the enabled webhook.

fetch_job_logs[[huggingface_hub.HfApi.fetch_job_logs]]

Source

Fetch all the logs from a compute Job on Hugging Face infrastructure.

Example:

>>> from huggingface_hub import fetch_job_logs, run_job
>>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
>>> for log in fetch_job_logs(job_id=job.id):
...     print(log)
Hello from HF compute!

>>> # Non-blocking: fetch only currently available logs
>>> for log in fetch_job_logs(job_id=job.id, follow=False):
...     print(log)

Parameters:

job_id (str) : ID of the Job.

namespace (str, optional) : The namespace where the Job is running. Defaults to the current user's namespace.

follow (bool, optional) : If True, stream logs in real-time until the job completes (blocking). If False (default), fetch only the currently available logs and return immediately (non-blocking).

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

fetch_job_metrics[[huggingface_hub.HfApi.fetch_job_metrics]]

Source

Fetch all the live metrics from a compute Job on Hugging Face infrastructure.

Example:

>>> from huggingface_hub import fetch_job_metrics, run_job
>>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], flavor="a10g-small")
>>> for metrics in fetch_job_metrics(job_id=job.id):
...     print(metrics)
{
    "cpu_usage_pct": 0,
    "cpu_millicores": 3500,
    "memory_used_bytes": 1306624,
    "memory_total_bytes": 15032385536,
    "rx_bps": 0,
    "tx_bps": 0,
    "gpus": {
        "882fa930": {
            "utilization": 0,
            "memory_used_bytes": 0,
            "memory_total_bytes": 22836000000
        }
    },
    "replica": "57vr7"
}

Parameters:

job_id (str) : ID of the Job.

namespace (str, optional) : The namespace where the Job is running. Defaults to the current user's namespace.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

fetch_space_logs[[huggingface_hub.HfApi.fetch_space_logs]]

Source

Fetch the run or build logs of a Space on the Hub.

Useful for debugging a Space that is failing to build or crashing at runtime, especially from a script or agentic workflow where reading logs in a browser is not an option.

Example:

>>> from huggingface_hub import fetch_space_logs
>>> # Non-blocking: print currently available run logs and exit.
>>> for line in fetch_space_logs("username/my-space"):
...     print(line, end="")

>>> # Debug a build failure:
>>> for line in fetch_space_logs("username/my-space", build=True):
...     print(line, end="")

>>> # Stream run logs until the server closes the stream.
>>> for line in fetch_space_logs("username/my-space", follow=True):
...     print(line, end="")

Parameters:

repo_id (str) : ID of the Space. Example: "bigcode/in-the-stack".

build (bool, optional, defaults to False) : If True, fetch the container build logs (useful when a Space is stuck in BUILD_ERROR). If False (default), fetch the run logs, i.e. the stdout/stderr of the running application.

follow (bool, optional, defaults to False) : If True, stream logs in real-time (blocking) until the server closes the stream or KeyboardInterrupt is raised. If False (default), fetch only the currently buffered logs and return immediately (non-blocking, like docker logs).

token (bool or str, optional) : A valid user access token. Defaults to the locally saved token, which is the recommended authentication method. Set to False to disable authentication. See https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

Returns:

Iterable[str]

A generator yielding log lines as they become available.

file_exists[[huggingface_hub.HfApi.file_exists]]

Source

Checks if a file exists in a repository on the Hugging Face Hub.

Examples:

>>> from huggingface_hub import file_exists
>>> file_exists("bigcode/starcoder", "config.json")
True
>>> file_exists("bigcode/starcoder", "not-a-file")
False
>>> file_exists("bigcode/not-a-repo", "config.json")
False

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

filename (str) : The name of the file to check, for example: "config.json"

repo_type (str, optional) : Set to "dataset" or "space" if getting repository info from a dataset or a space, None or "model" if getting repository info from a model. Default is None.

revision (str, optional) : The revision of the repository from which to get the information. Defaults to "main" branch.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

True if the file exists, False otherwise.

get_bucket_file_metadata[[huggingface_hub.HfApi.get_bucket_file_metadata]]

Source

Fetch metadata of a file in a bucket.

Example:

>>> from huggingface_hub import get_bucket_file_metadata
>>> metadata = get_bucket_file_metadata(
...     bucket_id="username/my-bucket",
...     remote_path="models/model.safetensors",
... )
>>> metadata.size
42000

Parameters:

bucket_id (str) : The ID of the bucket (e.g. "username/my-bucket").

remote_path (str) : The path of the file in the bucket.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

BucketFileMetadata

The file metadata containing size and xet information.

get_bucket_paths_info[[huggingface_hub.HfApi.get_bucket_paths_info]]

Source

Get information about a bucket's paths.

Calls are made in batches of 1000 paths. Results are yielded as they are received.

Example:

>>> from huggingface_hub import get_bucket_paths_info
>>> paths_info = get_bucket_paths_info("username/my-bucket", ["file.txt", "checkpoints/model.safetensors"])
>>> for info in paths_info:
...     print(info)
BucketFile(type='file', path='file.txt', size=2379, xet_hash='96e637d9665bd35477b1908a23f2e254edfba0618dbd2d62f90a6baee7d139cf', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc))
BucketFile(type='file', path='checkpoints/model.safetensors', size=2408828, xet_hash='3ed0e9fefe788ddd61d1e26eba67057e9740a064b009256fbafadf6bb95785ca', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc))

Parameters:

bucket_id (str) : The ID of the bucket (e.g. "username/my-bucket").

paths (Iterable[str]) : The paths to get information about. If a path does not exist, it is ignored without raising an exception. Only file paths are supported.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[BucketFile]

The information about the paths, as an iterable of BucketFile objects.

get_collection[[huggingface_hub.HfApi.get_collection]]

Source

Gets information about a Collection on the Hub.

Returns: Collection

Example:

>>> from huggingface_hub import get_collection
>>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
>>> collection.title
'Recent models'
>>> len(collection.items)
37
>>> collection.items[0]
CollectionItem(
    item_object_id='651446103cd773a050bf64c2',
    item_id='TheBloke/U-Amethyst-20B-AWQ',
    item_type='model',
    position=88,
    note=None
)

Parameters:

collection_slug (str) : Slug of the collection of the Hub. Example: "TheBloke/recent-models-64f9a55bb3115b4f513ec026".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

get_dataset_leaderboard[[huggingface_hub.HfApi.get_dataset_leaderboard]]

Source

Get the leaderboard for a dataset on the Hub.

The leaderboard ranks models based on their evaluation scores on the given benchmark dataset. Not all datasets have leaderboards — only benchmark datasets with evaluation results submitted to them. This gives a dataset-centric view of scores; for a model-centric view, use model_info() with expand=["evalResults"].

Raises the following errors:

- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.
- [HfHubHTTPError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.HfHubHTTPError)
  If the dataset does not have a leaderboard.

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> leaderboard = api.get_dataset_leaderboard("allenai/olmOCR-bench")
>>> leaderboard[0].model_id
'datalab-to/chandra-ocr-2'
>>> leaderboard[0].rank
1

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /. For example: "allenai/olmOCR-bench".

token (bool or str, optional) : A valid user access token. Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

timeout (float, optional) : Whether to set a timeout for the request to the Hub.

Returns:

list[DatasetLeaderboardEntry]

A list of DatasetLeaderboardEntry objects representing the leaderboard entries, sorted by rank.

get_dataset_tags[[huggingface_hub.HfApi.get_dataset_tags]]

Source

List all valid dataset tags as a nested namespace object.

get_discussion_details[[huggingface_hub.HfApi.get_discussion_details]]

Source

Fetches a Discussion's / Pull Request 's details from the Hub.

Returns: DiscussionWithDetails

Raises the following errors:

- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  if some parameter value is invalid
- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

discussion_num (int) : The number of the Discussion or Pull Request . Must be a strictly positive integer.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

get_full_repo_name[[huggingface_hub.HfApi.get_full_repo_name]]

Source

Returns the repository name for a given model ID and optional organization.

Parameters:

model_id (str) : The name of the model.

organization (str, optional) : If passed, the repository name will be in the organization namespace instead of the user namespace.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

str

The repository name in the user's namespace ({username}/{model_id}) if no organization is passed, and under the organization namespace ({organization}/{model_id}) otherwise.

get_hf_file_metadata[[huggingface_hub.HfApi.get_hf_file_metadata]]

Source

Fetch metadata of a file versioned on the Hub for a given url.

Parameters:

url (str) : File url, for example returned by hf_hub_url().

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

timeout (float, optional, defaults to 10) : How many seconds to wait for the server to send metadata before giving up.

Returns:

A HfFileMetadata object containing metadata such as location, etag, size and commit_hash.

get_inference_endpoint[[huggingface_hub.HfApi.get_inference_endpoint]]

Source

Get information about an Inference Endpoint.

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.get_inference_endpoint("my-text-to-image")
>>> endpoint
InferenceEndpoint(name='my-text-to-image', ...)

# Get status
>>> endpoint.status
'running'
>>> endpoint.url
'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'

# Run inference
>>> endpoint.client.text_to_image(...)

Parameters:

name (str) : The name of the Inference Endpoint to retrieve information about.

namespace (str, optional) : The namespace in which the Inference Endpoint is located. Defaults to the current user.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[InferenceEndpoint](/docs/huggingface_hub/pr_4113/ko/package_reference/inference_endpoints#huggingface_hub.InferenceEndpoint)

information about the requested Inference Endpoint.

get_model_tags[[huggingface_hub.HfApi.get_model_tags]]

Source

List all valid model tags as a nested namespace object

get_organization_overview[[huggingface_hub.HfApi.get_organization_overview]]

Source

Get an overview of an organization on the Hub.

Parameters:

organization (str) : Name of the organization to get an overview of.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Organization

An Organization object with the organization's overview.

get_paths_info[[huggingface_hub.HfApi.get_paths_info]]

Source

Get information about a repo's paths.

Example:

>>> from huggingface_hub import get_paths_info
>>> paths_info = get_paths_info("allenai/c4", ["README.md", "en"], repo_type="dataset")
>>> paths_info
[
    RepoFile(path='README.md', size=2379, blob_id='f84cb4c97182890fc1dbdeaf1a6a468fd27b4fff', lfs=None, last_commit=None, security=None),
    RepoFolder(path='en', tree_id='dc943c4c40f53d02b31ced1defa7e5f438d5862e', last_commit=None)
]

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

paths (Union[list[str], str], optional) : The paths to get information about. If a path do not exist, it is ignored without raising an exception.

expand (bool, optional, defaults to False) : Whether to fetch more information about the paths (e.g. last commit and files' security scan results). This operation is more expensive for the server so only 50 results are returned per page (instead of 1000). As pagination is implemented in huggingface_hub, this is transparent for you except for the time it takes to get the results.

revision (str, optional) : The revision of the repository from which to get the information. Defaults to "main" branch.

repo_type (str, optional) : The type of the repository from which to get the information ("model", "dataset" or "space". Defaults to "model".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

list[Union[RepoFile, RepoFolder]]

The information about the paths, as a list of RepoFile and RepoFolder objects.

get_repo_discussions[[huggingface_hub.HfApi.get_repo_discussions]]

Source

Fetches Discussions and Pull Requests for the given repo.

Example:

Collecting all discussions of a repo in a list:

>>> from huggingface_hub import get_repo_discussions
>>> discussions_list = list(get_repo_discussions(repo_id="bert-base-uncased"))

Iterating over discussions of a repo:

>>> from huggingface_hub import get_repo_discussions
>>> for discussion in get_repo_discussions(repo_id="bert-base-uncased"):
...     print(discussion.num, discussion.title)

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

author (str, optional) : Pass a value to filter by discussion author. None means no filter. Default is None.

discussion_type (str, optional) : Set to "pull_request" to fetch only pull requests, "discussion" to fetch only discussions. Set to "all" or None to fetch both. Default is None.

discussion_status (str, optional) : Set to "open" (respectively "closed") to fetch only open (respectively closed) discussions. Set to "all" or None to fetch both. Default is None.

repo_type (str, optional) : Set to "dataset" or "space" if fetching from a dataset or space, None or "model" if fetching from a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterator[Discussion]

An iterator of Discussion objects.

get_safetensors_metadata[[huggingface_hub.HfApi.get_safetensors_metadata]]

Source

Parse metadata for a safetensors repo on the Hub.

We first check if the repo has a single safetensors file or a sharded safetensors repo. If it's a single safetensors file, we parse the metadata from this file. If it's a sharded safetensors repo, we parse the metadata from the index file and then parse the metadata from each shard.

To parse metadata from a single safetensors file, use parse_safetensors_file_metadata().

For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.

Example:

# Parse repo with single weights file
>>> metadata = get_safetensors_metadata("bigscience/bloomz-560m")
>>> metadata
SafetensorsRepoMetadata(
    metadata=None,
    sharded=False,
    weight_map={'h.0.input_layernorm.bias': 'model.safetensors', ...},
    files_metadata={'model.safetensors': SafetensorsFileMetadata(...)}
)
>>> metadata.files_metadata["model.safetensors"].metadata
{'format': 'pt'}

# Parse repo with sharded model
>>> metadata = get_safetensors_metadata("bigscience/bloom")
Parse safetensors files: 100%|██████████████████████████████████████████| 72/72 [00:12>> metadata
SafetensorsRepoMetadata(metadata={'total_size': 352494542848}, sharded=True, weight_map={...}, files_metadata={...})
>>> len(metadata.files_metadata)
72  # All safetensors files have been fetched

# Parse repo with sharded model
>>> get_safetensors_metadata("runwayml/stable-diffusion-v1-5")
NotASafetensorsRepoError: 'runwayml/stable-diffusion-v1-5' is not a safetensors repo. Couldn't find 'model.safetensors.index.json' or 'model.safetensors' files.

Parameters:

repo_id (str) : A user or an organization name and a repo name separated by a /.

repo_type (str, optional) : Set to "dataset" or "space" if the file is in a dataset or space, None or "model" if in a model. Default is None.

revision (str, optional) : The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the head of the "main" branch.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

SafetensorsRepoMetadata

information related to safetensors repo.

get_space_runtime[[huggingface_hub.HfApi.get_space_runtime]]

Source

Gets runtime information about a Space.

Parameters:

repo_id (str) : ID of the repo to update. Example: "bigcode/in-the-stack".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[SpaceRuntime](/docs/huggingface_hub/pr_4113/ko/package_reference/space_runtime#huggingface_hub.SpaceRuntime)

Runtime information about a Space including Space stage and hardware.

get_space_variables[[huggingface_hub.HfApi.get_space_variables]]

Source

Gets all variables from a Space.

Variables allow to set environment variables to a Space without hardcoding them. For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables

Parameters:

repo_id (str) : ID of the repo to query. Example: "bigcode/in-the-stack".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

get_user_overview[[huggingface_hub.HfApi.get_user_overview]]

Source

Get an overview of a user on the Hub.

Parameters:

username (str) : Username of the user to get an overview of.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

User

A User object with the user's overview.

get_webhook[[huggingface_hub.HfApi.get_webhook]]

Source

Get a webhook by its id.

Example:

>>> from huggingface_hub import get_webhook
>>> webhook = get_webhook("654bbbc16f2ec14d77f109cc")
>>> print(webhook)
WebhookInfo(
    id="654bbbc16f2ec14d77f109cc",
    job=None,
    watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
    url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
    secret="my-secret",
    domains=["repo", "discussion"],
    disabled=False,
)

Parameters:

webhook_id (str) : The unique identifier of the webhook to get.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

WebhookInfo

Info about the webhook.

grant_access[[huggingface_hub.HfApi.grant_access]]

Source

Grant access to a user for a given gated repo.

Granting access don't require for the user to send an access request by themselves. The user is automatically added to the accepted list meaning they can download the files You can revoke the granted access at any time using cancel_access_request() or reject_access_request().

For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

Parameters:

repo_id (str) : The id of the repo to grant access to.

user (str) : The username of the user to grant access.

repo_type (str, optional) : The type of the repo to grant access to. Must be one of model, dataset or space. Defaults to model.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

hf_hub_download[[huggingface_hub.HfApi.hf_hub_download]]

Source

Download a given file if it's not already present in the local cache.

The new cache file layout looks like this:

  • The cache directory contains one subfolder per repo_id (namespaced by repo type)
  • inside each repo folder:
    • refs is a list of the latest known revision => commit_hash pairs
    • blobs contains the actual file blobs (identified by their git-sha or sha256, depending on whether they're LFS files or not)
    • snapshots contains one subfolder per commit, each "commit" contains the subset of the files that have been resolved at that particular commit. Each filename is a symlink to the blob at that particular commit.
[  96]  .
└── [ 160]  models--julien-c--EsperBERTo-small
    ├── [ 160]  blobs
    │   ├── [321M]  403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
    │   ├── [ 398]  7cb18dc9bafbfcf74629a4b760af1b160957a83e
    │   └── [1.4K]  d7edf6bd2a681fb0175f7735299831ee1b22b812
    ├── [  96]  refs
    │   └── [  40]  main
    └── [ 128]  snapshots
        ├── [ 128]  2439f60ef33a0d46d85da5001d52aeda5b00ce9f
        │   ├── [  52]  README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
        │   └── [  76]  pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
        └── [ 128]  bbc77c8132af1cc5cf678da3f1ddf2de43606d48
            ├── [  52]  README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
            └── [  76]  pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd

If local_dir is provided, the file structure from the repo will be replicated in this location. When using this option, the cache_dir will not be used and a .cache/huggingface/ folder will be created at the root of local_dir to store some metadata related to the downloaded files. While this mechanism is not as robust as the main cache-system, it's optimized for regularly pulling the latest version of a repository.

Parameters:

repo_id (str) : A user or an organization name and a repo name separated by a /.

filename (str) : The name of the file in the repo.

subfolder (str, optional) : An optional value corresponding to a folder inside the repository.

repo_type (str, optional) : Set to "dataset" or "space" if downloading from a dataset or space, None or "model" if downloading from a model. Default is None.

revision (str, optional) : An optional Git revision id which can be a branch name, a tag, or a commit hash.

cache_dir (str, Path, optional) : Path to the folder where cached files are stored.

local_dir (str or Path, optional) : If provided, the downloaded file will be placed under this directory.

force_download (bool, optional, defaults to False) : Whether the file should be downloaded even if it already exists in the local cache.

etag_timeout (float, optional, defaults to 10) : When fetching ETag, how many seconds to wait for the server to send data before giving up which is passed to httpx.request.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

local_files_only (bool, optional, defaults to False) : If True, avoid downloading the file and return the path to the local cached file if it exists.

tqdm_class (tqdm, optional) : If provided, overwrites the default behavior for the progress bar. Passed argument must inherit from tqdm.auto.tqdm or at least mimic its behavior. Defaults to the custom HF progress bar that can be disabled by setting HF_HUB_DISABLE_PROGRESS_BARS environment variable.

dry_run (bool, optional, defaults to False) : If True, perform a dry run without actually downloading the file. Returns a DryRunFileInfo object containing information about what would be downloaded.

Returns:

str` or `DryRunFileInfo

  • If dry_run=False: Local path of file or if networking is off, last version of file cached on disk.
  • If dry_run=True: A DryRunFileInfo object containing download information.

hide_discussion_comment[[huggingface_hub.HfApi.hide_discussion_comment]]

Source

Hides a comment on a Discussion / Pull Request.

Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.

Raises the following errors:

- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  if some parameter value is invalid
- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

discussion_num (int) : The number of the Discussion or Pull Request . Must be a strictly positive integer.

comment_id (str) : The ID of the comment to edit.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[DiscussionComment](/docs/huggingface_hub/pr_4113/ko/package_reference/community#huggingface_hub.DiscussionComment)

the hidden comment

inspect_job[[huggingface_hub.HfApi.inspect_job]]

Source

Inspect a compute Job on Hugging Face infrastructure.

Example:

>>> from huggingface_hub import inspect_job, run_job
>>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
>>> inspect_job(job.id)
JobInfo(
    id='68780d00bbe36d38803f645f',
    created_at=datetime.datetime(2025, 7, 16, 20, 35, 12, 808000, tzinfo=datetime.timezone.utc),
    docker_image='python:3.12',
    space_id=None,
    command=['python', '-c', "print('Hello from HF compute!')"],
    arguments=[],
    environment={},
    secrets={},
    flavor='cpu-basic',
    status=JobStatus(stage='RUNNING', message=None)
)

Parameters:

job_id (str) : ID of the Job.

namespace (str, optional) : The namespace where the Job is running. Defaults to the current user's namespace.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

inspect_scheduled_job[[huggingface_hub.HfApi.inspect_scheduled_job]]

Source

Inspect a scheduled compute Job on Hugging Face infrastructure.

Example:

>>> from huggingface_hub import inspect_job, create_scheduled_job
>>> scheduled_job = create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly")
>>> inspect_scheduled_job(scheduled_job.id)

Parameters:

scheduled_job_id (str) : ID of the scheduled Job.

namespace (str, optional) : The namespace where the scheduled Job is. Defaults to the current user's namespace.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

kernel_info[[huggingface_hub.HfApi.kernel_info]]

Source

Get info on one specific kernel on huggingface.co.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

revision (str, optional) : The revision of the kernel repository from which to get the information.

timeout (float, optional) : Whether to set a timeout for the request to the Hub.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[ModelInfo](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.ModelInfo)

The kernel repository information.

list_accepted_access_requests[[huggingface_hub.HfApi.list_accepted_access_requests]]

Source

Get accepted access requests for a given gated repo.

An accepted request means the user has requested access to the repo and the request has been accepted. The user can download any file of the repo. If the approval mode is automatic, this list should contains by default all requests. Accepted requests can be cancelled or rejected at any time using cancel_access_request() and reject_access_request(). A cancelled request will go back to the pending list while a rejected request will go to the rejected list. In both cases, the user will lose access to the repo.

For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

Example:

>>> from huggingface_hub import list_accepted_access_requests

>>> requests = list(list_accepted_access_requests("meta-llama/Llama-2-7b"))
>>> len(requests)
411
>>> requests[0]
[
    AccessRequest(
        username='clem',
        fullname='Clem 🤗',
        email='***',
        timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
        status='accepted',
        fields=None,
    ),
    ...
]

Parameters:

repo_id (str) : The id of the repo to get access requests for.

repo_type (str, optional) : The type of the repo to get access requests for. Must be one of model, dataset or space. Defaults to model.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[AccessRequest]

An iterable of AccessRequest objects. Each time contains a username, email, status and timestamp attribute. If the gated repo has a custom form, the fields attribute will be populated with user's answers.

list_bucket_tree[[huggingface_hub.HfApi.list_bucket_tree]]

Source

List files in a bucket.

Example:

>>> from huggingface_hub import list_bucket_tree
>>> for file_info in list_bucket_tree(bucket_id="username/my-bucket"):
...     print(file_info.path)

>>> # Filter by prefix
>>> for file_info in list_bucket_tree(bucket_id="username/my-bucket", prefix="models/"):
...     print(file_info.path)

Parameters:

bucket_id (str) : The ID of the bucket (e.g. "username/my-bucket").

prefix (str, optional) : Filter results to files whose path starts with this prefix.

recursive (bool, optional) : If True, list files recursively. If False (default), list files and directories only at root.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[Union[BucketFile, BucketFolder]]

An iterable of BucketFile and BucketFolder objects containing file and directory information (path, etc.).

list_buckets[[huggingface_hub.HfApi.list_buckets]]

Source

List buckets on the Hub under a certain namespace.

Example:

>>> from huggingface_hub import list_buckets
>>> for bucket in list_buckets(): # lists buckets in the user's namespace
...     print(bucket)

>>> for bucket in list_buckets(namespace="huggingface"): # lists buckets in the "huggingface" organization
...     print(bucket)

Parameters:

namespace (str, optional) : List buckets under this namespace (user or organization). Defaults to listing user's buckets.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[BucketInfo]

An iterable of BucketInfo objects.

list_collections[[huggingface_hub.HfApi.list_collections]]

Source

List collections on the Huggingface Hub, given some filters.

When listing collections, the item list per collection is truncated to 4 items maximum. To retrieve all items from a collection, you must use get_collection().

Parameters:

owner (list[str] or str, optional) : Filter by owner's username.

item (list[str] or str, optional) : Filter collections containing a particular items. Example: "models/teknium/OpenHermes-2.5-Mistral-7B", "datasets/squad" or "papers/2311.12983".

sort (Literal["lastModified", "trending", "upvotes"], optional) : Sort collections by last modified, trending or upvotes.

limit (int, optional) : Maximum number of collections to be returned.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[Collection]

an iterable of Collection objects.

list_daily_papers[[huggingface_hub.HfApi.list_daily_papers]]

Source

List the daily papers published on a given date on the Hugging Face Hub.

Example:

>>> from huggingface_hub import HfApi

>>> api = HfApi()
>>> list(api.list_daily_papers(date="2025-10-29"))

Parameters:

date (str, optional) : Date in ISO format (YYYY-MM-DD) for which to fetch daily papers. Defaults to most recent ones.

token (Union[bool, str, None], optional) : A valid user access token (string). Defaults to the locally saved token. To disable authentication, pass False.

week (str, optional) : Week in ISO format (YYYY-Www) for which to fetch daily papers. Example, 2025-W09.

month (str, optional) : Month in ISO format (YYYY-MM) for which to fetch daily papers. Example, 2025-02.

submitter (str, optional) : Username of the submitter to filter daily papers.

sort (Literal["publishedAt", "trending"], optional) : Sort order for the daily papers. Can be either by publishedAt or by trending. Defaults to "publishedAt"

p (int, optional) : Page number for pagination. Defaults to 0.

limit (int, optional) : Limit of papers to fetch. Defaults to 50.

Returns:

Iterable[PaperInfo]

an iterable of huggingface_hub.hf_api.PaperInfo objects.

list_dataset_parquet_files[[huggingface_hub.HfApi.list_dataset_parquet_files]]

Source

List parquet files available for a dataset on the Hub.

All datasets hosted on the Hub are auto-converted to Parquet by the Dataset Viewer. This method returns the list of parquet files with their URLs, configs, splits and sizes.

Example:

>>> from huggingface_hub import list_dataset_parquet_files
>>> list_dataset_parquet_files("lhoestq/demo1")
>>> entries[0]
DatasetParquetEntry(config='default', split='train', url='https://huggingface.co/...', size=5038)

Parameters:

repo_id (str) : The dataset repository ID (e.g. "username/dataset-name").

config (str, optional) : Filter by a specific config/subset name. When provided, only parquet files for that config are returned.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

list[DatasetParquetEntry]

a list of DatasetParquetEntry objects containing config, split, url and size for each parquet file.

list_datasets[[huggingface_hub.HfApi.list_datasets]]

Source

List datasets hosted on the Huggingface Hub, given some filters.

Example usage with the filter argument:

>>> from huggingface_hub import HfApi

>>> api = HfApi()

# List all datasets
>>> api.list_datasets()

# List only the text classification datasets
>>> api.list_datasets(filter="task_categories:text-classification")

# List only the datasets in russian for language modeling
>>> api.list_datasets(
...     filter=("language:ru", "task_ids:language-modeling")
... )

# List FiftyOne datasets (identified by the tag "fiftyone" in dataset card)
>>> api.list_datasets(tags="fiftyone")

Example usage with the search argument:

>>> from huggingface_hub import HfApi

>>> api = HfApi()

# List all datasets with "text" in their name
>>> api.list_datasets(search="text")

# List all datasets with "text" in their name made by google
>>> api.list_datasets(search="text", author="google")

Parameters:

filter (str or Iterable[str], optional) : A string or list of string to filter datasets on the hub.

author (str, optional) : A string which identify the author of the returned datasets.

benchmark (True, "official", str, optional) : Filter datasets by benchmark. Can be True or "official" to return official benchmark datasets. For future-compatibility, can also be a string representing the benchmark name (currently only "official" is supported).

dataset_name (str, optional) : A string or list of strings that can be used to identify datasets on the Hub by its name, such as SQAC or wikineural

gated (bool, optional) : A boolean to filter datasets on the Hub that are gated or not. By default, all datasets are returned. If gated=True is passed, only gated datasets are returned. If gated=False is passed, only non-gated datasets are returned.

language_creators (str or List, optional) : A string or list of strings that can be used to identify datasets on the Hub with how the data was curated, such as crowdsourced or machine_generated.

language (str or List, optional) : A string or list of strings representing a two-character language to filter datasets by on the Hub.

multilinguality (str or List, optional) : A string or list of strings representing a filter for datasets that contain multiple languages.

size_categories (str or List, optional) : A string or list of strings that can be used to identify datasets on the Hub by the size of the dataset such as `100K [!WARNING]

list_inference_catalog is experimental. Its API is subject to change in the future. Please provide feedback if you have any suggestions or requests.

Parameters:

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).

Returns:

Liststr``

A list of model IDs available in the catalog.

list_inference_endpoints[[huggingface_hub.HfApi.list_inference_endpoints]]

Source

Lists all inference endpoints for the given namespace.

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.list_inference_endpoints()
[InferenceEndpoint(name='my-endpoint', ...), ...]

Parameters:

namespace (str, optional) : The namespace to list endpoints for. Defaults to the current user. Set to "*" to list all endpoints from all namespaces (i.e. personal namespace and all orgs the user belongs to).

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

list[InferenceEndpoint](/docs/huggingface_hub/pr_4113/ko/package_reference/inference_endpoints#huggingface_hub.InferenceEndpoint)

A list of all inference endpoints for the given namespace.

list_jobs[[huggingface_hub.HfApi.list_jobs]]

Source

List compute Jobs on Hugging Face infrastructure.

Parameters:

timeout (float, optional) : Whether to set a timeout for the request to the Hub.

namespace (str, optional) : The namespace from where it lists the jobs. Defaults to the current user's namespace.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

list_jobs_hardware[[huggingface_hub.HfApi.list_jobs_hardware]]

Source

List available hardware options for Jobs on Hugging Face infrastructure.

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> hardware_list = api.list_jobs_hardware()
>>> hardware_list[0]
JobHardware(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', accelerator=None, unit_cost_micro_usd=167, unit_cost_usd=0.000167, unit_label='minute')
>>> hardware_list[0].name
'cpu-basic'

# Filter GPU options
>>> gpu_hardware = [hw for hw in hardware_list if hw.accelerator is not None]
>>> gpu_hardware[0].accelerator.model
'T4'

Returns:

list[JobHardware]

A list of available hardware configurations.

list_lfs_files[[huggingface_hub.HfApi.list_lfs_files]]

Source

List all LFS files in a repo on the Hub.

This is primarily useful to count how much storage a repo is using and to eventually clean up large files with permanently_delete_lfs_files(). Note that this would be a permanent action that will affect all commits referencing this deleted files and that cannot be undone.

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> lfs_files = api.list_lfs_files("username/my-cool-repo")

# Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
# e.g. select only LFS files in the "checkpoints" folder
>>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))

# Permanently delete LFS files
>>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)

Parameters:

repo_id (str) : The repository for which you are listing LFS files.

repo_type (str, optional) : Type of repository. Set to "dataset" or "space" if listing from a dataset or space, None or "model" if listing from a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[LFSFileInfo]

An iterator of LFSFileInfo objects.

list_liked_repos[[huggingface_hub.HfApi.list_liked_repos]]

Source

List all public repos liked by a user on huggingface.co.

This list is public so token is optional. If user is not passed, it defaults to the logged in user.

See also unlike().

Example:

>>> from huggingface_hub import list_liked_repos

>>> likes = list_liked_repos("julien-c")

>>> likes.user
"julien-c"

>>> likes.models
["osanseviero/streamlit_1.15", "Xhaheen/ChatGPT_HF", ...]

Parameters:

user (str, optional) : Name of the user for which you want to fetch the likes.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[UserLikes](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.UserLikes)

object containing the user name and 3 lists of repo ids (1 for models, 1 for datasets and 1 for Spaces).

list_models[[huggingface_hub.HfApi.list_models]]

Source

List models hosted on the Huggingface Hub, given some filters.

Example:

>>> from huggingface_hub import HfApi

>>> api = HfApi()

# List all models
>>> api.list_models()

# List text classification models
>>> api.list_models(filter="text-classification")

# List models from the KerasHub library
>>> api.list_models(filter="keras-hub")

# List models served by Cohere
>>> api.list_models(inference_provider="cohere")

# List models with "bert" in their name
>>> api.list_models(search="bert")

# List models with "bert" in their name and pushed by google
>>> api.list_models(search="bert", author="google")

# List models with 6B to 128B parameters
>>> api.list_models(num_parameters="min:6B,max:128B", sort="likes")

Parameters:

filter (str or Iterable[str], optional) : A string or list of string to filter models on the Hub. Models can be filtered by library, language, task, tags, and more.

author (str, optional) : A string which identify the author (user or organization) of the returned models.

apps (str or List, optional) : A string or list of strings to filter models on the Hub that support the specified apps. Example values include "ollama" or ["ollama", "vllm"].

gated (bool, optional) : A boolean to filter models on the Hub that are gated or not. By default, all models are returned. If gated=True is passed, only gated models are returned. If gated=False is passed, only non-gated models are returned.

inference (Literal["warm"], optional) : If "warm", filter models on the Hub currently served by at least one provider.

inference_provider (Literal["all"] or str, optional) : A string to filter models on the Hub that are served by a specific provider. Pass "all" to get all models served by at least one provider.

model_name (str, optional) : A string that contain complete or partial names for models on the Hub, such as "bert" or "bert-base-cased"

trained_dataset (str or List, optional) : A string tag or a list of string tags of the trained dataset for a model on the Hub.

search (str, optional) : A string that will be contained in the returned model ids.

pipeline_tag (str, optional) : A string pipeline tag to filter models on the Hub by, such as summarization.

num_parameters (str, optional) : Filter models by parameter count. Accepts the same range syntax as the Hub UI and API, for example "min:6B,max:128B", "min:6B" or "max:128B".

emissions_thresholds (Tuple, optional) : A tuple of two ints or floats representing a minimum and maximum carbon footprint to filter the resulting models with in grams.

sort (ModelSort_T, optional) : The key with which to sort the resulting models. Possible values are "created_at", "downloads", "last_modified", "likes" and "trending_score".

limit (int, optional) : The limit on the number of models fetched. Leaving this option to None fetches all models.

expand (list[ExpandModelProperty_T], optional) : List properties to return in the response. When used, only the properties in the list will be returned. This parameter cannot be used if full, cardData or fetch_config are passed. Possible values are "author", "cardData", "config", "createdAt", "disabled", "downloads", "downloadsAllTime", "evalResults", "gated", "gguf", "inference", "inferenceProviderMapping", "lastModified", "library_name", "likes", "mask_token", "model-index", "pipeline_tag", "private", "safetensors", "sha", "siblings", "spaces", "tags", "transformersInfo", "trendingScore", "widgetData", and "resourceGroup".

full (bool, optional) : Whether to fetch all model data, including the last_modified, the sha, the files and the tags. This is set to True by default when using a filter.

cardData (bool, optional) : Whether to grab the metadata for the model as well. Can contain useful information such as carbon emissions, metrics, and datasets trained on.

fetch_config (bool, optional) : Whether to fetch the model configs as well. This is not included in full due to its size.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[ModelInfo]

an iterable of huggingface_hub.hf_api.ModelInfo objects.

list_organization_followers[[huggingface_hub.HfApi.list_organization_followers]]

Source

List followers of an organization on the Hub.

Parameters:

organization (str) : Name of the organization to get the followers of.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[User]

A list of User objects with the followers of the organization.

list_organization_members[[huggingface_hub.HfApi.list_organization_members]]

Source

List of members of an organization on the Hub.

Parameters:

organization (str) : Name of the organization to get the members of.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[User]

A list of User objects with the members of the organization.

list_papers[[huggingface_hub.HfApi.list_papers]]

Source

List daily papers on the Hugging Face Hub given a search query.

Example:

>>> from huggingface_hub import HfApi

>>> api = HfApi()

# List all papers with "attention" in their title
>>> api.list_papers(query="attention")

Parameters:

query (str, optional) : A search query string to find papers. If provided, returns papers that match the query.

limit (int, optional) : The maximum number of papers to return.

token (Union[bool, str, None], optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[PaperInfo]

an iterable of huggingface_hub.hf_api.PaperInfo objects.

list_pending_access_requests[[huggingface_hub.HfApi.list_pending_access_requests]]

Source

Get pending access requests for a given gated repo.

A pending request means the user has requested access to the repo but the request has not been processed yet. If the approval mode is automatic, this list should be empty. Pending requests can be accepted or rejected using accept_access_request() and reject_access_request().

For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

Example:

>>> from huggingface_hub import list_pending_access_requests, accept_access_request

# List pending requests
>>> requests = list(list_pending_access_requests("meta-llama/Llama-2-7b"))
>>> len(requests)
411
>>> requests[0]
[
    AccessRequest(
        username='clem',
        fullname='Clem 🤗',
        email='***',
        timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
        status='pending',
        fields=None,
    ),
    ...
]

# Accept Clem's request
>>> accept_access_request("meta-llama/Llama-2-7b", "clem")

Parameters:

repo_id (str) : The id of the repo to get access requests for.

repo_type (str, optional) : The type of the repo to get access requests for. Must be one of model, dataset or space. Defaults to model.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[AccessRequest]

An iterable of AccessRequest objects. Each time contains a username, email, status and timestamp attribute. If the gated repo has a custom form, the fields attribute will be populated with user's answers.

list_rejected_access_requests[[huggingface_hub.HfApi.list_rejected_access_requests]]

Source

Get rejected access requests for a given gated repo.

A rejected request means the user has requested access to the repo and the request has been explicitly rejected by a repo owner (either you or another user from your organization). The user cannot download any file of the repo. Rejected requests can be accepted or cancelled at any time using accept_access_request() and cancel_access_request(). A cancelled request will go back to the pending list while an accepted request will go to the accepted list.

For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

Example:

>>> from huggingface_hub import list_rejected_access_requests

>>> requests = list(list_rejected_access_requests("meta-llama/Llama-2-7b"))
>>> len(requests)
411
>>> requests[0]
[
    AccessRequest(
        username='clem',
        fullname='Clem 🤗',
        email='***',
        timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
        status='rejected',
        fields=None,
    ),
    ...
]

Parameters:

repo_id (str) : The id of the repo to get access requests for.

repo_type (str, optional) : The type of the repo to get access requests for. Must be one of model, dataset or space. Defaults to model.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[AccessRequest]

An iterable of AccessRequest objects. Each time contains a username, email, status and timestamp attribute. If the gated repo has a custom form, the fields attribute will be populated with user's answers.

list_repo_commits[[huggingface_hub.HfApi.list_repo_commits]]

Source

Get the list of commits of a given revision for a repo on the Hub.

Commits are sorted by date (last commit first).

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()

# Commits are sorted by date (last commit first)
>>> initial_commit = api.list_repo_commits("gpt2")[-1]

# Initial commit is always a system commit containing the `.gitattributes` file.
>>> initial_commit
GitCommitInfo(
    commit_id='9b865efde13a30c13e0a33e536cf3e4a5a9d71d8',
    authors=['system'],
    created_at=datetime.datetime(2019, 2, 18, 10, 36, 15, tzinfo=datetime.timezone.utc),
    title='initial commit',
    message='',
    formatted_title=None,
    formatted_message=None
)

# Create an empty branch by deriving from initial commit
>>> api.create_branch("gpt2", "new_empty_branch", revision=initial_commit.commit_id)

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

repo_type (str, optional) : Set to "dataset" or "space" if listing commits from a dataset or a Space, None or "model" if listing from a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

revision (str, optional) : The git revision to commit from. Defaults to the head of the "main" branch.

formatted (bool) : Whether to return the HTML-formatted title and description of the commits. Defaults to False.

Returns:

list[[GitCommitInfo](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.GitCommitInfo)]

list of objects containing information about the commits for a repo on the Hub.

list_repo_files[[huggingface_hub.HfApi.list_repo_files]]

Source

Get the list of files in a given repo.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

revision (str, optional) : The revision of the repository from which to get the information.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

list[str]

the list of files in a given repository.

list_repo_likers[[huggingface_hub.HfApi.list_repo_likers]]

Source

List all users who liked a given repo on the hugging Face Hub.

See also list_liked_repos().

Parameters:

repo_id (str) : The repository to retrieve . Example: "user/my-cool-model".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

Returns:

Iterable[User]

an iterable of huggingface_hub.hf_api.User objects.

list_repo_refs[[huggingface_hub.HfApi.list_repo_refs]]

Source

Get the list of refs of a given repo (both tags and branches).

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.list_repo_refs("gpt2")
GitRefs(branches=[GitRefInfo(name='main', ref='refs/heads/main', target_commit='e7da7f221d5bf496a48136c0cd264e630fe9fcc8')], converts=[], tags=[])

>>> api.list_repo_refs("bigcode/the-stack", repo_type='dataset')
GitRefs(
    branches=[
        GitRefInfo(name='main', ref='refs/heads/main', target_commit='18edc1591d9ce72aa82f56c4431b3c969b210ae3'),
        GitRefInfo(name='v1.1.a1', ref='refs/heads/v1.1.a1', target_commit='f9826b862d1567f3822d3d25649b0d6d22ace714')
    ],
    converts=[],
    tags=[
        GitRefInfo(name='v1.0', ref='refs/tags/v1.0', target_commit='c37a8cd1e382064d8aced5e05543c5f7753834da')
    ]
)

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

repo_type (str, optional) : Set to "dataset", "space" or "kernel" if listing refs from a dataset, a Space or a Kernel, None or "model" if listing from a model. Default is None.

include_pull_requests (bool, optional) : Whether to include refs from pull requests in the list. Defaults to False.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[GitRefs](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.GitRefs)

object containing all information about branches and tags for a repo on the Hub.

list_repo_tree[[huggingface_hub.HfApi.list_repo_tree]]

Source

List a repo tree's files and folders and get information about them.

Examples:

Get information about a repo's tree.

>>> from huggingface_hub import list_repo_tree
>>> repo_tree = list_repo_tree("lysandre/arxiv-nlp")
>>> repo_tree

>>> list(repo_tree)
[
    RepoFile(path='.gitattributes', size=391, blob_id='ae8c63daedbd4206d7d40126955d4e6ab1c80f8f', lfs=None, last_commit=None, security=None),
    RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None),
    RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None),
    RepoFile(
        path='flax_model.msgpack', size=497764107, blob_id='8095a62ccb4d806da7666fcda07467e2d150218e',
        lfs={'size': 497764107, 'sha256': 'd88b0d6a6ff9c3f8151f9d3228f57092aaea997f09af009eefd7373a77b5abb9', 'pointer_size': 134}, last_commit=None, security=None
    ),
    RepoFile(path='merges.txt', size=456318, blob_id='226b0752cac7789c48f0cb3ec53eda48b7be36cc', lfs=None, last_commit=None, security=None),
    RepoFile(
        path='pytorch_model.bin', size=548123560, blob_id='64eaa9c526867e404b68f2c5d66fd78e27026523',
        lfs={'size': 548123560, 'sha256': '9be78edb5b928eba33aa88f431551348f7466ba9f5ef3daf1d552398722a5436', 'pointer_size': 134}, last_commit=None, security=None
    ),
    RepoFile(path='vocab.json', size=898669, blob_id='b00361fece0387ca34b4b8b8539ed830d644dbeb', lfs=None, last_commit=None, security=None)]
]

Get even more information about a repo's tree (last commit and files' security scan results)

>>> from huggingface_hub import list_repo_tree
>>> repo_tree = list_repo_tree("prompthero/openjourney-v4", expand=True)
>>> list(repo_tree)
[
    RepoFolder(
        path='feature_extractor',
        tree_id='aa536c4ea18073388b5b0bc791057a7296a00398',
        last_commit={
            'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
            'title': 'Upload diffusers weights (#48)',
            'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
        }
    ),
    RepoFolder(
        path='safety_checker',
        tree_id='65aef9d787e5557373fdf714d6c34d4fcdd70440',
        last_commit={
            'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
            'title': 'Upload diffusers weights (#48)',
            'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
        }
    ),
    RepoFile(
        path='model_index.json',
        size=582,
        blob_id='d3d7c1e8c3e78eeb1640b8e2041ee256e24c9ee1',
        lfs=None,
        last_commit={
            'oid': 'b195ed2d503f3eb29637050a886d77bd81d35f0e',
            'title': 'Fix deprecation warning by changing `CLIPFeatureExtractor` to `CLIPImageProcessor`. (#54)',
            'date': datetime.datetime(2023, 5, 15, 21, 41, 59, tzinfo=datetime.timezone.utc)
        },
        security={
            'safe': True,
            'av_scan': {'virusFound': False, 'virusNames': None},
            'pickle_import_scan': None
        }
    )
    ...
]

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

path_in_repo (str, optional) : Relative path of the tree (folder) in the repo, for example: "checkpoints/1fec34a/results". Will default to the root tree (folder) of the repository.

recursive (bool, optional, defaults to False) : Whether to list tree's files and folders recursively.

expand (bool, optional, defaults to False) : Whether to fetch more information about the tree's files and folders (e.g. last commit and files' security scan results). This operation is more expensive for the server so only 50 results are returned per page (instead of 1000). As pagination is implemented in huggingface_hub, this is transparent for you except for the time it takes to get the results.

revision (str, optional) : The revision of the repository from which to get the tree. Defaults to "main" branch.

repo_type (str, optional) : The type of the repository from which to get the tree ("model", "dataset", "space" or "kernel"). Defaults to "model".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[Union[RepoFile, RepoFolder]]

The information about the tree's files and folders, as an iterable of RepoFile and RepoFolder objects. The order of the files and folders is not guaranteed.

list_scheduled_jobs[[huggingface_hub.HfApi.list_scheduled_jobs]]

Source

List scheduled compute Jobs on Hugging Face infrastructure.

Parameters:

timeout (float, optional) : Whether to set a timeout for the request to the Hub.

namespace (str, optional) : The namespace from where it lists the jobs. Defaults to the current user's namespace.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

list_spaces[[huggingface_hub.HfApi.list_spaces]]

Source

List spaces hosted on the Huggingface Hub, given some filters.

Parameters:

filter (str or Iterable, optional) : A string tag or list of tags that can be used to identify Spaces on the Hub.

author (str, optional) : A string which identify the author of the returned Spaces.

search (str, optional) : A string that will be contained in the returned Spaces.

datasets (str or Iterable, optional) : Whether to return Spaces that make use of a dataset. The name of a specific dataset can be passed as a string.

models (str or Iterable, optional) : Whether to return Spaces that make use of a model. The name of a specific model can be passed as a string.

linked (bool, optional) : Whether to return Spaces that make use of either a model or a dataset.

sort (SpaceSort_T, optional) : The key with which to sort the resulting spaces. Possible values are "created_at", "last_modified", "likes" and "trending_score".

limit (int, optional) : The limit on the number of Spaces fetched. Leaving this option to None fetches all Spaces.

expand (list[ExpandSpaceProperty_T], optional) : List properties to return in the response. When used, only the properties in the list will be returned. This parameter cannot be used if full is passed. Possible values are "author", "cardData", "datasets", "disabled", "lastModified", "createdAt", "likes", "models", "private", "runtime", "sdk", "siblings", "sha", "subdomain", "tags", "trendingScore", "usedStorage", and "resourceGroup".

full (bool, optional) : Whether to fetch all Spaces data, including the last_modified, siblings and card_data fields.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[SpaceInfo]

an iterable of huggingface_hub.hf_api.SpaceInfo objects.

list_user_followers[[huggingface_hub.HfApi.list_user_followers]]

Source

Get the list of followers of a user on the Hub.

Parameters:

username (str) : Username of the user to get the followers of.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[User]

A list of User objects with the followers of the user.

list_user_following[[huggingface_hub.HfApi.list_user_following]]

Source

Get the list of users followed by a user on the Hub.

Parameters:

username (str) : Username of the user to get the users followed by.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[User]

A list of User objects with the users followed by the user.

list_webhooks[[huggingface_hub.HfApi.list_webhooks]]

Source

List all configured webhooks.

Example:

>>> from huggingface_hub import list_webhooks
>>> webhooks = list_webhooks()
>>> len(webhooks)
2
>>> webhooks[0]
WebhookInfo(
    id="654bbbc16f2ec14d77f109cc",
    watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
    url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
    secret="my-secret",
    domains=["repo", "discussion"],
    disabled=False,
)

Parameters:

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

list[WebhookInfo]

List of webhook info objects.

merge_pull_request[[huggingface_hub.HfApi.merge_pull_request]]

Source

Merges a Pull Request.

Raises the following errors:

- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  if some parameter value is invalid
- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

discussion_num (int) : The number of the Discussion or Pull Request . Must be a strictly positive integer.

comment (str, optional) : An optional comment to post with the status change.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[DiscussionStatusChange](/docs/huggingface_hub/pr_4113/ko/package_reference/community#huggingface_hub.DiscussionStatusChange)

the status change event

model_info[[huggingface_hub.HfApi.model_info]]

Source

Get info on one specific model on huggingface.co

Model can be private if you pass an acceptable token or are logged in.

Raises the following errors:

- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.
- [RevisionNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RevisionNotFoundError)
  If the revision to download from cannot be found.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

revision (str, optional) : The revision of the model repository from which to get the information.

timeout (float, optional) : Whether to set a timeout for the request to the Hub.

securityStatus (bool, optional) : Whether to retrieve the security status from the model repository as well. The security status will be returned in the security_repo_status field.

files_metadata (bool, optional) : Whether or not to retrieve metadata for files in the repository (size, LFS metadata, etc). Defaults to False.

expand (list[ExpandModelProperty_T], optional) : List properties to return in the response. When used, only the properties in the list will be returned. This parameter cannot be used if securityStatus or files_metadata are passed. Possible values are "author", "baseModels", "cardData", "childrenModelCount", "config", "createdAt", "disabled", "downloads", "downloadsAllTime", "evalResults", "gated", "gguf", "inference", "inferenceProviderMapping", "lastModified", "library_name", "likes", "mask_token", "model-index", "pipeline_tag", "private", "safetensors", "sha", "siblings", "spaces", "tags", "transformersInfo", "trendingScore", "widgetData", "usedStorage", and "resourceGroup".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[huggingface_hub.hf_api.ModelInfo](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.ModelInfo)

The model repository information.

move_bucket[[huggingface_hub.HfApi.move_bucket]]

Source

Move a bucket from "namespace1/repo_name1" to "namespace2/repo_name2"

Note there are certain limitations. For more information about moving repositories, please see https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.

Example:

>>> from huggingface_hub import move_bucket

>>> # Rename a bucket within the same namespace
>>> move_bucket(from_id="username/old-name", to_id="username/new-name")

>>> # Transfer a bucket to an organization
>>> move_bucket(from_id="username/my-bucket", to_id="my-org/my-bucket")

Parameters:

from_id (str) : A namespace (user or an organization) and a bucket name separated by a /. Original bucket identifier (e.g. "username/my-bucket").

to_id (str) : A namespace (user or an organization) and a bucket name separated by a /. Final bucket identifier (e.g. "username/new-bucket-name" or "organization/my-bucket").

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

move_repo[[huggingface_hub.HfApi.move_repo]]

Source

Moving a repository from namespace1/repo_name1 to namespace2/repo_name2

Note there are certain limitations. For more information about moving repositories, please see https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo.

Raises the following errors:

- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.

Parameters:

from_id (str) : A namespace (user or an organization) and a repo name separated by a /. Original repository identifier.

to_id (str) : A namespace (user or an organization) and a repo name separated by a /. Final repository identifier.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

paper_info[[huggingface_hub.HfApi.paper_info]]

Source

Get information for a paper on the Hub.

Parameters:

id (str, optional) : ArXiv id of the paper.

Returns:

PaperInfo

A PaperInfo object.

parse_safetensors_file_metadata[[huggingface_hub.HfApi.parse_safetensors_file_metadata]]

Source

Parse metadata from a safetensors file on the Hub.

To parse metadata from all safetensors files in a repo at once, use get_safetensors_metadata().

For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.

Parameters:

repo_id (str) : A user or an organization name and a repo name separated by a /.

filename (str) : The name of the file in the repo.

repo_type (str, optional) : Set to "dataset" or "space" if the file is in a dataset or space, None or "model" if in a model. Default is None.

revision (str, optional) : The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the head of the "main" branch.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

SafetensorsFileMetadata

information related to a safetensors file.

pause_inference_endpoint[[huggingface_hub.HfApi.pause_inference_endpoint]]

Source

Pause an Inference Endpoint.

A paused Inference Endpoint will not be charged. It can be resumed at any time using resume_inference_endpoint(). This is different than scaling the Inference Endpoint to zero with scale_to_zero_inference_endpoint(), which would be automatically restarted when a request is made to it.

For convenience, you can also pause an Inference Endpoint using pause_inference_endpoint().

Parameters:

name (str) : The name of the Inference Endpoint to pause.

namespace (str, optional) : The namespace in which the Inference Endpoint is located. Defaults to the current user.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[InferenceEndpoint](/docs/huggingface_hub/pr_4113/ko/package_reference/inference_endpoints#huggingface_hub.InferenceEndpoint)

information about the paused Inference Endpoint.

pause_space[[huggingface_hub.HfApi.pause_space]]

Source

Pause your Space.

A paused Space stops executing until manually restarted by its owner. This is different from the sleeping state in which free Spaces go after 48h of inactivity. Paused time is not billed to your account, no matter the hardware you've selected. To restart your Space, use restart_space() and go to your Space settings page.

For more details, please visit the docs.

Parameters:

repo_id (str) : ID of the Space to pause. Example: "Salesforce/BLIP2".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[SpaceRuntime](/docs/huggingface_hub/pr_4113/ko/package_reference/space_runtime#huggingface_hub.SpaceRuntime)

Runtime information about your Space including stage=PAUSED and requested hardware.

permanently_delete_lfs_files[[huggingface_hub.HfApi.permanently_delete_lfs_files]]

Source

Permanently delete LFS files from a repo on the Hub.

This is a permanent action that will affect all commits referencing the deleted files and might corrupt your repository. This is a non-revertible operation. Use it only if you know what you are doing.

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> lfs_files = api.list_lfs_files("username/my-cool-repo")

# Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
# e.g. select only LFS files in the "checkpoints" folder
>>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))

# Permanently delete LFS files
>>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)

Parameters:

repo_id (str) : The repository for which you are listing LFS files.

lfs_files (Iterable[LFSFileInfo]) : An iterable of LFSFileInfo items to permanently delete from the repo. Use list_lfs_files() to list all LFS files from a repo.

rewrite_history (bool, optional, default to True) : Whether to rewrite repository history to remove file pointers referencing the deleted LFS files (recommended).

repo_type (str, optional) : Type of repository. Set to "dataset" or "space" if listing from a dataset or space, None or "model" if listing from a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

preupload_lfs_files[[huggingface_hub.HfApi.preupload_lfs_files]]

Source

Pre-upload LFS files to S3 in preparation on a future commit.

This method is useful if you are generating the files to upload on-the-fly and you don't want to store them in memory before uploading them all at once.

This is a power-user method. You shouldn't need to call it directly to make a normal commit. Use create_commit() directly instead.

Commit operations will be mutated during the process. In particular, the attached path_or_fileobj will be removed after the upload to save memory (and replaced by an empty bytes object). Do not reuse the same objects except to pass them to create_commit(). If you don't want to remove the attached content from the commit operation object, pass free_memory=False.

Example:

>>> from huggingface_hub import CommitOperationAdd, preupload_lfs_files, create_commit, create_repo

>>> repo_id = create_repo("test_preupload").repo_id

# Generate and preupload LFS files one by one
>>> operations = [] # List of all `CommitOperationAdd` objects that will be generated
>>> for i in range(5):
...     content = ... # generate binary content
...     addition = CommitOperationAdd(path_in_repo=f"shard_{i}_of_5.bin", path_or_fileobj=content)
...     preupload_lfs_files(repo_id, additions=[addition]) # upload + free memory
...     operations.append(addition)

# Create commit
>>> create_commit(repo_id, operations=operations, commit_message="Commit all shards")

Parameters:

repo_id (str) : The repository in which you will commit the files, for example: "username/custom_transformers".

operations (Iterable of CommitOperationAdd) : The list of files to upload. Warning: the objects in this list will be mutated to include information relative to the upload. Do not reuse the same objects for multiple commits.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

repo_type (str, optional) : The type of repository to upload to (e.g. "model" -default-, "dataset" or "space").

revision (str, optional) : The git revision to commit from. Defaults to the head of the "main" branch.

create_pr (boolean, optional) : Whether or not you plan to create a Pull Request with that commit. Defaults to False.

num_threads (int, optional) : Number of concurrent threads for uploading files. Defaults to 5. Setting it to 2 means at most 2 files will be uploaded concurrently.

gitignore_content (str, optional) : The content of the .gitignore file to know which files should be ignored. The order of priority is to first check if gitignore_content is passed, then check if the .gitignore file is present in the list of files to commit and finally default to the .gitignore file already hosted on the Hub (if any).

read_paper[[huggingface_hub.HfApi.read_paper]]

Source

Get the markdown content of a paper page on the Hub.

Parameters:

id (str) : ArXiv id of the paper.

Returns:

str

The paper page content as markdown.

reject_access_request[[huggingface_hub.HfApi.reject_access_request]]

Source

Reject an access request from a user for a given gated repo.

A rejected request will go to the rejected list. The user cannot download any file of the repo. Rejected requests can be accepted or cancelled at any time using accept_access_request() and cancel_access_request(). A cancelled request will go back to the pending list while an accepted request will go to the accepted list.

For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.

Parameters:

repo_id (str) : The id of the repo to reject access request for.

user (str) : The username of the user which access request should be rejected.

repo_type (str, optional) : The type of the repo to reject access request for. Must be one of model, dataset or space. Defaults to model.

rejection_reason (str, optional) : Optional rejection reason that will be visible to the user (max 200 characters).

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

rename_discussion[[huggingface_hub.HfApi.rename_discussion]]

Source

Renames a Discussion.

Examples:

>>> new_title = "New title, fixing a typo"
>>> HfApi().rename_discussion(
...     repo_id="username/repo_name",
...     discussion_num=34
...     new_title=new_title
... )
# DiscussionTitleChange(id='deadbeef0000000', type='title-change', ...)

Raises the following errors:

- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  if some parameter value is invalid
- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

discussion_num (int) : The number of the Discussion or Pull Request . Must be a strictly positive integer.

new_title (str) : The new title for the discussion

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[DiscussionTitleChange](/docs/huggingface_hub/pr_4113/ko/package_reference/community#huggingface_hub.DiscussionTitleChange)

the title change event

repo_exists[[huggingface_hub.HfApi.repo_exists]]

Source

Checks if a repository exists on the Hugging Face Hub.

Examples:

>>> from huggingface_hub import repo_exists
>>> repo_exists("google/gemma-7b")
True
>>> repo_exists("google/not-a-repo")
False

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

repo_type (str, optional) : Set to "dataset" or "space" if getting repository info from a dataset or a space, None or "model" if getting repository info from a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

True if the repository exists, False otherwise.

repo_info[[huggingface_hub.HfApi.repo_info]]

Source

Get the info object for a given repo of a given type.

Raises the following errors:

- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.
- [RevisionNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RevisionNotFoundError)
  If the revision to download from cannot be found.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

revision (str, optional) : The revision of the repository from which to get the information.

repo_type (str, optional) : Set to "dataset" or "space" if getting repository info from a dataset or a space, None or "model" if getting repository info from a model. Default is None.

timeout (float, optional) : Whether to set a timeout for the request to the Hub.

expand (ExpandModelProperty_T or ExpandDatasetProperty_T or ExpandSpaceProperty_T, optional) : List properties to return in the response. When used, only the properties in the list will be returned. This parameter cannot be used if files_metadata is passed. For an exhaustive list of available properties, check out model_info(), dataset_info() or space_info().

files_metadata (bool, optional) : Whether or not to retrieve metadata for files in the repository (size, LFS metadata, etc). Defaults to False.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Union[SpaceInfo, DatasetInfo, ModelInfo]

The repository information, as a huggingface_hub.hf_api.DatasetInfo, huggingface_hub.hf_api.ModelInfo or huggingface_hub.hf_api.SpaceInfo object.

request_space_hardware[[huggingface_hub.HfApi.request_space_hardware]]

Source

Request new hardware for a Space.

It is also possible to request hardware directly when creating the Space repo! See create_repo() for details.

Parameters:

repo_id (str) : ID of the repo to update. Example: "bigcode/in-the-stack".

hardware (str or SpaceHardware) : Hardware on which to run the Space. Example: "t4-medium".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

sleep_time (int, optional) : Number of seconds of inactivity to wait before a Space is put to sleep. Set to -1 if you don't want your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure the sleep time (value is fixed to 48 hours of inactivity). See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.

Returns:

[SpaceRuntime](/docs/huggingface_hub/pr_4113/ko/package_reference/space_runtime#huggingface_hub.SpaceRuntime)

Runtime information about a Space including Space stage and hardware.

request_space_storage[[huggingface_hub.HfApi.request_space_storage]]

Source

Request persistent storage for a Space.

request_space_storage is deprecated and will be removed in version 2.0. Use set_space_volumes() instead.

Parameters:

repo_id (str) : ID of the Space to update. Example: "open-llm-leaderboard/open_llm_leaderboard".

storage (str or SpaceStorage) : Storage tier. Either 'small', 'medium', or 'large'.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[SpaceRuntime](/docs/huggingface_hub/pr_4113/ko/package_reference/space_runtime#huggingface_hub.SpaceRuntime)

Runtime information about a Space including Space stage and hardware.

restart_space[[huggingface_hub.HfApi.restart_space]]

Source

Restart your Space.

This is the only way to programmatically restart a Space if you've put it on Pause (see pause_space()). You must be the owner of the Space to restart it. If you are using an upgraded hardware, your account will be billed as soon as the Space is restarted. You can trigger a restart no matter the current state of a Space.

For more details, please visit the docs.

Parameters:

repo_id (str) : ID of the Space to restart. Example: "Salesforce/BLIP2".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

factory_reboot (bool, optional) : If True, the Space will be rebuilt from scratch without caching any requirements.

Returns:

[SpaceRuntime](/docs/huggingface_hub/pr_4113/ko/package_reference/space_runtime#huggingface_hub.SpaceRuntime)

Runtime information about your Space.

resume_inference_endpoint[[huggingface_hub.HfApi.resume_inference_endpoint]]

Source

Resume an Inference Endpoint.

For convenience, you can also resume an Inference Endpoint using InferenceEndpoint.resume().

Parameters:

name (str) : The name of the Inference Endpoint to resume.

namespace (str, optional) : The namespace in which the Inference Endpoint is located. Defaults to the current user.

running_ok (bool, optional) : If True, the method will not raise an error if the Inference Endpoint is already running. Defaults to True.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[InferenceEndpoint](/docs/huggingface_hub/pr_4113/ko/package_reference/inference_endpoints#huggingface_hub.InferenceEndpoint)

information about the resumed Inference Endpoint.

resume_scheduled_job[[huggingface_hub.HfApi.resume_scheduled_job]]

Source

Resume (unpause) a scheduled compute Job on Hugging Face infrastructure.

Parameters:

scheduled_job_id (str) : ID of the scheduled Job.

namespace (str, optional) : The namespace where the scheduled Job is. Defaults to the current user's namespace.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

revision_exists[[huggingface_hub.HfApi.revision_exists]]

Source

Checks if a specific revision exists on a repo on the Hugging Face Hub.

Examples:

>>> from huggingface_hub import revision_exists
>>> revision_exists("google/gemma-7b", "float16")
True
>>> revision_exists("google/gemma-7b", "not-a-revision")
False

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

revision (str) : The revision of the repository to check.

repo_type (str, optional) : Set to "dataset" or "space" if getting repository info from a dataset or a space, None or "model" if getting repository info from a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

True if the repository and the revision exists, False otherwise.

run_as_future[[huggingface_hub.HfApi.run_as_future]]

Source

Run a method in the background and return a Future instance.

The main goal is to run methods without blocking the main thread (e.g. to push data during a training). Background jobs are queued to preserve order but are not ran in parallel. If you need to speed-up your scripts by parallelizing lots of call to the API, you must setup and use your own ThreadPoolExecutor.

Note: Most-used methods like upload_file(), upload_folder() and create_commit() have a run_as_future: bool argument to directly call them in the background. This is equivalent to calling api.run_as_future(...) on them but less verbose.

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> future = api.run_as_future(api.whoami) # instant
>>> future.done()
False
>>> future.result() # wait until complete and return result
(...)
>>> future.done()
True

Parameters:

fn (Callable) : The method to run in the background.

  • *args, **kwargs : Arguments with which the method will be called.

Returns:

Future

a Future instance to get the result of the task.

run_job[[huggingface_hub.HfApi.run_job]]

Source

Run compute Jobs on Hugging Face infrastructure.

Example:

Run your first Job:

>>> from huggingface_hub import run_job
>>> run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])

Run a GPU Job:

>>> from huggingface_hub import run_job
>>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"
>>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"]
>>> run_job(image=image, command=command, flavor="a10g-small")

Run a Job with volumes:

>>> from huggingface_hub import Volume, run_job
>>> dataset_volume = Volume(type="dataset", source="HuggingFaceFW/fineweb", mount_path="/data")
>>> output_bucket_volume = Volume(type="bucket", source="username/my-bucket", mount_path="/output")
>>> image = "duckdb/duckdb"
>>> command = ["duckdb", "-c", "COPY (SELECT * FROM '/data/**/*.parquet' LIMIT 5) TO '/output/first-rows.parquet'"]
>>> run_job(image=image, command=command, volumes=[dataset_volume, output_bucket_volume])

Parameters:

image (str) : The Docker image to use. Examples: "ubuntu", "python:3.12", "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel". Example with an image from a Space: "hf.co/spaces/lhoestq/duckdb".

command (list[str]) : The command to run. Example: ["echo", "hello"].

env (dict[str, Any], optional) : Defines the environment variables for the Job.

secrets (dict[str, Any], optional) : Defines the secret environment variables for the Job.

flavor (str, optional) : Flavor for the hardware, as in Hugging Face Spaces. See SpaceHardware for possible values. Defaults to "cpu-basic".

timeout (Union[int, float, str], optional) : Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days). Example: 300 or "5m" for 5 minutes.

labels (dict[str, str], optional) : Labels to attach to the job (key-value pairs).

volumes (list[Volume], optional) : Hugging Face Buckets or Repos to mount as volumes in the job container. Each volume is a Volume with type ("bucket", "model", "dataset", or "space"), source (e.g. "username/my-bucket"), and mount_path (e.g. "/data").

namespace (str, optional) : The namespace where the Job will be created. Defaults to the current user's namespace.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

run_uv_job[[huggingface_hub.HfApi.run_uv_job]]

Source

Run a UV script Job on Hugging Face infrastructure.

Example:

Run a script from a URL:

>>> from huggingface_hub import run_uv_job
>>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
>>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
>>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small")

Run a local script:

>>> from huggingface_hub import run_uv_job
>>> script = "my_sft.py"
>>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
>>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small")

Run a command:

>>> from huggingface_hub import run_uv_job
>>> script = "lighteval"
>>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
>>> run_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small")

Mount volumes, e.g. to save model checkpoints during training:

>>> from huggingface_hub import Volume, run_uv_job
>>> script = "my_sft.py"
>>> script_args = ["--output_dir", "/training-outputs/training-v3-final", ...]
>>> checkpoints_bucket = Volume(type="bucket", source="username/my-bucket", mount_path="/training-outputs")
>>> run_uv_job(script, script_args=script_args, volumes=[checkpoints_bucket])

Parameters:

script (str) : Path or URL of the UV script, or a command.

script_args (list[str], optional) : Arguments to pass to the script or command.

dependencies (list[str], optional) : Dependencies to use to run the UV script.

python (str, optional) : Use a specific Python version. Default is 3.12.

image (str, optional, defaults to "ghcr.io/astral-sh/uv --python3.12-bookworm"): Use a custom Docker image with uv installed.

env (dict[str, Any], optional) : Defines the environment variables for the Job.

secrets (dict[str, Any], optional) : Defines the secret environment variables for the Job.

flavor (str, optional) : Flavor for the hardware, as in Hugging Face Spaces. See SpaceHardware for possible values. Defaults to "cpu-basic".

timeout (Union[int, float, str], optional) : Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days). Example: 300 or "5m" for 5 minutes.

labels (dict[str, str], optional) : Labels to attach to the job (key-value pairs).

volumes (list[Volume], optional) : Hugging Face Buckets or Repos to mount as volumes in the job container. Each volume is a Volume with type ("bucket", "model", "dataset", or "space"), source (e.g. "username/my-bucket"), and mount_path (e.g. "/data").

namespace (str, optional) : The namespace where the Job will be created. Defaults to the current user's namespace.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

scale_to_zero_inference_endpoint[[huggingface_hub.HfApi.scale_to_zero_inference_endpoint]]

Source

Scale Inference Endpoint to zero.

An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a cold start delay. This is different than pausing the Inference Endpoint with pause_inference_endpoint(), which would require a manual resume with resume_inference_endpoint().

For convenience, you can also scale an Inference Endpoint to zero using InferenceEndpoint.scale_to_zero().

Parameters:

name (str) : The name of the Inference Endpoint to scale to zero.

namespace (str, optional) : The namespace in which the Inference Endpoint is located. Defaults to the current user.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[InferenceEndpoint](/docs/huggingface_hub/pr_4113/ko/package_reference/inference_endpoints#huggingface_hub.InferenceEndpoint)

information about the scaled-to-zero Inference Endpoint.

search_spaces[[huggingface_hub.HfApi.search_spaces]]

Source

Search Spaces on the Hub using semantic search.

This endpoint uses semantic search (embedding-based) for multi-word queries and full-text search for single-word queries.

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> results = list(api.search_spaces("generate image"))
>>> results[0].id
'mrfakename/Z-Image-Turbo'
>>> results[0].ai_category
'Image Generation'

Parameters:

query (str) : The search query string.

filter (str or Iterable[str], optional) : A string tag or list of tags to filter by.

sdk (str or list[str], optional) : Filter by SDK (e.g. "gradio", "docker", "static").

include_non_running (bool, optional) : Whether to include non-running Spaces in results. Defaults to False.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

Iterable[SpaceSearchResult]

an iterable of SpaceSearchResult objects.

set_space_sleep_time[[huggingface_hub.HfApi.set_space_sleep_time]]

Source

Set a custom sleep time for a Space running on upgraded hardware..

Your Space will go to sleep after X seconds of inactivity. You are not billed when your Space is in "sleep" mode. If a new visitor lands on your Space, it will "wake it up". Only upgraded hardware can have a configurable sleep time. To know more about the sleep stage, please refer to https://huggingface.co/docs/hub/spaces-gpus#sleep-time.

It is also possible to set a custom sleep time when requesting hardware with request_space_hardware().

Parameters:

repo_id (str) : ID of the repo to update. Example: "bigcode/in-the-stack".

sleep_time (int, optional) : Number of seconds of inactivity to wait before a Space is put to sleep. Set to -1 if you don't want your Space to pause (default behavior for upgraded hardware). For free hardware, you can't configure the sleep time (value is fixed to 48 hours of inactivity). See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[SpaceRuntime](/docs/huggingface_hub/pr_4113/ko/package_reference/space_runtime#huggingface_hub.SpaceRuntime)

Runtime information about a Space including Space stage and hardware.

set_space_volumes[[huggingface_hub.HfApi.set_space_volumes]]

Source

Set volumes for a Space.

Sets (or replaces) the list of volumes mounted in the Space. Each volume gives the Space's container access to a Hub resource (model, dataset, or storage bucket).

Example:

>>> from huggingface_hub import HfApi, Volume
>>> api = HfApi()
>>> api.set_space_volumes(
...     "username/my-space",
...     volumes=[
...         Volume(type="model", source="username/my-model", mount_path="/models", read_only=True),
...         Volume(type="bucket", source="username/my-bucket", mount_path="/data"),
...     ],
... )

Parameters:

repo_id (str) : ID of the Space to update. Example: "username/my-space".

volumes (list[Volume]) : List of Volume objects to mount. Each volume has a type ("bucket", "model", "dataset", or "space"), a source (repo or bucket ID), a mount_path (path inside the container), and optional revision, read_only, and path fields.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

snapshot_download[[huggingface_hub.HfApi.snapshot_download]]

Source

Download repo files.

Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order to keep their actual filename relative to that folder. You can also filter which files to download using allow_patterns and ignore_patterns.

If local_dir is provided, the file structure from the repo will be replicated in this location. When using this option, the cache_dir will not be used and a .cache/huggingface/ folder will be created at the root of local_dir to store some metadata related to the downloaded files.While this mechanism is not as robust as the main cache-system, it's optimized for regularly pulling the latest version of a repository.

An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly configured. It is also not possible to filter which files to download when cloning a repository using git.

Parameters:

repo_id (str) : A user or an organization name and a repo name separated by a /.

repo_type (str, optional) : Set to "dataset" or "space" if downloading from a dataset or space, None or "model" if downloading from a model. Default is None.

revision (str, optional) : An optional Git revision id which can be a branch name, a tag, or a commit hash.

cache_dir (str, Path, optional) : Path to the folder where cached files are stored.

local_dir (str or Path, optional) : If provided, the downloaded files will be placed under this directory.

etag_timeout (float, optional, defaults to 10) : When fetching ETag, how many seconds to wait for the server to send data before giving up which is passed to httpx.request.

force_download (bool, optional, defaults to False) : Whether the file should be downloaded even if it already exists in the local cache.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

local_files_only (bool, optional, defaults to False) : If True, avoid downloading the file and return the path to the local cached file if it exists.

allow_patterns (list[str] or str, optional) : If provided, only files matching at least one pattern are downloaded.

ignore_patterns (list[str] or str, optional) : If provided, files matching any of the patterns are not downloaded.

max_workers (int, optional) : Number of concurrent threads to download files (1 thread = 1 file download). Defaults to 8.

tqdm_class (tqdm, optional) : If provided, overwrites the default behavior for the progress bar. Passed argument must inherit from tqdm.auto.tqdm or at least mimic its behavior. Note that the tqdm_class is not passed to each individual download. Defaults to the custom HF progress bar that can be disabled by setting HF_HUB_DISABLE_PROGRESS_BARS environment variable.

dry_run (bool, optional, defaults to False) : If True, perform a dry run without actually downloading the files. Returns a list of DryRunFileInfo objects containing information about what would be downloaded.

Returns:

str` or list of `DryRunFileInfo

  • If dry_run=False: Folder path of the repo snapshot.
  • If dry_run=True: A list of DryRunFileInfo objects containing download information.

space_info[[huggingface_hub.HfApi.space_info]]

Source

Get info on one specific Space on huggingface.co.

Space can be private if you pass an acceptable token.

Raises the following errors:

- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.
- [RevisionNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RevisionNotFoundError)
  If the revision to download from cannot be found.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

revision (str, optional) : The revision of the space repository from which to get the information.

timeout (float, optional) : Whether to set a timeout for the request to the Hub.

files_metadata (bool, optional) : Whether or not to retrieve metadata for files in the repository (size, LFS metadata, etc). Defaults to False.

expand (list[ExpandSpaceProperty_T], optional) : List properties to return in the response. When used, only the properties in the list will be returned. This parameter cannot be used if full is passed. Possible values are "author", "cardData", "createdAt", "datasets", "disabled", "lastModified", "likes", "models", "private", "runtime", "sdk", "siblings", "sha", "subdomain", "tags", "trendingScore", "usedStorage", and "resourceGroup".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[SpaceInfo](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.SpaceInfo)

The space repository information.

super_squash_history[[huggingface_hub.HfApi.super_squash_history]]

Source

Squash commit history on a branch for a repo on the Hub.

Squashing the repo history is useful when you know you'll make hundreds of commits and you don't want to clutter the history. Squashing commits can only be performed from the head of a branch.

Once squashed, the commit history cannot be retrieved. This is a non-revertible operation.

Once the history of a branch has been squashed, it is not possible to merge it back into another branch since their history will have diverged.

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()

# Create repo
>>> repo_id = api.create_repo("test-squash").repo_id

# Make a lot of commits.
>>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"content")
>>> api.upload_file(repo_id=repo_id, path_in_repo="lfs.bin", path_or_fileobj=b"content")
>>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"another_content")

# Squash history
>>> api.super_squash_history(repo_id=repo_id)

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

branch (str, optional) : The branch to squash. Defaults to the head of the "main" branch.

commit_message (str, optional) : The commit message to use for the squashed commit.

repo_type (str, optional) : Set to "dataset" or "space" if listing commits from a dataset or a Space, None or "model" if listing from a model. Default is None.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

suspend_scheduled_job[[huggingface_hub.HfApi.suspend_scheduled_job]]

Source

Suspend (pause) a scheduled compute Job on Hugging Face infrastructure.

Parameters:

scheduled_job_id (str) : ID of the scheduled Job.

namespace (str, optional) : The namespace where the scheduled Job is. Defaults to the current user's namespace.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set to False to disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.

sync_bucket[[huggingface_hub.HfApi.sync_bucket]]

Source

Sync files between a local directory and a bucket.

This is equivalent to the hf buckets sync CLI command. One of source or dest must be a bucket path (hf://buckets/...) and the other must be a local directory path.

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()

# Upload local directory to bucket
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket")

# Download bucket to local directory
>>> api.sync_bucket("hf://buckets/username/my-bucket", "./data")

# Sync with delete and filtering
>>> api.sync_bucket(
...     "./data",
...     "hf://buckets/username/my-bucket",
...     delete=True,
...     include=["*.safetensors"],
... )

# Dry run: preview what would be synced
>>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True)
>>> plan.summary()
{'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}

# Save plan for review, then apply
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl")
>>> api.sync_bucket(apply="sync-plan.jsonl")

Parameters:

source (str, optional) : Source path: local directory or hf://buckets/namespace/bucket_name(/prefix). Required unless using apply.

dest (str, optional) : Destination path: local directory or hf://buckets/namespace/bucket_name(/prefix). Required unless using apply.

delete (bool, optional, defaults to False) : Delete destination files not present in source.

ignore_times (bool, optional, defaults to False) : Skip files only based on size, ignoring modification times.

ignore_sizes (bool, optional, defaults to False) : Skip files only based on modification times, ignoring sizes.

existing (bool, optional, defaults to False) : Skip creating new files on receiver (only update existing files).

ignore_existing (bool, optional, defaults to False) : Skip updating files that exist on receiver (only create new files).

include (list[str], optional) : Include files matching patterns (fnmatch-style).

exclude (list[str], optional) : Exclude files matching patterns (fnmatch-style).

filter_from (str, optional) : Path to a filter file with include/exclude rules.

plan (str, optional) : Save sync plan to this JSONL file instead of executing.

apply (str, optional) : Apply a previously saved plan file. When set, source and dest are not needed.

dry_run (bool, optional, defaults to False) : Print sync plan to stdout as JSONL without executing.

verbose (bool, optional, defaults to False) : Show detailed per-file operations.

quiet (bool, optional, defaults to False) : Suppress all output and progress bars.

token (Union[bool, str, None], optional) : A valid user access token. If not provided, the locally saved token will be used.

Returns:

[*SyncPlan*]

The computed (or loaded) sync plan.

unlike[[huggingface_hub.HfApi.unlike]]

Source

Unlike a given repo on the Hub (e.g. remove from favorite list).

To prevent spam usage, it is not possible to like a repository from a script.

See also list_liked_repos().

Example:

>>> from huggingface_hub import list_liked_repos, unlike
>>> "gpt2" in list_liked_repos().models # we assume you have already liked gpt2
True
>>> unlike("gpt2")
>>> "gpt2" in list_liked_repos().models
False

Parameters:

repo_id (str) : The repository to unlike. Example: "user/my-cool-model".

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

repo_type (str, optional) : Set to "dataset" or "space" if unliking a dataset or space, None or "model" if unliking a model. Default is None.

update_collection_item[[huggingface_hub.HfApi.update_collection_item]]

Source

Update an item in a collection.

Example:

>>> from huggingface_hub import get_collection, update_collection_item

# Get collection first
>>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")

# Update item based on its ID (add note + update position)
>>> update_collection_item(
...     collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
...     item_object_id=collection.items[-1].item_object_id,
...     note="Newly updated model!"
...     position=0,
... )

Parameters:

collection_slug (str) : Slug of the collection to update. Example: "TheBloke/recent-models-64f9a55bb3115b4f513ec026".

item_object_id (str) : ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id). It must be retrieved from a CollectionItem object. Example: collection.items[0].item_object_id.

note (str, optional) : A note to attach to the item in the collection. The maximum size for a note is 500 characters.

position (int, optional) : New position of the item in the collection.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

update_collection_metadata[[huggingface_hub.HfApi.update_collection_metadata]]

Source

Update metadata of a collection on the Hub.

All arguments are optional. Only provided metadata will be updated.

Returns: Collection

Example:

>>> from huggingface_hub import update_collection_metadata
>>> collection = update_collection_metadata(
...     collection_slug="username/iccv-2023-64f9a55bb3115b4f513ec026",
...     title="ICCV Oct. 2023"
...     description="Portfolio of models, datasets, papers and demos I presented at ICCV Oct. 2023",
...     private=False,
...     theme="pink",
... )
>>> collection.slug
"username/iccv-oct-2023-64f9a55bb3115b4f513ec026"
# ^collection slug got updated but not the trailing ID

Parameters:

collection_slug (str) : Slug of the collection to update. Example: "TheBloke/recent-models-64f9a55bb3115b4f513ec026".

title (str) : Title of the collection to update.

description (str, optional) : Description of the collection to update.

position (int, optional) : New position of the collection in the list of collections of the user.

private (bool, optional) : Whether the collection should be private or not.

theme (str, optional) : Theme of the collection on the Hub.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

update_inference_endpoint[[huggingface_hub.HfApi.update_inference_endpoint]]

Source

Update an Inference Endpoint.

This method allows the update of either the compute configuration, the deployed model, the route, or any combination. All arguments are optional but at least one must be provided.

For convenience, you can also update an Inference Endpoint using InferenceEndpoint.update().

Parameters:

name (str) : The name of the Inference Endpoint to update.

accelerator (str, optional) : The hardware accelerator to be used for inference (e.g. "cpu").

instance_size (str, optional) : The size or type of the instance to be used for hosting the model (e.g. "x4").

instance_type (str, optional) : The cloud instance type where the Inference Endpoint will be deployed (e.g. "intel-icl").

min_replica (int, optional) : The minimum number of replicas (instances) to keep running for the Inference Endpoint.

max_replica (int, optional) : The maximum number of replicas (instances) to scale to for the Inference Endpoint.

scale_to_zero_timeout (int, optional) : The duration in minutes before an inactive endpoint is scaled to zero.

scaling_metric (str or InferenceEndpointScalingMetric , optional) : The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided. Defaults to None.

scaling_threshold (float, optional) : The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided. Defaults to None.

repository (str, optional) : The name of the model repository associated with the Inference Endpoint (e.g. "gpt2").

framework (str, optional) : The machine learning framework used for the model (e.g. "custom").

revision (str, optional) : The specific model revision to deploy on the Inference Endpoint (e.g. "6c0e6080953db56375760c0471a8c5f2929baf11").

task (str, optional) : The task on which to deploy the model (e.g. "text-classification").

custom_image (dict, optional) : A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an Inference Endpoint running on the text-generation-inference (TGI) framework (see examples).

env (dict[str, str], optional) : Non-secret environment variables to inject in the container environment

secrets (dict[str, str], optional) : Secret values to inject in the container environment.

domain (str, optional) : The custom domain for the Inference Endpoint deployment, if setup the inference endpoint will be available at this domain (e.g. "my-new-domain.cool-website.woof").

path (str, optional) : The custom path to the deployed model, should start with a / (e.g. "/models/google-bert/bert-base-uncased").

cache_http_responses (bool, optional) : Whether to cache HTTP responses from the Inference Endpoint.

tags (list[str], optional) : A list of tags to associate with the Inference Endpoint.

namespace (str, optional) : The namespace where the Inference Endpoint will be updated. Defaults to the current user's namespace.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

[InferenceEndpoint](/docs/huggingface_hub/pr_4113/ko/package_reference/inference_endpoints#huggingface_hub.InferenceEndpoint)

information about the updated Inference Endpoint.

update_repo_settings[[huggingface_hub.HfApi.update_repo_settings]]

Source

Update the settings of a repository, including gated access and visibility.

To give more control over how repos are used, the Hub allows repo authors to enable access requests for their repos, and also to change the visibility of the repo.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

gated (Literal["auto", "manual", False], optional) : The gated status for the repository. If set to None (default), the gated setting of the repository won't be updated. * "auto": The repository is gated, and access requests are automatically approved or denied based on predefined criteria. * "manual": The repository is gated, and access requests require manual approval. * False : The repository is not gated, and anyone can access it.

private (bool, optional) : Whether the repository should be private. Cannot be passed together with visibility.

visibility (Literal["public", "private", "protected"], optional) : Visibility of the repository. Can be "public" or "private", or "protected" for Spaces.

token (Union[str, bool, None], optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

repo_type (str, optional) : The type of the repository to update settings from ("model", "dataset" or "space"). Defaults to "model".

update_webhook[[huggingface_hub.HfApi.update_webhook]]

Source

Update an existing webhook.

Example:

>>> from huggingface_hub import update_webhook
>>> updated_payload = update_webhook(
...     webhook_id="654bbbc16f2ec14d77f109cc",
...     url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
...     watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
...     domains=["repo"],
...     secret="my-secret",
... )
>>> print(updated_payload)
WebhookInfo(
    id="654bbbc16f2ec14d77f109cc",
    job=None,
    url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
    watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
    domains=["repo"],
    secret="my-secret",
    disabled=False,

Parameters:

webhook_id (str) : The unique identifier of the webhook to be updated.

url (str, optional) : The URL to which the payload will be sent.

watched (list[WebhookWatchedItem], optional) : List of items to watch. It can be users, orgs, models, datasets, or spaces. Refer to WebhookWatchedItem for more details. Watched items can also be provided as plain dictionaries.

domains (list[Literal["repo", "discussion"]], optional) : The domains to watch. This can include "repo", "discussion", or both.

secret (str, optional) : A secret to sign the payload with, providing an additional layer of security.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

WebhookInfo

Info about the updated webhook.

upload_file[[huggingface_hub.HfApi.upload_file]]

Source

Upload a local file (up to 50 GB) to the given repo. The upload is done through a HTTP post request, and doesn't require git or git-lfs to be installed.

Raises the following errors:

- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
  if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  if some parameter value is invalid
- [RepositoryNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError)
  If the repository to download from cannot be found. This may be because it doesn't exist,
  or because it is set to `private` and you do not have access.
- [RevisionNotFoundError](/docs/huggingface_hub/pr_4113/ko/package_reference/utilities#huggingface_hub.errors.RevisionNotFoundError)
  If the revision to download from cannot be found.

upload_file assumes that the repo already exists on the Hub. If you get a Client error 404, please make sure you are authenticated, that your token has the required permissions, and that repo_id and repo_type are set correctly. If repo does not exist, create it first using create_repo().

Example:

>>> from huggingface_hub import upload_file

>>> with open("./local/filepath", "rb") as fobj:
...     upload_file(
...         path_or_fileobj=fileobj,
...         path_in_repo="remote/file/path.h5",
...         repo_id="username/my-dataset",
...         repo_type="dataset",
...         token="my_token",
...     )

>>> upload_file(
...     path_or_fileobj=".\\local\\file\\path",
...     path_in_repo="remote/file/path.h5",
...     repo_id="username/my-model",
...     token="my_token",
... )

>>> upload_file(
...     path_or_fileobj=".\\local\\file\\path",
...     path_in_repo="remote/file/path.h5",
...     repo_id="username/my-model",
...     token="my_token",
...     create_pr=True,
... )

Parameters:

path_or_fileobj (str, Path, bytes, or IO) : Path to a file on the local machine or binary data stream / fileobj / buffer.

path_in_repo (str) : Relative filepath in the repo, for example: "checkpoints/1fec34a/weights.bin"

repo_id (str) : The repository to which the file will be uploaded, for example: "username/custom_transformers"

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

revision (str, optional) : The git revision to commit from. Defaults to the head of the "main" branch.

commit_message (str, optional) : The summary / title / first line of the generated commit

commit_description (str optional) : The description of the generated commit

create_pr (boolean, optional) : Whether or not to create a Pull Request with that commit. Defaults to False. If revision is not set, PR is opened against the "main" branch. If revision is set and is a branch, PR is opened against this branch. If revision is set and is not a branch name (example: a commit oid), an RevisionNotFoundError is returned by the server.

parent_commit (str, optional) : The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. If specified and create_pr is False, the commit will fail if revision does not point to parent_commit. If specified and create_pr is True, the pull request will be created from parent_commit. Specifying parent_commit ensures the repo has not changed before committing the changes, and can be especially useful if the repo is updated / committed to concurrently.

run_as_future (bool, optional) : Whether or not to run this method in the background. Background jobs are run sequentially without blocking the main thread. Passing run_as_future=True will return a Future object. Defaults to False.

Returns:

[CommitInfo](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.CommitInfo) or Future``

Instance of CommitInfo containing information about the newly created commit (commit hash, commit url, pr url, commit message,...). If run_as_future=True is passed, returns a Future object which will contain the result when executed.

upload_folder[[huggingface_hub.HfApi.upload_folder]]

Source

Upload a local folder to the given repo. The upload is done through a HTTP requests, and doesn't require git or git-lfs to be installed.

The structure of the folder will be preserved. Files with the same name already present in the repository will be overwritten. Others will be left untouched.

Use the allow_patterns and ignore_patterns arguments to specify which files to upload. These parameters accept either a single pattern or a list of patterns. Patterns are Standard Wildcards (globbing patterns) as documented here. If both allow_patterns and ignore_patterns are provided, both constraints apply. By default, all files from the folder are uploaded.

Use the delete_patterns argument to specify remote files you want to delete. Input type is the same as for allow_patterns (see above). If path_in_repo is also provided, the patterns are matched against paths relative to this folder. For example, upload_folder(..., path_in_repo="experiment", delete_patterns="logs/*") will delete any remote file under ./experiment/logs/. Note that the .gitattributes file will not be deleted even if it matches the patterns.

Any .git/ folder present in any subdirectory will be ignored. However, please be aware that the .gitignore file is not taken into account.

Uses HfApi.create_commit under the hood.

Raises the following errors:

- [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
if the HuggingFace API returned an error
- [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
if some parameter value is invalid

upload_folder assumes that the repo already exists on the Hub. If you get a Client error 404, please make sure you are authenticated, that your token has the required permissions, and that repo_id and repo_type are set correctly. If repo does not exist, create it first using create_repo().

When dealing with a large folder (thousands of files or hundreds of GB), we recommend using upload_large_folder() instead.

Example:

# Upload checkpoints folder except the log files
>>> upload_folder(
...     folder_path="local/checkpoints",
...     path_in_repo="remote/experiment/checkpoints",
...     repo_id="username/my-dataset",
...     repo_type="datasets",
...     token="my_token",
...     ignore_patterns="**/logs/*.txt",
... )

# Upload checkpoints folder including logs while deleting existing logs from the repo
# Useful if you don't know exactly which log files have already being pushed
>>> upload_folder(
...     folder_path="local/checkpoints",
...     path_in_repo="remote/experiment/checkpoints",
...     repo_id="username/my-dataset",
...     repo_type="datasets",
...     token="my_token",
...     delete_patterns="**/logs/*.txt",
... )

# Upload checkpoints folder while creating a PR
>>> upload_folder(
...     folder_path="local/checkpoints",
...     path_in_repo="remote/experiment/checkpoints",
...     repo_id="username/my-dataset",
...     repo_type="datasets",
...     token="my_token",
...     create_pr=True,
... )

Parameters:

repo_id (str) : The repository to which the file will be uploaded, for example: "username/custom_transformers"

folder_path (str or Path) : Path to the folder to upload on the local file system

path_in_repo (str, optional) : Relative path of the directory in the repo, for example: "checkpoints/1fec34a/results". Will default to the root folder of the repository.

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

repo_type (str, optional) : Set to "dataset" or "space" if uploading to a dataset or space, None or "model" if uploading to a model. Default is None.

revision (str, optional) : The git revision to commit from. Defaults to the head of the "main" branch.

commit_message (str, optional) : The summary / title / first line of the generated commit. Defaults to: f"Upload {path_in_repo} with huggingface_hub"

commit_description (str optional) : The description of the generated commit

create_pr (boolean, optional) : Whether or not to create a Pull Request with that commit. Defaults to False. If revision is not set, PR is opened against the "main" branch. If revision is set and is a branch, PR is opened against this branch. If revision is set and is not a branch name (example: a commit oid), an RevisionNotFoundError is returned by the server.

parent_commit (str, optional) : The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. If specified and create_pr is False, the commit will fail if revision does not point to parent_commit. If specified and create_pr is True, the pull request will be created from parent_commit. Specifying parent_commit ensures the repo has not changed before committing the changes, and can be especially useful if the repo is updated / committed to concurrently.

allow_patterns (list[str] or str, optional) : If provided, only files matching at least one pattern are uploaded.

ignore_patterns (list[str] or str, optional) : If provided, files matching any of the patterns are not uploaded.

delete_patterns (list[str] or str, optional) : If provided, remote files matching any of the patterns will be deleted from the repo while committing new files. This is useful if you don't know which files have already been uploaded. Note: to avoid discrepancies the .gitattributes file is not deleted even if it matches the pattern.

run_as_future (bool, optional) : Whether or not to run this method in the background. Background jobs are run sequentially without blocking the main thread. Passing run_as_future=True will return a Future object. Defaults to False.

Returns:

[CommitInfo](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.CommitInfo) or Future``

Instance of CommitInfo containing information about the newly created commit (commit hash, commit url, pr url, commit message,...). If run_as_future=True is passed, returns a Future object which will contain the result when executed.

upload_large_folder[[huggingface_hub.HfApi.upload_large_folder]]

Source

Upload a large folder to the Hub in the most resilient way possible.

Several workers are started to upload files in an optimized way. Before being committed to a repo, files must be hashed and be pre-uploaded if they are LFS files. Workers will perform these tasks for each file in the folder. At each step, some metadata information about the upload process is saved in the folder under .cache/.huggingface/ to be able to resume the process if interrupted. The whole process might result in several commits.

A few things to keep in mind: - Repository limits still apply: https://huggingface.co/docs/hub/repositories-recommendations - Do not start several processes in parallel. - You can interrupt and resume the process at any time. - Do not upload the same folder to several repositories. If you need to do so, you must delete the local .cache/.huggingface/ folder first.

While being much more robust to upload large folders, upload_large_folder is more limited than upload_folder() feature-wise. In practice: - you cannot set a custom path_in_repo. If you want to upload to a subfolder, you need to set the proper structure locally. - you cannot set a custom commit_message and commit_description since multiple commits are created. - you cannot delete from the repo while uploading. Please make a separate commit first. - you cannot create a PR directly. Please create a PR first (from the UI or using create_pull_request()) and then commit to it by passing revision.

Technical details:

upload_large_folder process is as follow:

  1. (Check parameters and setup.)
  2. Create repo if missing.
  3. List local files to upload.
  4. Run validation checks and display warnings if repository limits might be exceeded:
    • Warns if the total number of files exceeds 100k (recommended limit).
    • Warns if any folder contains more than 10k files (recommended limit).
    • Warns about files larger than 20GB (recommended) or 50GB (hard limit).
  5. Start workers. Workers can perform the following tasks:
    • Hash a file.
    • Get upload mode (regular or LFS) for a list of files.
    • Pre-upload an LFS file.
    • Commit a bunch of files. Once a worker finishes a task, it will move on to the next task based on the priority list (see below) until all files are uploaded and committed.
  6. While workers are up, regularly print a report to sys.stdout.

Order of priority:

  1. Commit if more than 5 minutes since last commit attempt (and at least 1 file).
  2. Commit if at least 150 files are ready to commit.
  3. Get upload mode if at least 10 files have been hashed.
  4. Pre-upload LFS file if at least 1 file and no worker is pre-uploading.
  5. Hash file if at least 1 file and no worker is hashing.
  6. Get upload mode if at least 1 file and no worker is getting upload mode.
  7. Pre-upload LFS file if at least 1 file.
  8. Hash file if at least 1 file to hash.
  9. Get upload mode if at least 1 file to get upload mode.
  10. Commit if at least 1 file to commit and at least 1 min since last commit attempt.
  11. Commit if at least 1 file to commit and all other queues are empty.

Special rules:

  • Only one worker can commit at a time.
  • If no tasks are available, the worker waits for 10 seconds before checking again.

Parameters:

repo_id (str) : The repository to which the file will be uploaded. E.g. "HuggingFaceTB/smollm-corpus".

folder_path (str or Path) : Path to the folder to upload on the local file system.

repo_type (str) : Type of the repository. Must be one of "model", "dataset" or "space". Unlike in all other HfApi methods, repo_type is explicitly required here. This is to avoid any mistake when uploading a large folder to the Hub, and therefore prevent from having to re-upload everything.

revision (str, optional) : The branch to commit to. If not provided, the main branch will be used.

private (bool, optional) : Whether the repository should be private. If None (default), the repo will be public unless the organization's default is private.

allow_patterns (list[str] or str, optional) : If provided, only files matching at least one pattern are uploaded.

ignore_patterns (list[str] or str, optional) : If provided, files matching any of the patterns are not uploaded.

num_workers (int, optional) : Number of workers to start. Defaults to half of CPU cores (minimum 1). A higher number of workers may speed up the process if your machine allows it. However, on machines with a slower connection, it is recommended to keep the number of workers low to ensure better resumability. Indeed, partially uploaded files will have to be completely re-uploaded if the process is interrupted.

print_report (bool, optional) : Whether to print a report of the upload progress. Defaults to True. Report is printed to sys.stdout every X seconds (60 by defaults) and overwrites the previous report.

print_report_every (int, optional) : Frequency at which the report is printed. Defaults to 60 seconds.

verify_repo_checksums[[huggingface_hub.HfApi.verify_repo_checksums]]

Source

Verify local files for a repo against Hub checksums.

Parameters:

repo_id (str) : A namespace (user or an organization) and a repo name separated by a /.

repo_type (str, optional) : The type of the repository from which to get the tree ("model", "dataset" or "space". Defaults to "model".

revision (str, optional) : The revision of the repository from which to get the tree. Defaults to "main" branch.

local_dir (str or Path, optional) : The local directory to verify.

cache_dir (str or Path, optional) : The cache directory to verify.

token (Union[bool, str, None], optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

Returns:

FolderVerification

a structured result containing the verification details.

whoami[[huggingface_hub.HfApi.whoami]]

Source

Call HF API to know "whoami".

If passing cache=True, the result will be cached for subsequent calls for the duration of the Python process. This is useful if you plan to call whoami multiple times as this endpoint is heavily rate-limited for security reasons.

Parameters:

token (bool or str, optional) : A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, pass False.

cache (bool, optional) : Whether to cache the result of the whoami call for subsequent calls. If an error occurs during the first call, it won't be cached. Defaults to False.

API Dataclasses[[api-dataclasses]]

AccessRequest[[huggingface_hub.hf_api.AccessRequest]][[huggingface_hub.hf_api.AccessRequest]]

huggingface_hub.hf_api.AccessRequest[[huggingface_hub.hf_api.AccessRequest]]

Source

Data structure containing information about a user access request.

Parameters:

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.

CommitInfo[[huggingface_hub.CommitInfo]][[huggingface_hub.CommitInfo]]

huggingface_hub.CommitInfo[[huggingface_hub.CommitInfo]]

Source

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.

Parameters:

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.

DatasetInfo[[huggingface_hub.hf_api.DatasetInfo]][[huggingface_hub.DatasetInfo]]

huggingface_hub.DatasetInfo[[huggingface_hub.DatasetInfo]]

Source

Contains information about a dataset on the Hub. This object is returned by dataset_info() and list_datasets().

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.

Parameters:

id (str) : ID of dataset.

author (str) : Author of the dataset.

card_data (DatasetCardData, optional) : Dataset Card Metadata as a huggingface_hub.repocard_data.DatasetCardData object.

citation (str, optional) : Citation information for the dataset.

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.

description (str, optional) : Description of the dataset.

disabled (bool, optional) : Is the repo disabled.

downloads (int) : Number of downloads of the dataset over the last 30 days.

downloads_all_time (int) : Cumulated number of downloads of the dataset since its creation.

gated (Literal["auto", "manual", False], optional) : Is the repo gated. If so, whether there is manual or automatic approval.

last_modified (datetime, optional) : Date of last commit to the repo.

likes (int) : Number of likes of the dataset.

paperswithcode_id (str, optional) : Papers with code ID of the dataset.

private (bool) : Is the repo private.

resource_group (dict, optional) : Resource group information for the dataset.

sha (str) : Repo SHA at this particular revision.

siblings (list[RepoSibling]) : List of huggingface_hub.hf_api.RepoSibling objects that constitute the dataset.

tags (list[str]) : List of tags of the dataset.

trending_score (int, optional) : Trending score of the dataset.

used_storage (int, optional) : Size in bytes of the dataset on the Hub.

GitRefInfo[[huggingface_hub.GitRefInfo]][[huggingface_hub.GitRefInfo]]

huggingface_hub.GitRefInfo[[huggingface_hub.GitRefInfo]]

Source

Contains information about a git reference for a repo on the Hub.

Parameters:

name (str) : Name of the reference (e.g. tag name or branch name).

ref (str) : Full git ref on the Hub (e.g. "refs/heads/main" or "refs/tags/v1.0").

target_commit (str) : OID of the target commit for the ref (e.g. "e7da7f221d5bf496a48136c0cd264e630fe9fcc8")

GitCommitInfo[[huggingface_hub.GitCommitInfo]][[huggingface_hub.GitCommitInfo]]

huggingface_hub.GitCommitInfo[[huggingface_hub.GitCommitInfo]]

Source

Contains information about a git commit for a repo on the Hub. Check out list_repo_commits() for more details.

Parameters:

commit_id (str) : OID of the commit (e.g. "e7da7f221d5bf496a48136c0cd264e630fe9fcc8")

authors (list[str]) : List of authors of the commit.

created_at (datetime) : Datetime when the commit was created.

title (str) : Title of the commit. This is a free-text value entered by the authors.

message (str) : Description of the commit. This is a free-text value entered by the authors.

formatted_title (str) : Title of the commit formatted as HTML. Only returned if formatted=True is set.

formatted_message (str) : Description of the commit formatted as HTML. Only returned if formatted=True is set.

GitRefs[[huggingface_hub.GitRefs]][[huggingface_hub.GitRefs]]

huggingface_hub.GitRefs[[huggingface_hub.GitRefs]]

Source

Contains information about all git references for a repo on the Hub.

Object is returned by list_repo_refs().

Parameters:

branches (list[GitRefInfo]) : A list of GitRefInfo containing information about branches on the repo.

converts (list[GitRefInfo]) : A list of GitRefInfo containing information about "convert" refs on the repo. Converts are refs used (internally) to push preprocessed data in Dataset repos.

tags (list[GitRefInfo]) : A list of GitRefInfo containing information about tags on the repo.

pull_requests (list[GitRefInfo], optional) : A list of GitRefInfo containing information about pull requests on the repo. Only returned if include_prs=True is set.

ModelInfo[[huggingface_hub.hf_api.ModelInfo]][[huggingface_hub.ModelInfo]]

huggingface_hub.ModelInfo[[huggingface_hub.ModelInfo]]

Source

Contains information about a model on the Hub. This object is returned by model_info() and list_models().

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.

Parameters:

id (str) : ID of model.

author (str, optional) : Author of the model.

base_models (list[str], optional) : List of base models this model is derived from.

card_data (ModelCardData, optional) : Model Card Metadata as a huggingface_hub.repocard_data.ModelCardData object.

children_model_count (int, optional) : Number of children models derived from this model.

config (dict, optional) : Model configuration.

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.

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.

eval_results (list[EvalResultEntry], optional) : Model's evaluation results.

gated (Literal["auto", "manual", False], optional) : Is the repo gated. If so, whether there is manual or automatic approval.

gguf (dict, optional) : GGUF information of the model.

inference (Literal["warm"], optional) : Status of the model on Inference Providers. Warm if the model is served by at least one provider.

inference_provider_mapping (list[InferenceProviderMapping], optional) : A list of InferenceProviderMapping ordered after the user's provider order.

last_modified (datetime, optional) : Date of last commit to the repo.

library_name (str, optional) : Library associated with the model.

likes (int) : Number of likes of the model.

mask_token (str, optional) : Mask token used by the model.

model_index (dict, optional) : Model index for evaluation.

pipeline_tag (str, optional) : Pipeline tag associated with the model.

private (bool) : Is the repo private.

resource_group (dict, optional) : Resource group information for the model.

safetensors (SafeTensorsInfo, optional) : Model's safetensors information.

security_repo_status (dict, optional) : Model's security scan status.

sha (str, optional) : Repo SHA at this particular revision.

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.

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).

transformers_info (TransformersInfo, optional) : Transformers-specific info (auto class, processor, etc.) associated with the model.

trending_score (int, optional) : Trending score of the model.

used_storage (int, optional) : Size in bytes of the model on the Hub.

widget_data (Any, optional) : Widget data associated with the model.

RepoSibling[[huggingface_hub.hf_api.RepoSibling]][[huggingface_hub.hf_api.RepoSibling]]

huggingface_hub.hf_api.RepoSibling[[huggingface_hub.hf_api.RepoSibling]]

Source

Contains basic information about a repo file inside a repo on the Hub.

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.

Parameters:

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 whenfiles_metadata argument of repo_info() is set to True and the file is stored with Git LFS. It's None otherwise.

RepoFile[[huggingface_hub.hf_api.RepoFile]][[huggingface_hub.RepoFile]]

huggingface_hub.RepoFile[[huggingface_hub.RepoFile]]

Source

Contains information about a file on the Hub.

Parameters:

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, optional) : The file's LFS metadata.

xet_hash (str, optional) : The file's Xet hash.

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.

RepoUrl[[huggingface_hub.RepoUrl]][[huggingface_hub.RepoUrl]]

huggingface_hub.RepoUrl[[huggingface_hub.RepoUrl]]

Source

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)

Example:

>>> 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')

Parameters:

url (Any) : String value of the repo url.

endpoint (str, optional) : Endpoint of the Hub. Defaults to .

SafetensorsRepoMetadata[[huggingface_hub.utils.SafetensorsRepoMetadata]][[huggingface_hub.utils.SafetensorsRepoMetadata]]

huggingface_hub.utils.SafetensorsRepoMetadata[[huggingface_hub.utils.SafetensorsRepoMetadata]]

Source

Metadata for a Safetensors repo.

A repo is considered to be a Safetensors repo if it contains either a 'model.safetensors' weight file (non-shared model) or a 'model.safetensors.index.json' index file (sharded model) at its root.

This class is returned by get_safetensors_metadata().

For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.

Parameters:

metadata (dict, optional) : The metadata contained in the 'model.safetensors.index.json' file, if it exists. Only populated for sharded models.

sharded (bool) : Whether the repo contains a sharded model or not.

weight_map (dict[str, str]) : A map of all weights. Keys are tensor names and values are filenames of the files containing the tensors.

files_metadata (dict[str, SafetensorsFileMetadata]) : A map of all files metadata. Keys are filenames and values are the metadata of the corresponding file, as a SafetensorsFileMetadata object.

parameter_count (dict[str, int]) : A map of the number of parameters per data type. Keys are data types and values are the number of parameters of that data type.

SafetensorsFileMetadata[[huggingface_hub.utils.SafetensorsFileMetadata]][[huggingface_hub.utils.SafetensorsFileMetadata]]

huggingface_hub.utils.SafetensorsFileMetadata[[huggingface_hub.utils.SafetensorsFileMetadata]]

Source

Metadata for a Safetensors file hosted on the Hub.

This class is returned by parse_safetensors_file_metadata().

For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.

Parameters:

metadata (dict) : The metadata contained in the file.

tensors (dict[str, TensorInfo]) : A map of all tensors. Keys are tensor names and values are information about the corresponding tensor, as a TensorInfo object.

parameter_count (dict[str, int]) : A map of the number of parameters per data type. Keys are data types and values are the number of parameters of that data type.

SpaceInfo[[huggingface_hub.hf_api.SpaceInfo]][[huggingface_hub.SpaceInfo]]

huggingface_hub.SpaceInfo[[huggingface_hub.SpaceInfo]]

Source

Contains information about a Space on the Hub. This object is returned by space_info() and list_spaces().

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.

Parameters:

id (str) : ID of the Space.

author (str, optional) : Author of the Space.

card_data (SpaceCardData, optional) : Space Card Metadata as a huggingface_hub.repocard_data.SpaceCardData object.

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.

datasets (list[str], optional) : List of datasets used by the Space.

disabled (bool, optional) : Is the Space disabled.

gated (Literal["auto", "manual", False], optional) : Is the repo gated. If so, whether there is manual or automatic approval.

host (str, optional) : Host URL of the Space.

last_modified (datetime, optional) : Date of last commit to the repo.

likes (int) : Number of likes of the Space.

models (list[str], optional) : List of models used by the Space.

private (bool) : Is the repo private.

resource_group (dict, optional) : Resource group information for the Space.

runtime (SpaceRuntime, optional) : Space runtime information as a huggingface_hub.hf_api.SpaceRuntime object.

sdk (str, optional) : SDK used by the Space.

sha (str, optional) : Repo SHA at this particular revision.

siblings (list[RepoSibling]) : List of huggingface_hub.hf_api.RepoSibling objects that constitute the Space.

subdomain (str, optional) : Subdomain of the Space.

tags (list[str]) : List of tags of the Space.

trending_score (int, optional) : Trending score of the Space.

used_storage (int, optional) : Size in bytes of the Space on the Hub.

TensorInfo[[huggingface_hub.utils.TensorInfo]][[huggingface_hub.utils.TensorInfo]]

huggingface_hub.utils.TensorInfo[[huggingface_hub.utils.TensorInfo]]

Source

Information about a tensor.

For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.

Parameters:

dtype (str) : The data type of the tensor ("F64", "F32", "F16", "BF16", "I64", "I32", "I16", "I8", "U8", "BOOL").

shape (list[int]) : The shape of the tensor.

data_offsets (tuple[int, int]) : The offsets of the data in the file as a tuple [BEGIN, END].

parameter_count (int) : The number of parameters in the tensor.

User[[huggingface_hub.User]][[huggingface_hub.User]]

huggingface_hub.User[[huggingface_hub.User]]

Source

Contains information about a user on the Hub.

Parameters:

username (str) : Name of the user on the Hub (unique).

fullname (str) : User's full name.

avatar_url (str) : URL of the user's avatar.

details (str, optional) : User's details.

is_following (bool, optional) : Whether the authenticated user is following this user.

is_pro (bool, optional) : Whether the user is a pro user.

num_models (int, optional) : Number of models created by the user.

num_datasets (int, optional) : Number of datasets created by the user.

num_spaces (int, optional) : Number of spaces created by the user.

num_discussions (int, optional) : Number of discussions initiated by the user.

num_papers (int, optional) : Number of papers authored by the user.

num_upvotes (int, optional) : Number of upvotes received by the user.

num_likes (int, optional) : Number of likes given by the user.

num_following (int, optional) : Number of users this user is following.

num_followers (int, optional) : Number of users following this user.

orgs (list of Organization) : List of organizations the user is part of.

UserLikes[[huggingface_hub.UserLikes]][[huggingface_hub.UserLikes]]

huggingface_hub.UserLikes[[huggingface_hub.UserLikes]]

Source

Contains information about a user likes on the Hub.

Parameters:

user (str) : Name of the user for which we fetched the likes.

total (int) : Total number of likes.

datasets (list[str]) : List of datasets liked by the user (as repo_ids).

kernels (list[str]) : List of kernels liked by the user (as repo_ids).

models (list[str]) : List of models liked by the user (as repo_ids).

spaces (list[str]) : List of spaces liked by the user (as repo_ids).

CommitOperation[[huggingface_hub.CommitOperationAdd]][[huggingface_hub.CommitOperationAdd]]

CommitOperation()에 지원되는 값은 다음과 같습니다:

huggingface_hub.CommitOperationAdd[[huggingface_hub.CommitOperationAdd]]

Source

Data structure holding necessary info to upload a file to a repository on the Hub.

as_filehuggingface_hub.CommitOperationAdd.as_filehttps://github.com/huggingface/huggingface_hub/blob/vr_4113/src/huggingface_hub/_commit_api.py#L209[{"name": "with_tqdm", "val": ": bool = False"}]- with_tqdm (bool, optional, defaults to False) -- If True, iterating over the file object will display a progress bar. Only works if the file-like object is a path to a file. Pure bytes and buffers are not supported.0

A context manager that yields a file-like object allowing to read the underlying data behind path_or_fileobj.

Example:

>>> operation = CommitOperationAdd(
...        path_in_repo="remote/dir/weights.h5",
...        path_or_fileobj="./local/weights.h5",
... )
CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5')

>>> with operation.as_file() as file:
...     content = file.read()

>>> with operation.as_file(with_tqdm=True) as file:
...     while True:
...         data = file.read(1024)
...         if not data:
...              break
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02>> with operation.as_file(with_tqdm=True) as file:
...     httpx.put(..., data=file)
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02

**Parameters:**

path_in_repo (`str`) : Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`

path_or_fileobj (`str`, `Path`, `bytes`, or `BinaryIO`) : Either: - a path to a local file (as `str` or `pathlib.Path`) to upload - a buffer of bytes (`bytes`) holding the content of the file to upload - a "file object" (subclass of `io.BufferedIOBase`), typically obtained with `open(path, "rb")`. It must support `seek()` and `tell()` methods.
#### b64content[[huggingface_hub.CommitOperationAdd.b64content]]

[Source](https://github.com/huggingface/huggingface_hub/blob/vr_4113/src/huggingface_hub/_commit_api.py#L259)

The base64-encoded content of `path_or_fileobj`

Returns: `bytes`

#### huggingface_hub.CommitOperationDelete[[huggingface_hub.CommitOperationDelete]]

[Source](https://github.com/huggingface/huggingface_hub/blob/vr_4113/src/huggingface_hub/_commit_api.py#L60)

Data structure holding necessary info to delete a file or a folder from a repository
on the Hub.

**Parameters:**

path_in_repo (`str`) : Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"` for a file or `"checkpoints/1fec34a/"` for a folder.

is_folder (`bool` or `Literal["auto"]`, *optional*) : Whether the Delete Operation applies to a folder or not. If "auto", the path type (file or folder) is guessed automatically by looking if path ends with a "/" (folder) or not (file). To explicitly set the path type, you can set `is_folder=True` or `is_folder=False`.

#### huggingface_hub.CommitOperationCopy[[huggingface_hub.CommitOperationCopy]]

[Source](https://github.com/huggingface/huggingface_hub/blob/vr_4113/src/huggingface_hub/_commit_api.py#L91)

Data structure holding necessary info to copy a file in a repository on the Hub.

Limitations:
- Only LFS files can be copied. To copy a regular file, you need to download it locally and re-upload it
- Cross-repository copies are not supported.

Note: you can combine a [CommitOperationCopy](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.CommitOperationCopy) and a [CommitOperationDelete](/docs/huggingface_hub/pr_4113/ko/package_reference/hf_api#huggingface_hub.CommitOperationDelete) to rename an LFS file on the Hub.

**Parameters:**

src_path_in_repo (`str`) : Relative filepath in the repo of the file to be copied, e.g. `"checkpoints/1fec34a/weights.bin"`.

path_in_repo (`str`) : Relative filepath in the repo where to copy the file, e.g. `"checkpoints/1fec34a/weights_copy.bin"`.

src_revision (`str`, *optional*) : The git revision of the file to be copied. Can be any valid git revision. Default to the target commit revision.

## CommitScheduler[[huggingface_hub.CommitScheduler]][[huggingface_hub.CommitScheduler]]

#### huggingface_hub.CommitScheduler[[huggingface_hub.CommitScheduler]]

[Source](https://github.com/huggingface/huggingface_hub/blob/vr_4113/src/huggingface_hub/_commit_scheduler.py#L29)

Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes).

The recommended way to use the scheduler is to use it as a context manager. This ensures that the scheduler is
properly stopped and the last commit is triggered when the script ends. The scheduler can also be stopped manually
with the `stop` method. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads)
to learn more about how to use it.

Example:
```py
>>> from pathlib import Path
>>> from huggingface_hub import CommitScheduler

# Scheduler uploads every 10 minutes
>>> csv_path = Path("watched_folder/data.csv")
>>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)

>>> with csv_path.open("a") as f:
...     f.write("first line")

# Some time later (...)
>>> with csv_path.open("a") as f:
...     f.write("second line")

Example using a context manager:

>>> from pathlib import Path
>>> from huggingface_hub import CommitScheduler

>>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler:
...     csv_path = Path("watched_folder/data.csv")
...     with csv_path.open("a") as f:
...         f.write("first line")
...     (...)
...     with csv_path.open("a") as f:
...         f.write("second line")

# Scheduler is now stopped and last commit have been triggered

push_to_hubhuggingface_hub.CommitScheduler.push_to_hubhttps://github.com/huggingface/huggingface_hub/blob/vr_4113/src/huggingface_hub/_commit_scheduler.py#L204[]

Push folder to the Hub and return the commit info.

This method is not meant to be called directly. It is run in the background by the scheduler, respecting a queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency issues.

The default behavior of push_to_hub is to assume an append-only folder. It lists all files in the folder and uploads only changed files. If no changes are found, the method returns without committing anything. If you want to change this behavior, you can inherit from CommitScheduler and override this method. This can be useful for example to compress data together in a single file before committing. For more details and examples, check out our integration guide.

Parameters:

repo_id (str) : The id of the repo to commit to.

folder_path (str or Path) : Path to the local folder to upload regularly.

every (int or float, optional) : The number of minutes between each commit. Defaults to 5 minutes.

path_in_repo (str, optional) : Relative path of the directory in the repo, for example: "checkpoints/". Defaults to the root folder of the repository.

repo_type (str, optional) : The type of the repo to commit to. Defaults to model.

revision (str, optional) : The revision of the repo to commit to. Defaults to main.

private (bool, optional) : Whether to make the repo private. If None (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.

token (str, optional) : The token to use to commit to the repo. Defaults to the token saved on the machine.

allow_patterns (list[str] or str, optional) : If provided, only files matching at least one pattern are uploaded.

ignore_patterns (list[str] or str, optional) : If provided, files matching any of the patterns are not uploaded.

squash_history (bool, optional) : Whether to squash the history of the repo after each commit. Defaults to False. Squashing commits is useful to avoid degraded performances on the repo when it grows too large.

hf_api (HfApi, optional) : The HfApi client to use to commit to the Hub. Can be set with custom settings (user agent, token,...).

stop[[huggingface_hub.CommitScheduler.stop]]

Source

Stop the scheduler.

A stopped scheduler cannot be restarted. Mostly for tests purposes.

trigger[[huggingface_hub.CommitScheduler.trigger]]

Source

Trigger a push_to_hub and return a future.

This method is automatically called every every minutes. You can also call it manually to trigger a commit immediately, without waiting for the next scheduled commit.

Xet Storage Details

Size:
309 kB
·
Xet hash:
f79020ab665197efa6a3617af52f8dbafaa5a6fd1f304ef0734a383637a7d5b8

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.