Hub Python Library documentation

HfApi Client

You are viewing v0.19.0.rc0 version. A newer version v0.20.3 is available.
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

HfApi Client

Below is the documentation for the HfApi class, which serves as a Python wrapper for the Hugging Face Hub’s API.

All methods from the HfApi are also accessible from the package’s root directly. Both approaches are detailed below.

Using the root method is more straightforward but the HfApi class gives you more flexibility. In particular, you can pass a token that will be reused in all HTTP calls. This is different than huggingface-cli login or login() as the token is not persisted on the machine. It is also possible to provide a different endpoint or configure a custom user-agent.

from huggingface_hub import HfApi, list_models

# Use root method
models = list_models()

# Or configure a HfApi client
hf_api = HfApi(
    endpoint="https://huggingface.co", # Can be a Private Hub endpoint.
    token="hf_xxx", # Token is not persisted on the machine.
)
models = hf_api.list_models()

HfApi

class huggingface_hub.HfApi

< >

( endpoint: Optional[str] = None token: Optional[str] = None library_name: Optional[str] = None library_version: Optional[str] = None user_agent: Union[Dict, str, None] = None )

add_collection_item

< >

( collection_slug: str item_id: str item_type: CollectionItemType_T note: Optional[str] = None exists_ok: bool = False token: Optional[str] = None )

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. It can be the ID of a repo on the Hub (e.g. "facebook/bart-large-mnli") or a paper id (e.g. "2307.09288").
  • item_type (str) — Type of the item to add. Can be one of "model", "dataset", "space" or "paper".
  • 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 (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

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."
... )
(...)

add_space_secret

< >

( repo_id: str key: str value: str description: Optional[str] = None token: Optional[str] = None )

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 (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

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.

add_space_variable

< >

( repo_id: str key: str value: str description: Optional[str] = None token: Optional[str] = None )

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 (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

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

change_discussion_status

< >

( repo_id: str discussion_num: int new_status: Literal[('open', 'closed')] token: Optional[str] = None comment: Optional[str] = None repo_type: Optional[str] = None ) DiscussionStatusChange

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token)

Returns

DiscussionStatusChange

the status change event

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 if the HuggingFace API returned an error
  • ValueError if some parameter value is invalid
  • 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.

comment_discussion

< >

( repo_id: str discussion_num: int comment: str token: Optional[str] = None repo_type: Optional[str] = None ) DiscussionComment

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token)

Returns

DiscussionComment

the newly created comment

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 if the HuggingFace API returned an error
  • ValueError if some parameter value is invalid
  • 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.

create_branch

< >

( repo_id: str branch: str revision: Optional[str] = None token: Optional[str] = None repo_type: Optional[str] = None exist_ok: bool = False )

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 (str, optional) — Authentication token. Will default to the stored token.
  • 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.

Raises

RepositoryNotFoundError or BadRequestError or HfHubHTTPError

  • RepositoryNotFoundError — If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo does not exist.
  • BadRequestError — If invalid reference for a branch. Ex: refs/pr/5 or ‘refs/foo/bar’.
  • HfHubHTTPError — If the branch already exists on the repo (error 409) and exist_ok is set to False.

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().

create_collection

< >

( title: str namespace: Optional[str] = None description: Optional[str] = None private: bool = False exists_ok: bool = False token: Optional[str] = None )

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 (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

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"

create_commit

< >

( repo_id: str operations: Iterable[CommitOperation] commit_message: str commit_description: Optional[str] = None token: Optional[str] = None repo_type: Optional[str] = None revision: Optional[str] = None create_pr: Optional[bool] = None num_threads: int = 5 parent_commit: Optional[str] = None run_as_future: bool = False ) CommitInfo or Future

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:

    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 (str, optional) — Authentication token, obtained with HfApi.login method. Will default to the stored token.
  • 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 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.

Raises

ValueError or RepositoryNotFoundError

  • ValueError — If commit message is empty.
  • ValueError — If parent commit is not a valid commit OID.
  • ValueError — If the Hub API returns an HTTP 400 error (bad request)
  • ValueError — If create_pr is True and revision is neither None nor "main".
  • RepositoryNotFoundError — If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo does not exist.

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 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.

create_commits_on_pr

< >

( repo_id: str addition_commits: List[List[CommitOperationAdd]] deletion_commits: List[List[CommitOperationDelete]] commit_message: str commit_description: Optional[str] = None token: Optional[str] = None repo_type: Optional[str] = None merge_pr: bool = True num_threads: int = 5 verbose: bool = False ) str

Parameters

  • repo_id (str) — The repository in which the commits will be pushed. Example: "username/my-cool-model".
  • addition_commits (List of List of CommitOperationAdd) — A list containing lists of CommitOperationAdd. Each sublist will result in a commit on the PR.

    deletion_commits — A list containing lists of CommitOperationDelete. Each sublist will result in a commit on the PR. Deletion commits are pushed before addition commits.

  • commit_message (str) — The summary (first line) of the commit that will be created. Will also be the title of the PR.
  • commit_description (str, optional) — The description of the commit that will be created. The description will be added to the PR.
  • token (str, optional) — Authentication token, obtained with HfApi.login method. Will default to the stored token.
  • 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.
  • merge_pr (bool) — If set to True, the Pull Request is merged at the end of the process. Defaults to True.
  • num_threads (int, optional) — Number of concurrent threads for uploading files. Defaults to 5.
  • verbose (bool) — If set to True, process will run on verbose mode i.e. print information about the ongoing tasks. Defaults to False.

Returns

str

URL to the created PR.

Raises

MultiCommitException

  • MultiCommitException — If an unexpected issue occur in the process: empty commits, unexpected commits in a PR, unexpected PR description, etc.

Push changes to the Hub in multiple commits.

Commits are pushed to a draft PR branch. If the upload fails or gets interrupted, it can be resumed. Progress is tracked in the PR description. At the end of the process, the PR is set as open and the title is updated to match the initial commit message. If merge_pr=True is passed, the PR is merged automatically.

All deletion commits are pushed first, followed by the addition commits. The order of the commits is not guaranteed as we might implement parallel commits in the future. Be sure that your are not updating several times the same file.

create_commits_on_pr is experimental. Its API and behavior is subject to change in the future without prior notice.

create_commits_on_pr assumes that the repo already exists on the Hub. If you get a Client error 404, please make sure you are authenticated 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 HfApi, plan_multi_commits
>>> addition_commits, deletion_commits = plan_multi_commits(
...     operations=[
...          CommitOperationAdd(...),
...          CommitOperationAdd(...),
...          CommitOperationDelete(...),
...          CommitOperationDelete(...),
...          CommitOperationAdd(...),
...     ],
... )
>>> HfApi().create_commits_on_pr(
...     repo_id="my-cool-model",
...     addition_commits=addition_commits,
...     deletion_commits=deletion_commits,
...     (...)
...     verbose=True,
... )

create_discussion

< >

( repo_id: str title: str token: Optional[str] = None description: Optional[str] = None repo_type: Optional[str] = None pull_request: bool = False )

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token)
  • 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.

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 if the HuggingFace API returned an error
  • ValueError if some parameter value is invalid
  • 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.

create_inference_endpoint

< >

( name: str repository: str framework: str accelerator: str instance_size: str instance_type: str region: str vendor: str account_id: Optional[str] = None min_replica: int = 0 max_replica: int = 1 revision: Optional[str] = None task: Optional[str] = None type: InferenceEndpointType = <InferenceEndpointType.PROTECTED: 'protected'> namespace: Optional[str] = None token: Optional[str] = None ) InferenceEndpoint

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. "large").
  • instance_type (str) — The cloud instance type where the Inference Endpoint will be deployed (e.g. "c6i").
  • 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. Defaults to 0.
  • max_replica (int, optional) — The maximum number of replicas (instances) to scale to for the Inference Endpoint. Defaults to 1.
  • 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").
  • type ([`InferenceEndpointType], *optional*) -- The type of the Inference Endpoint, which can be “protected”(default),“public”or“private”`.
  • namespace (str, optional) — The namespace where the Inference Endpoint will be created. Defaults to the current user’s namespace.
  • token (str, optional) — An authentication token (See https://huggingface.co/settings/token).

Returns

InferenceEndpoint

information about the updated Inference Endpoint.

Create a new Inference Endpoint.

Example:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> 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="medium",
...     instance_type="c6i"
... )
>>> endpoint
InferenceEndpoint(name='my-endpoint-name', status="pending",...)

# Run inference on the endpoint
>>> endpoint.client.text_generation(...)
"..."

create_pull_request

< >

( repo_id: str title: str token: Optional[str] = None description: Optional[str] = None repo_type: Optional[str] = None )

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token)
  • 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.

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 if the HuggingFace API returned an error
  • ValueError if some parameter value is invalid
  • 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.

create_repo

< >

( repo_id: str token: Optional[str] = None private: bool = False repo_type: Optional[str] = None exist_ok: bool = False space_sdk: Optional[str] = None space_hardware: Optional[SpaceHardware] = None space_storage: Optional[SpaceStorage] = None space_sleep_time: Optional[int] = None space_secrets: Optional[List[Dict[str, str]]] = None space_variables: Optional[List[Dict[str, str]]] = None ) RepoUrl

Parameters

  • repo_id (str) — A namespace (user or an organization) and a repo name separated by a /.
  • token (str, optional) — An authentication token (See https://huggingface.co/settings/token)
  • private (bool, optional, defaults to False) — Whether the model repo should be private.
  • 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.
  • 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.

Returns

RepoUrl

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

Create an empty repo on the HuggingFace Hub.

create_tag

< >

( repo_id: str tag: str tag_message: Optional[str] = None revision: Optional[str] = None token: Optional[str] = None repo_type: Optional[str] = None exist_ok: bool = False )

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 (str, optional) — Authentication token. Will default to the stored token.
  • 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.

Raises

RepositoryNotFoundError or RevisionNotFoundError or HfHubHTTPError

  • RepositoryNotFoundError — If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo does not exist.
  • RevisionNotFoundError — If revision is not found (error 404) on the repo.
  • HfHubHTTPError — If the branch already exists on the repo (error 409) and exist_ok is set to False.

Tag a given commit of a repo on the Hub.

dataset_info

< >

( repo_id: str revision: Optional[str] = None timeout: Optional[float] = None files_metadata: bool = False token: Optional[Union[bool, str]] = None ) hf_api.DatasetInfo

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.
  • token (bool or str, optional) — A valid authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.

Returns

hf_api.DatasetInfo

The dataset repository information.

Get info on one specific dataset on huggingface.co.

Dataset can be private if you pass an acceptable token.

Raises the following 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 If the revision to download from cannot be found.

delete_branch

< >

( repo_id: str branch: str token: Optional[str] = None repo_type: Optional[str] = None )

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 (str, optional) — Authentication token. Will default to the stored token.
  • 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.

Raises

RepositoryNotFoundError or HfHubHTTPError

  • RepositoryNotFoundError — If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo does not exist.
  • HfHubHTTPError — If trying to delete a protected branch. Ex: main cannot be deleted.
  • HfHubHTTPError — If trying to delete a branch that does not exist.

Delete a branch from a repo on the Hub.

delete_collection

< >

( collection_slug: str missing_ok: bool = False token: Optional[str] = None )

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 (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

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.

delete_collection_item

< >

( collection_slug: str item_object_id: str missing_ok: bool = False token: Optional[str] = None )

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]._id.
  • missing_ok (bool, optional) — If True, do not raise an error if item doesn’t exists.
  • token (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

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,
... )

delete_file

< >

( path_in_repo: str repo_id: str token: Optional[str] = None repo_type: Optional[str] = None revision: Optional[str] = None commit_message: Optional[str] = None commit_description: Optional[str] = None create_pr: Optional[bool] = None parent_commit: Optional[str] = None )

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 (str, optional) — Authentication token, obtained with HfApi.login method. Will default to the stored token.
  • 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.

Deletes a file in the given repo.

Raises the following errors:

delete_folder

< >

( path_in_repo: str repo_id: str token: Optional[str] = None repo_type: Optional[str] = None revision: Optional[str] = None commit_message: Optional[str] = None commit_description: Optional[str] = None create_pr: Optional[bool] = None parent_commit: Optional[str] = None )

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 (str, optional) — Authentication token, obtained with HfApi.login method. Will default 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.

Deletes a folder in the given repo.

Simple wrapper around create_commit() method.

delete_inference_endpoint

< >

( name: str namespace: Optional[str] = None token: Optional[str] = None )

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token).

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().

delete_repo

< >

( repo_id: str token: Optional[str] = None repo_type: Optional[str] = None missing_ok: bool = False )

Parameters

  • repo_id (str) — A namespace (user or an organization) and a repo name separated by a /.
  • token (str, optional) — An authentication token (See https://huggingface.co/settings/token)
  • 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.

Raises

    • RepositoryNotFoundError If the repository to delete from cannot be found and missing_ok is set to False (default).

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

delete_space_secret

< >

( repo_id: str key: str token: Optional[str] = None )

Parameters

  • repo_id (str) — ID of the repo to update. Example: "bigcode/in-the-stack".
  • key (str) — Secret key. Example: "GITHUB_API_KEY".
  • token (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

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.

delete_space_storage

< >

( repo_id: str token: Optional[str] = None ) SpaceRuntime

Parameters

  • repo_id (str) — ID of the Space to update. Example: "HuggingFaceH4/open_llm_leaderboard".
  • token (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

Returns

SpaceRuntime

Runtime information about a Space including Space stage and hardware.

Raises

BadRequestError

  • BadRequestError — If space has no persistent storage.

Delete persistent storage for a Space.

delete_space_variable

< >

( repo_id: str key: str token: Optional[str] = None )

Parameters

  • repo_id (str) — ID of the repo to update. Example: "bigcode/in-the-stack".
  • key (str) — Variable key. Example: "MODEL_REPO_ID"
  • token (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

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

delete_tag

< >

( repo_id: str tag: str token: Optional[str] = None repo_type: Optional[str] = None )

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 (str, optional) — Authentication token. Will default to the stored token.
  • 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.

Raises

RepositoryNotFoundError or RevisionNotFoundError

Delete a tag from a repo on the Hub.

duplicate_space

< >

( from_id: str to_id: Optional[str] = None private: Optional[bool] = None token: Optional[str] = None exist_ok: bool = False hardware: Optional[SpaceHardware] = None storage: Optional[SpaceStorage] = None sleep_time: Optional[int] = None secrets: Optional[List[Dict[str, str]]] = None variables: Optional[List[Dict[str, str]]] = None ) RepoUrl

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.
  • token (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.
  • 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

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

Raises

    • HTTPError if the HuggingFace API returned an error
    • RepositoryNotFoundError If one of from_id or to_id cannot be found. This may be because it doesn’t exist, or because it is set to private and you do not have access.

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", private=True)
RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...)

edit_discussion_comment

< >

( repo_id: str discussion_num: int comment_id: str new_content: str token: Optional[str] = None repo_type: Optional[str] = None ) DiscussionComment

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token)

Returns

DiscussionComment

the edited comment

Edits a comment on a Discussion / Pull Request.

Raises the following errors:

  • HTTPError if the HuggingFace API returned an error
  • ValueError if some parameter value is invalid
  • 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.

file_exists

< >

( repo_id: str filename: str repo_type: Optional[str] = None revision: Optional[str] = None token: Optional[str] = None )

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 authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.

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

get_collection

< >

( collection_slug: str token: Optional[str] = None )

Parameters

  • collection_slug (str) — Slug of the collection of the Hub. Example: "TheBloke/recent-models-64f9a55bb3115b4f513ec026".
  • token (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

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
)

get_dataset_tags

< >

( )

List all valid dataset tags as a nested namespace object.

get_discussion_details

< >

( repo_id: str discussion_num: int repo_type: Optional[str] = None token: Optional[str] = None )

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token)

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

Returns: DiscussionWithDetails

Raises the following errors:

  • HTTPError if the HuggingFace API returned an error
  • ValueError if some parameter value is invalid
  • 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.

get_full_repo_name

< >

( model_id: str organization: Optional[str] = None token: Optional[Union[bool, str]] = None ) str

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 authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.

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.

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

get_inference_endpoint

< >

( name: str namespace: Optional[str] = None token: Optional[str] = None ) InferenceEndpoint

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token).

Returns

InferenceEndpoint

information about the requested Inference Endpoint.

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(...)

get_model_tags

< >

( )

List all valid model tags as a nested namespace object

get_repo_discussions

< >

( repo_id: str repo_type: Optional[str] = None token: Optional[str] = None ) Iterator[Discussion]

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 fetching from a dataset or space, None or "model" if fetching from a model. Default is None.
  • token (str, optional) — An authentication token (See https://huggingface.co/settings/token).

Returns

Iterator[Discussion]

An iterator of Discussion objects.

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)

get_space_runtime

< >

( repo_id: str token: Optional[str] = None ) SpaceRuntime

Parameters

  • repo_id (str) — ID of the repo to update. Example: "bigcode/in-the-stack".
  • token (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

Returns

SpaceRuntime

Runtime information about a Space including Space stage and hardware.

Gets runtime information about a Space.

get_space_variables

< >

( repo_id: str token: Optional[str] = None )

Parameters

  • repo_id (str) — ID of the repo to query. Example: "bigcode/in-the-stack".
  • token (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

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

get_token_permission

< >

( token: Optional[str] = None ) Literal["read", "write", None]

Parameters

  • token (str, optional) — The token to check for validity. Defaults to the one saved locally.

Returns

Literal["read", "write", None]

Permission granted by the token (“read” or “write”). Returns None if no token passed or token is invalid.

Check if a given token is valid and return its permissions.

For more details about tokens, please refer to https://huggingface.co/docs/hub/security-tokens#what-are-user-access-tokens.

hf_hub_download

< >

( repo_id: str filename: str subfolder: Optional[str] = None repo_type: Optional[str] = None revision: Optional[str] = None cache_dir: Union[str, Path, None] = None local_dir: Union[str, Path, None] = None local_dir_use_symlinks: Union[bool, Literal['auto']] = 'auto' force_download: bool = False force_filename: Optional[str] = None proxies: Optional[Dict] = None etag_timeout: float = 10 resume_download: bool = False token: Optional[Union[str, bool]] = None local_files_only: bool = False legacy_cache_layout: bool = False )

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 model repo.
  • 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, either as a symlink (default) or a regular file (see description for more details).
  • local_dir_use_symlinks ("auto" or bool, defaults to "auto") — To be used with local_dir. If set to “auto”, the cache directory will be used and the file will be either duplicated or symlinked to the local directory depending on its size. It set to True, a symlink will be created, no matter the file size. If set to False, the file will either be duplicated from cache (if already exists) or downloaded from the Hub and not cached. See description for more details.
  • force_download (bool, optional, defaults to False) — Whether the file should be downloaded even if it already exists in the local cache.
  • proxies (dict, optional) — Dictionary mapping protocol to the URL of the proxy passed to requests.request.
  • 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 requests.request.
  • resume_download (bool, optional, defaults to False) — If True, resume a previously interrupted download.
  • token (bool or str, optional) — A valid authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.
  • 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.
  • legacy_cache_layout (bool, optional, defaults to False) — If True, uses the legacy file cache layout i.e. just call hf_hub_url() then cached_download. This is deprecated as the new cache layout is more powerful.

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.

If local_dir is provided, the file structure from the repo will be replicated in this location. You can configure how you want to move those files:

  • If local_dir_use_symlinks="auto" (default), files are downloaded and stored in the cache directory as blob files. Small files (<5MB) are duplicated in local_dir while a symlink is created for bigger files. The goal is to be able to manually edit and save small files without corrupting the cache while saving disk space for binary files. The 5MB threshold can be configured with the HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD environment variable.
  • If local_dir_use_symlinks=True, files are downloaded, stored in the cache directory and symlinked in local_dir. This is optimal in term of disk usage but files must not be manually edited.
  • If local_dir_use_symlinks=False and the blob files exist in the cache directory, they are duplicated in the local dir. This means disk usage is not optimized.
  • Finally, if local_dir_use_symlinks=False and the blob files do not exist in the cache directory, then the files are downloaded and directly placed under local_dir. This means if you need to download them again later, they will be re-downloaded entirely.
[  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

Raises the following errors:

hide_discussion_comment

< >

( repo_id: str discussion_num: int comment_id: str token: Optional[str] = None repo_type: Optional[str] = None ) DiscussionComment

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token)

Returns

DiscussionComment

the hidden comment

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 if the HuggingFace API returned an error
  • ValueError if some parameter value is invalid
  • 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.

like

< >

( repo_id: str token: Optional[str] = None repo_type: Optional[str] = None )

Parameters

  • repo_id (str) — The repository to like. Example: "user/my-cool-model".
  • token (str, optional) — Authentication token. Will default to the stored token.
  • repo_type (str, optional) — Set to "dataset" or "space" if liking a dataset or space, None or "model" if liking a model. Default is None.

Raises

RepositoryNotFoundError

  • RepositoryNotFoundError — If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo does not exist.

Like a given repo on the Hub (e.g. set as favorite).

See also unlike() and list_liked_repos().

Example:

>>> from huggingface_hub import like, list_liked_repos, unlike
>>> like("gpt2")
>>> "gpt2" in list_liked_repos().models
True
>>> unlike("gpt2")
>>> "gpt2" in list_liked_repos().models
False

list_datasets

< >

( filter: Union[DatasetFilter, str, Iterable[str], None] = None author: Optional[str] = None search: Optional[str] = None sort: Union[Literal['last_modified'], str, None] = None direction: Optional[Literal[-1]] = None limit: Optional[int] = None full: Optional[bool] = None token: Optional[str] = None ) Iterable[DatasetInfo]

Parameters

  • filter (DatasetFilter or str or Iterable, optional) — A string or DatasetFilter which can be used to identify datasets on the hub.
  • author (str, optional) — A string which identify the author of the returned datasets.
  • search (str, optional) — A string that will be contained in the returned datasets.
  • sort (Literal["last_modified"] or str, optional) — The key with which to sort the resulting datasets. Possible values are the properties of the huggingface_hub.hf_api.DatasetInfo class.
  • direction (Literal[-1] or int, optional) — Direction in which to sort. The value -1 sorts by descending order while all other values sort by ascending order.
  • limit (int, optional) — The limit on the number of datasets fetched. Leaving this option to None fetches all datasets.
  • full (bool, optional) — Whether to fetch all dataset data, including the last_modified, the card_data and the files. Can contain useful information such as the PapersWithCode ID.
  • token (bool or str, optional) — A valid authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.

Returns

Iterable[DatasetInfo]

an iterable of huggingface_hub.hf_api.DatasetInfo objects.

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")
>>> # Using the `DatasetFilter`
>>> filt = DatasetFilter(task_categories="text-classification")


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

>>> api.list_datasets(filter=filt)

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")

list_files_info

< >

( repo_id: str paths: Union[List[str], str, None] = None expand: bool = False revision: Optional[str] = None repo_type: Optional[str] = None token: Optional[Union[bool, str]] = None ) Iterable[RepoFile]

Parameters

  • repo_id (str) — A namespace (user or an organization) and a repo name separated by a /.
  • paths (Union[List[str], str, None], optional) — The paths to get information about. Paths to files are directly resolved. Paths to folders are resolved recursively which means that information is returned about all files in the folder and its subfolders. If None, all files are returned (the default). 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 files (e.g. last commit and 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 authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.

Returns

Iterable[RepoFile]

The information about the files, as an iterable of RepoFile objects. The order of the files is not guaranteed.

Raises

RepositoryNotFoundError or RevisionNotFoundError

  • RepositoryNotFoundError — If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo does not exist.
  • RevisionNotFoundError — If revision is not found (error 404) on the repo.

List files on a repo and get information about them.

Takes as input a list of paths. Those paths can be either files or folders. Two server endpoints are called:

  1. POST “/paths-info” to get information about the provided paths. Called once.
  2. GET “/tree?recursive=True” to paginate over the input folders. Called only if a folder path is provided as input. Will be called multiple times to follow pagination. If no path is provided as input, step 1. is ignored and all files from the repo are listed.

Examples:

Get information about files on a repo.

>>> from huggingface_hub import list_files_info
>>> files_info = list_files_info("lysandre/arxiv-nlp", ["README.md", "config.json"])
>>> files_info
<generator object HfApi.list_files_info at 0x7f93b848e730>
>>> list(files_info)
[
    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)
]

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

>>> from huggingface_hub import list_files_info
>>> files_info = list_files_info("prompthero/openjourney-v4", expand=True)
>>> list(files_info)
[
    RepoFile(
        path='safety_checker/pytorch_model.bin',
        size=1216064769,
        blob_id='c8835557a0d3af583cb06c7c154b7e54a069c41d',
        lfs={
            'size': 1216064769,
            'sha256': '16d28f2b37109f222cdc33620fdd262102ac32112be0352a7f77e9614b35a394',
            'pointer_size': 135
        },
        last_commit={
            'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
            'title': 'Upload diffusers weights (#48)',
            'date': datetime.datetime(2023, 3, 21, 10, 5, 27, tzinfo=datetime.timezone.utc)
        },
        security={
            'safe': True,
            'av_scan': {
                'virusFound': False,
                'virusNames': None
            },
            'pickle_import_scan': {
                'highestSafetyLevel': 'innocuous',
                'imports': [
                    {'module': 'torch', 'name': 'FloatStorage', 'safety': 'innocuous'},
                    {'module': 'collections', 'name': 'OrderedDict', 'safety': 'innocuous'},
                    {'module': 'torch', 'name': 'LongStorage', 'safety': 'innocuous'},
                    {'module': 'torch._utils', 'name': '_rebuild_tensor_v2', 'safety': 'innocuous'}
                ]
            }
        }
    ),
    RepoFile(
        path='scheduler/scheduler_config.json',
        size=465,
        blob_id='70d55e3e9679f41cbc66222831b38d5abce683dd',
        lfs=None,
        last_commit={
            'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
            'title': 'Upload diffusers weights (#48)',
            'date': datetime.datetime(2023, 3, 21, 10, 5, 27, tzinfo=datetime.timezone.utc)},
            security={
                'safe': True,
                'av_scan': {
                    'virusFound': False,
                    'virusNames': None
                },
                'pickle_import_scan': None
            }
    ),
    ...
]

List LFS files from the “vae/” folder in “stabilityai/stable-diffusion-2” repository.

>>> from huggingface_hub import list_files_info
>>> [info.path for info in list_files_info("stabilityai/stable-diffusion-2", "vae") if info.lfs is not None]
['vae/diffusion_pytorch_model.bin', 'vae/diffusion_pytorch_model.safetensors']

List all files on a repo.

>>> from huggingface_hub import list_files_info
>>> [info.path for info in list_files_info("glue", repo_type="dataset")]
['.gitattributes', 'README.md', 'dataset_infos.json', 'glue.py']

list_inference_endpoints

< >

( namespace: Optional[str] = None token: Optional[str] = None ) ListInferenceEndpoint

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token).

Returns

ListInferenceEndpoint

A list of all inference endpoints for the given namespace.

Lists all inference endpoints for the given namespace.

Example:

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

list_liked_repos

< >

( user: Optional[str] = None token: Optional[str] = None ) UserLikes

Parameters

  • user (str, optional) — Name of the user for which you want to fetch the likes.
  • token (str, optional) — A valid authentication token (see https://huggingface.co/settings/token). Used only if user is not passed to implicitly determine the current user name.

Returns

UserLikes

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

Raises

ValueError

  • ValueError — If user is not passed and no token found (either from argument or from machine).

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 like() and 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", ...]

list_metrics

< >

( ) List[MetricInfo]

Returns

List[MetricInfo]

a list of MetricInfo objects which.

Get the public list of all the metrics on huggingface.co

list_models

< >

( filter: Union[ModelFilter, str, Iterable[str], None] = None author: Optional[str] = None search: Optional[str] = None emissions_thresholds: Optional[Tuple[float, float]] = None sort: Union[Literal['last_modified'], str, None] = None direction: Optional[Literal[-1]] = None limit: Optional[int] = None full: Optional[bool] = None cardData: bool = False fetch_config: bool = False token: Optional[Union[bool, str]] = None ) Iterable[ModelInfo]

Parameters

  • filter (ModelFilter or str or Iterable, optional) — A string or ModelFilter which can be used to identify models on the Hub.
  • author (str, optional) — A string which identify the author (user or organization) of the returned models
  • search (str, optional) — A string that will be contained in the returned model ids.
  • 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 (Literal["last_modified"] or str, optional) — The key with which to sort the resulting models. Possible values are the properties of the huggingface_hub.hf_api.ModelInfo class.
  • direction (Literal[-1] or int, optional) — Direction in which to sort. The value -1 sorts by descending order while all other values sort by ascending order.
  • limit (int, optional) — The limit on the number of models fetched. Leaving this option to None fetches all models.
  • 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 authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.

Returns

Iterable[ModelInfo]

an iterable of huggingface_hub.hf_api.ModelInfo objects.

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

Example usage with the filter argument:

>>> from huggingface_hub import HfApi

>>> api = HfApi()

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

>>> # List only the text classification models
>>> api.list_models(filter="text-classification")
>>> # Using the `ModelFilter`
>>> filt = ModelFilter(task="text-classification")


>>> # List only models from the AllenNLP library
>>> api.list_models(filter="allennlp")


Example usage with the `search` argument:
python >>> from huggingface_hub import HfApi

api = HfApi()

List all models with “bert” in their name

api.list_models(search=“bert”)

List all models with “bert” in their name made by google

api.list_models(search=“bert”, author=“google”)

list_repo_commits

< >

( repo_id: str repo_type: Optional[str] = None token: Optional[Union[bool, str]] = None revision: Optional[str] = None formatted: bool = False ) List[GitCommitInfo]

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 authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.
  • 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]

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

Raises

RepositoryNotFoundError or RevisionNotFoundError

  • RepositoryNotFoundError — If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo does not exist.
  • RevisionNotFoundError — If revision is not found (error 404) on the repo.

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)

list_repo_files

< >

( repo_id: str revision: Optional[str] = None repo_type: Optional[str] = None timeout: Optional[float] = None token: Optional[Union[bool, str]] = None ) List[str]

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.
  • 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 authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.

Returns

List[str]

the list of files in a given repository.

Get the list of files in a given repo.

list_repo_likers

< >

( repo_id: str repo_type: Optional[str] = None token: Optional[str] = None ) List[User]

Parameters

  • repo_id (str) — The repository to retrieve . Example: "user/my-cool-model".
  • token (str, optional) — Authentication token. Will default to the stored token.
  • 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

List[User]

a list of User objects.

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

See also like() and list_liked_repos().

list_repo_refs

< >

( repo_id: str repo_type: Optional[str] = None token: Optional[Union[bool, str]] = None ) GitRefs

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 refs from a dataset or a Space, None or "model" if listing from a model. Default is None.
  • token (bool or str, optional) — A valid authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.

Returns

GitRefs

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

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')
    ]
)

list_spaces

< >

( filter: Union[str, Iterable[str], None] = None author: Optional[str] = None search: Optional[str] = None sort: Union[Literal['last_modified'], str, None] = None direction: Optional[Literal[-1]] = None limit: Optional[int] = None datasets: Union[str, Iterable[str], None] = None models: Union[str, Iterable[str], None] = None linked: bool = False full: Optional[bool] = None token: Optional[str] = None ) Iterable[SpaceInfo]

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.
  • sort (Literal["last_modified"] or str, optional) — The key with which to sort the resulting Spaces. Possible values are the properties of the huggingface_hub.hf_api.SpaceInfo` class.
  • direction (Literal[-1] or int, optional) — Direction in which to sort. The value -1 sorts by descending order while all other values sort by ascending order.
  • limit (int, optional) — The limit on the number of Spaces fetched. Leaving this option to None fetches all 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.
  • 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 authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.

Returns

Iterable[SpaceInfo]

an iterable of huggingface_hub.hf_api.SpaceInfo objects.

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

merge_pull_request

< >

( repo_id: str discussion_num: int token: Optional[str] = None comment: Optional[str] = None repo_type: Optional[str] = None ) DiscussionStatusChange

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token)

Returns

DiscussionStatusChange

the status change event

Merges a Pull Request.

Raises the following errors:

  • HTTPError if the HuggingFace API returned an error
  • ValueError if some parameter value is invalid
  • 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.

model_info

< >

( repo_id: str revision: Optional[str] = None timeout: Optional[float] = None securityStatus: Optional[bool] = None files_metadata: bool = False token: Optional[Union[bool, str]] = None ) huggingface_hub.hf_api.ModelInfo

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.
  • 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 authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.

Returns

huggingface_hub.hf_api.ModelInfo

The model repository information.

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 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 If the revision to download from cannot be found.

move_repo

< >

( from_id: str to_id: str repo_type: Optional[str] = None token: Optional[str] = None )

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token)

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 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.

pause_inference_endpoint

< >

( name: str namespace: Optional[str] = None token: Optional[str] = None ) InferenceEndpoint

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token).

Returns

InferenceEndpoint

information about the paused Inference Endpoint.

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().

pause_space

< >

( repo_id: str token: Optional[str] = None ) SpaceRuntime

Parameters

  • repo_id (str) — ID of the Space to pause. Example: "Salesforce/BLIP2".
  • token (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

Returns

SpaceRuntime

Runtime information about your Space including stage=PAUSED and requested hardware.

Raises

RepositoryNotFoundError or HfHubHTTPError or BadRequestError

  • RepositoryNotFoundError — If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you are not authenticated.
  • HfHubHTTPError — 403 Forbidden: only the owner of a Space can pause it. If you want to manage a Space that you don’t own, either ask the owner by opening a Discussion or duplicate the Space.
  • BadRequestError — If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide a static Space, you can set it to private.

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.

preupload_lfs_files

< >

( repo_id: str additions: Iterable[CommitOperationAdd] token: Optional[str] = None repo_type: Optional[str] = None revision: Optional[str] = None create_pr: Optional[bool] = None num_threads: int = 5 free_memory: bool = True )

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 (str, optional) — Authentication token. Will default to the stored token.
  • 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.

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")

rename_discussion

< >

( repo_id: str discussion_num: int new_title: str token: Optional[str] = None repo_type: Optional[str] = None ) DiscussionTitleChange

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 (str, optional) — An authentication token (See https://huggingface.co/settings/token)

Returns

DiscussionTitleChange

the title change event

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 if the HuggingFace API returned an error
  • ValueError if some parameter value is invalid
  • 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.

repo_exists

< >

( repo_id: str repo_type: Optional[str] = None token: Optional[str] = None )

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 authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.

Checks if a repository exists on the Hugging Face Hub.

Examples:

>>> from huggingface_hub import repo_exists
>>> repo_exists("huggingface/transformers")
True
>>> repo_exists("huggingface/not-a-repo")
False

repo_info

< >

( repo_id: str revision: Optional[str] = None repo_type: Optional[str] = None timeout: Optional[float] = None files_metadata: bool = False token: Optional[Union[bool, str]] = None ) Union[SpaceInfo, DatasetInfo, ModelInfo]

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.
  • 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 authentication token (see https://huggingface.co/settings/token). If None or True and machine is logged in (through huggingface-cli login or login()), token will be retrieved from the cache. If False, token is not sent in the request header.

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.

Get the info object for a given repo of a given type.

Raises the following 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 If the revision to download from cannot be found.

request_space_hardware

< >

( repo_id: str hardware: SpaceHardware token: Optional[str] = None sleep_time: Optional[int] = None ) SpaceRuntime

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 (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.
  • 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

Runtime information about a Space including Space stage and hardware.

Request new hardware for a Space.

It is also possible to request hardware directly when creating the Space repo! See create_repo() for details.

request_space_storage

< >

( repo_id: str storage: SpaceStorage token: Optional[str] = None ) SpaceRuntime

Parameters

  • repo_id (str) — ID of the Space to update. Example: "HuggingFaceH4/open_llm_leaderboard".
  • storage (str or SpaceStorage) — Storage tier. Either ‘small’, ‘medium’, or ‘large’.
  • token (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.

Returns

SpaceRuntime

Runtime information about a Space including Space stage and hardware.

Request persistent storage for a Space.

It is not possible to decrease persistent storage after its granted. To do so, you must delete it via delete_space_storage().

restart_space

< >

( repo_id: str token: Optional[str] = None factory_reboot: bool = False ) SpaceRuntime

Parameters

  • repo_id (str) — ID of the Space to restart. Example: "Salesforce/BLIP2".
  • token (str, optional) — Hugging Face token. Will default to the locally saved token if not provided.
  • factory_reboot (bool, optional) — If True, the Space will be rebuilt from scratch without caching any requirements.

Returns

SpaceRuntime

Runtime information about your Space.

Raises

RepositoryNotFoundError or HfHubHTTPError or BadRequestError

  • RepositoryNotFoundError — If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you are not authenticated.
  • HfHubHTTPError — 403 Forbidden: only the owner of a Space can restart it. If you want to restart a Space that you don’t own, either ask the owner by opening a Discussion or duplicate the Space.
  • BadRequestError — If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide a static Space, you can set it to private.

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.

resume_inference_endpoint

< >

( name: str namespace: Optional[str] = None token: Optional[str] = None ) InferenceEndpoint

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.
  • token (str, optional) — An authentication token (See https://huggingface.co/settings/token).

Returns

InferenceEndpoint

information about the resumed Inference Endpoint.

Resume an Inference Endpoint.

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

run_as_future

<