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
< source >( endpoint: Optional[str] = None token: Union[str, bool, None] = None library_name: Optional[str] = None library_version: Optional[str] = None user_agent: Union[Dict, str, None] = None headers: Optional[Dict[str, str]] = None )
accept_access_request
< source >( repo_id: str user: str repo_type: Optional[str] = None token: Union[bool, str, None] = None )
Parameters
- repo_id (
str
) — The id of the repo to accept access request for. - user (
str
) — The username of the user which access request should be accepted. - repo_type (
str
, optional) — The type of the repo to accept access request for. Must be one ofmodel
,dataset
orspace
. Defaults tomodel
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Raises
HTTPError
HTTPError
— HTTP 400 if the repo is not gated.HTTPError
— HTTP 403 if you only have read-only access to the repo. This can be the case if you don’t havewrite
oradmin
role in the organization the repo belongs to or if you passed aread
token.HTTPError
— HTTP 404 if the user does not exist on the Hub.HTTPError
— HTTP 404 if the user access request cannot be found.HTTPError
— HTTP 404 if the user access request is already in the accepted list.
Accept an access request from a user for a given gated repo.
Once the request is accepted, the user will be able to download any file of the repo and access the community tab. If the approval mode is automatic, you don’t have to accept requests manually. An accepted request can be cancelled or rejected at any time using cancel_access_request() and reject_access_request().
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
add_collection_item
< source >( collection_slug: str item_id: str item_type: CollectionItemType_T note: Optional[str] = None exists_ok: bool = False token: Union[bool, str, None] = 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) — IfTrue
, do not raise an error if item already exists. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Raises
HTTPError
HTTPError
— HTTP 403 if you only have read-only access to the repo. This can be the case if you don’t havewrite
oradmin
role in the organization the repo belongs to or if you passed aread
token.HTTPError
— HTTP 404 if the item you try to add to the collection does not exist on the Hub.HTTPError
— HTTP 409 if the item you try to add to the collection is already in the collection (and exists_ok=False)
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
< source >( repo_id: str key: str value: str description: Optional[str] = None token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
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
< source >( repo_id: str key: str value: str description: Optional[str] = None token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
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
cancel_access_request
< source >( repo_id: str user: str repo_type: Optional[str] = None token: Union[bool, str, None] = None )
Parameters
- repo_id (
str
) — The id of the repo to cancel access request for. - user (
str
) — The username of the user which access request should be cancelled. - repo_type (
str
, optional) — The type of the repo to cancel access request for. Must be one ofmodel
,dataset
orspace
. Defaults tomodel
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Raises
HTTPError
HTTPError
— HTTP 400 if the repo is not gated.HTTPError
— HTTP 403 if you only have read-only access to the repo. This can be the case if you don’t havewrite
oradmin
role in the organization the repo belongs to or if you passed aread
token.HTTPError
— HTTP 404 if the user does not exist on the Hub.HTTPError
— HTTP 404 if the user access request cannot be found.HTTPError
— HTTP 404 if the user access request is already in the pending list.
Cancel an access request from a user for a given gated repo.
A cancelled request will go back to the pending list and the user will lose access to the repo.
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
change_discussion_status
< source >( repo_id: str discussion_num: int new_status: Literal['open', 'closed'] token: Union[bool, str, None] = 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 isNone
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
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 errorValueError
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
< source >( repo_id: str discussion_num: int comment: str token: Union[bool, str, None] = 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 isNone
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
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 errorValueError
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
< source >( repo_id: str branch: str revision: Optional[str] = None token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - 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 isNone
. - exist_ok (
bool
, optional, defaults toFalse
) — IfTrue
, 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 toFalse
.
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
< source >( title: str namespace: Optional[str] = None description: Optional[str] = None private: bool = False exists_ok: bool = False token: Union[bool, str, None] = 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 toFalse
(i.e. public collection). - exists_ok (
bool
, optional) — IfTrue
, do not raise an error if collection already exists. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Create a new Collection on the Hub.
Returns: Collection
create_commit
< source >( repo_id: str operations: Iterable[CommitOperation] commit_message: str commit_description: Optional[str] = None token: Union[str, bool, None] = 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
ofCommitOperation()
) — An iterable of operations to include in the commit, either:- CommitOperationAdd to upload a file
- CommitOperationDelete to delete a file
- CommitOperationCopy to copy a file
Operation objects will be mutated to include information relative to the upload. Do not reuse the same objects for multiple commits.
- commit_message (
str
) — The summary (first line) of the commit that will be created. - commit_description (
str
, optional) — The description of the commit that will be created - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - 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 isNone
. - 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 toFalse
. Ifrevision
is not set, PR is opened against the"main"
branch. Ifrevision
is set and is a branch, PR is opened against this branch. Ifrevision
is set and is not a branch name (example: a commit oid), anRevisionNotFoundError
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 andcreate_pr
isFalse
, the commit will fail ifrevision
does not point toparent_commit
. If specified andcreate_pr
isTrue
, the pull request will be created fromparent_commit
. Specifyingparent_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. Passingrun_as_future=True
will return a Future object. Defaults toFalse
.
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 a README.md file with an invalid metadata section is committed. In this case, the commit will fail early, before trying to upload any file.ValueError
— Ifcreate_pr
isTrue
and revision is neitherNone
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
< source >( repo_id: str addition_commits: List[List[CommitOperationAdd]] deletion_commits: List[List[CommitOperationDelete]] commit_message: str commit_description: Optional[str] = None token: Union[str, bool, None] = 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
ofList
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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - 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 isNone
. - merge_pr (
bool
) — If set toTrue
, the Pull Request is merged at the end of the process. Defaults toTrue
. - num_threads (
int
, optional) — Number of concurrent threads for uploading files. Defaults to 5. - verbose (
bool
) — If set toTrue
, process will run on verbose mode i.e. print information about the ongoing tasks. Defaults toFalse
.
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
< source >( repo_id: str title: str token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - 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. IfTrue
, creates a Pull Request. IfFalse
, creates a discussion. Defaults toFalse
. - 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 isNone
.
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 errorValueError
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
< source >( 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 custom_image: Optional[Dict] = None type: InferenceEndpointType = <InferenceEndpointType.PROTECTED: 'protected'> namespace: Optional[str] = None token: Union[bool, str, None] = 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."x4"
). - instance_type (
str
) — The cloud instance type where the Inference Endpoint will be deployed (e.g."intel-icl"
). - region (
str
) — The cloud region in which the Inference Endpoint will be created (e.g."us-east-1"
). - vendor (
str
) — The cloud provider or vendor where the Inference Endpoint will be hosted (e.g."aws"
). - account_id (
str
, optional) — The account ID used to link a VPC to a private Inference Endpoint (if applicable). - min_replica (
int
, optional) — The minimum number of replicas (instances) to keep running for the Inference Endpoint. 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"
). - custom_image (
Dict
, optional) — A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an Inference Endpoint running on thetext-generation-inference
(TGI) framework (see examples). - 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
information about the updated Inference Endpoint.
Create a new Inference Endpoint.
Example:
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.create_inference_endpoint(
... "my-endpoint-name",
... repository="gpt2",
... framework="pytorch",
... task="text-generation",
... accelerator="cpu",
... vendor="aws",
... region="us-east-1",
... type="protected",
... instance_size="x2",
... instance_type="intel-icl",
... )
>>> endpoint
InferenceEndpoint(name='my-endpoint-name', status="pending",...)
# Run inference on the endpoint
>>> endpoint.client.text_generation(...)
"..."
# Start an Inference Endpoint running Zephyr-7b-beta on TGI
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.create_inference_endpoint(
... "aws-zephyr-7b-beta-0486",
... repository="HuggingFaceH4/zephyr-7b-beta",
... framework="pytorch",
... task="text-generation",
... accelerator="gpu",
... vendor="aws",
... region="us-east-1",
... type="protected",
... instance_size="x1",
... instance_type="nvidia-a10g",
... custom_image={
... "health_route": "/health",
... "env": {
... "MAX_BATCH_PREFILL_TOKENS": "2048",
... "MAX_INPUT_LENGTH": "1024",
... "MAX_TOTAL_TOKENS": "1512",
... "MODEL_ID": "/repository"
... },
... "url": "ghcr.io/huggingface/text-generation-inference:1.1.0",
... },
... )
create_pull_request
< source >( repo_id: str title: str token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - 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 isNone
.
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 errorValueError
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
< source >( repo_id: str token: Union[str, bool, None] = None private: bool = False repo_type: Optional[str] = None exist_ok: bool = False resource_group_id: Optional[str] = None 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - private (
bool
, optional, defaults toFalse
) — 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 isNone
. - exist_ok (
bool
, optional, defaults toFalse
) — IfTrue
, do not raise an error if repo already exists. - resource_group_id (
str
, optional) — Resource group in which to create the repo. Resource groups is only available for organizations and allow to define which members of the organization can access the resource. The ID of a resource group can be found in the URL of the resource’s page on the Hub (e.g."66670e5163145ca562cb1988"
). To learn more about resource groups, see https://huggingface.co/docs/hub/en/security-resource-groups. - space_sdk (
str
, optional) — Choice of SDK to use if repo_type is “space”. Can be “streamlit”, “gradio”, “docker”, or “static”. - space_hardware (
SpaceHardware
orstr
, optional) — Choice of Hardware if repo_type is “space”. See SpaceHardware for a complete list. - space_storage (
SpaceStorage
orstr
, 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
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
< source >( repo_id: str tag: str tag_message: Optional[str] = None revision: Optional[str] = None token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - repo_type (
str
, optional) — Set to"dataset"
or"space"
if tagging a dataset or space,None
or"model"
if tagging a model. Default isNone
. - exist_ok (
bool
, optional, defaults toFalse
) — IfTrue
, 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 toFalse
.
Tag a given commit of a repo on the Hub.
create_webhook
< source >( url: str watched: List[Union[Dict, WebhookWatchedItem]] domains: Optional[List[WEBHOOK_DOMAIN_T]] = None secret: Optional[str] = None token: Union[bool, str, None] = None ) → WebhookInfo
Parameters
- url (
str
) — URL to send the payload to. - watched (
List[WebhookWatchedItem]
) — List of WebhookWatchedItem to be watched by the webhook. It can be users, orgs, models, datasets or spaces. Watched items can also be provided as plain dictionaries. - domains (
List[Literal["repo", "discussion"]]
, optional) — List of domains to watch. It can be “repo”, “discussion” or both. - secret (
str
, optional) — A secret to sign the payload with. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved token, which is the recommended
method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
Info about the newly created webhook.
Create a new webhook.
Example:
>>> from huggingface_hub import create_webhook
>>> payload = create_webhook(
... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
... url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
... domains=["repo", "discussion"],
... secret="my-secret",
... )
>>> print(payload)
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
domains=["repo", "discussion"],
secret="my-secret",
disabled=False,
)
dataset_info
< source >( repo_id: str revision: Optional[str] = None timeout: Optional[float] = None files_metadata: bool = False expand: Optional[List[ExpandDatasetProperty_T]] = None token: Union[bool, str, None] = 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 toFalse
. - expand (
List[ExpandDatasetProperty_T]
, optional) — List properties to return in the response. When used, only the properties in the list will be returned. This parameter cannot be used iffiles_metadata
is passed. Possible values are"author"
,"cardData"
,"citation"
,"createdAt"
,"disabled"
,"description"
,"downloads"
,"downloadsAllTime"
,"gated"
,"lastModified"
,"likes"
,"paperswithcode_id"
,"private"
,"siblings"
,"sha"
and"tags"
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
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
< source >( repo_id: str branch: str token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - 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 isNone
.
Raises
- 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
< source >( collection_slug: str missing_ok: bool = False token: Union[bool, str, None] = None )
Parameters
- collection_slug (
str
) — Slug of the collection to delete. Example:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"
. - missing_ok (
bool
, optional) — IfTrue
, do not raise an error if collection doesn’t exists. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
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
< source >( collection_slug: str item_object_id: str missing_ok: bool = False token: Union[bool, str, None] = 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) — IfTrue
, do not raise an error if item doesn’t exists. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
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
< source >( path_in_repo: str repo_id: str token: Union[str, bool, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - 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 isNone
. - 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 tof"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 toFalse
. Ifrevision
is not set, PR is opened against the"main"
branch. Ifrevision
is set and is a branch, PR is opened against this branch. Ifrevision
is set and is not a branch name (example: a commit oid), anRevisionNotFoundError
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 andcreate_pr
isFalse
, the commit will fail ifrevision
does not point toparent_commit
. If specified andcreate_pr
isTrue
, the pull request will be created fromparent_commit
. Specifyingparent_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:
HTTPError
if the HuggingFace API returned an errorValueError
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. - RevisionNotFoundError If the revision to download from cannot be found.
- EntryNotFoundError If the file to download cannot be found.
delete_files
< source >( repo_id: str delete_patterns: List[str] token: Union[bool, str, None] = 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
- repo_id (
str
) — The repository from which the folder will be deleted, for example:"username/custom_transformers"
- delete_patterns (
List[str]
) — List of files or folders to delete. Each string can either be a file path, a folder path or a Unix shell-style wildcard. E.g.["file.txt", "folder/", "data/*.parquet"]
- token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. to the stored token. - repo_type (
str
, optional) — Type of the repo to delete files from. Can be"model"
,"dataset"
or"space"
. Defaults to"model"
. - revision (
str
, optional) — The git revision to commit from. Defaults to the head of the"main"
branch. - commit_message (
str
, optional) — The summary (first line) of the generated commit. Defaults tof"Delete files using huggingface_hub"
. - commit_description (
str
optional) — The description of the generated commit. - create_pr (
boolean
, optional) — Whether or not to create a Pull Request with that commit. Defaults toFalse
. Ifrevision
is not set, PR is opened against the"main"
branch. Ifrevision
is set and is a branch, PR is opened against this branch. Ifrevision
is set and is not a branch name (example: a commit oid), anRevisionNotFoundError
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 andcreate_pr
isFalse
, the commit will fail ifrevision
does not point toparent_commit
. If specified andcreate_pr
isTrue
, the pull request will be created fromparent_commit
. Specifyingparent_commit
ensures the repo has not changed before committing the changes, and can be especially useful if the repo is updated / committed to concurrently.
Delete files from a repository on the Hub.
If a folder path is provided, the entire folder is deleted as well as all files it contained.
delete_folder
< source >( path_in_repo: str repo_id: str token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. 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 isNone
. - 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 tof"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 toFalse
. Ifrevision
is not set, PR is opened against the"main"
branch. Ifrevision
is set and is a branch, PR is opened against this branch. Ifrevision
is set and is not a branch name (example: a commit oid), anRevisionNotFoundError
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 andcreate_pr
isFalse
, the commit will fail ifrevision
does not point toparent_commit
. If specified andcreate_pr
isTrue
, the pull request will be created fromparent_commit
. Specifyingparent_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
< source >( name: str namespace: Optional[str] = None token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
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
< source >( repo_id: str token: Union[str, bool, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - 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 toFalse
) — IfTrue
, 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
< source >( repo_id: str key: str token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
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
< source >( repo_id: str token: Union[bool, str, None] = None ) → SpaceRuntime
Parameters
- repo_id (
str
) — ID of the Space to update. Example:"open-llm-leaderboard/open_llm_leaderboard"
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
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
< source >( repo_id: str key: str token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
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
< source >( repo_id: str tag: str token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - repo_type (
str
, optional) — Set to"dataset"
or"space"
if tagging a dataset or space,None
or"model"
if tagging a model. Default isNone
.
Raises
- RepositoryNotFoundError — If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo does not exist.
- RevisionNotFoundError — If tag is not found.
Delete a tag from a repo on the Hub.
delete_webhook
< source >( webhook_id: str token: Union[bool, str, None] = None ) → None
Parameters
- webhook_id (
str
) — The unique identifier of the webhook to delete. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved token, which is the recommended
method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
None
Delete a webhook.
disable_webhook
< source >( webhook_id: str token: Union[bool, str, None] = None ) → WebhookInfo
Parameters
- webhook_id (
str
) — The unique identifier of the webhook to disable. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved token, which is the recommended
method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
Info about the disabled webhook.
Disable a webhook (makes it “disabled”).
Example:
>>> from huggingface_hub import disable_webhook
>>> disabled_webhook = disable_webhook("654bbbc16f2ec14d77f109cc")
>>> disabled_webhook
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
domains=["repo", "discussion"],
secret="my-secret",
disabled=True,
)
duplicate_space
< source >( from_id: str to_id: Optional[str] = None private: Optional[bool] = None token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - exist_ok (
bool
, optional, defaults toFalse
) — IfTrue
, do not raise an error if repo already exists. - hardware (
SpaceHardware
orstr
, optional) — Choice of Hardware. Example:"t4-medium"
. See SpaceHardware for a complete list. - storage (
SpaceStorage
orstr
, 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
URL to the newly created repo. Value is a subclass of str
containing
attributes like endpoint
, repo_type
and repo_id
.
Raises
RepositoryNotFoundError or HTTPError
- RepositoryNotFoundError —
If one of
from_id
orto_id
cannot be found. This may be because it doesn’t exist, or because it is set toprivate
and you do not have access. HTTPError
— If the HuggingFace API returned an error
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
< source >( repo_id: str discussion_num: int comment_id: str new_content: str token: Union[bool, str, None] = 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 isNone
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
the edited comment
Edits a comment on a Discussion / Pull Request.
Raises the following errors:
HTTPError
if the HuggingFace API returned an errorValueError
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.
enable_webhook
< source >( webhook_id: str token: Union[bool, str, None] = None ) → WebhookInfo
Parameters
- webhook_id (
str
) — The unique identifier of the webhook to enable. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved token, which is the recommended
method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
Info about the enabled webhook.
Enable a webhook (makes it “active”).
Example:
>>> from huggingface_hub import enable_webhook
>>> enabled_webhook = enable_webhook("654bbbc16f2ec14d77f109cc")
>>> enabled_webhook
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
domains=["repo", "discussion"],
secret="my-secret",
disabled=False,
)
file_exists
< source >( repo_id: str filename: str repo_type: Optional[str] = None revision: Optional[str] = None token: Union[str, bool, None] = 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 isNone
. - revision (
str
, optional) — The revision of the repository from which to get the information. Defaults to"main"
branch. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Checks if a file exists in a repository on the Hugging Face Hub.
get_collection
< source >( collection_slug: str token: Union[bool, str, None] = None )
Parameters
- collection_slug (
str
) — Slug of the collection of the Hub. Example:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
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
)
List all valid dataset tags as a nested namespace object.
get_discussion_details
< source >( repo_id: str discussion_num: int repo_type: Optional[str] = None token: Union[bool, str, None] = 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 isNone
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Fetches a Discussion’s / Pull Request ‘s details from the Hub.
Returns: DiscussionWithDetails
Raises the following errors:
HTTPError
if the HuggingFace API returned an errorValueError
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
< source >( model_id: str organization: Optional[str] = None token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
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_hf_file_metadata
< source >( url: str token: Union[bool, str, None] = None proxies: Optional[Dict] = None timeout: Optional[float] = 10 )
Parameters
- url (
str
) — File url, for example returned by hf_hub_url(). - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - proxies (
dict
, optional) — Dictionary mapping protocol to the URL of the proxy passed torequests.request
. - timeout (
float
, optional, defaults to 10) — How many seconds to wait for the server to send metadata before giving up.
Fetch metadata of a file versioned on the Hub for a given url.
get_inference_endpoint
< source >( name: str namespace: Optional[str] = None token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
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(...)
List all valid model tags as a nested namespace object
get_paths_info
< source >( repo_id: str paths: Union[List[str], str] expand: bool = False revision: Optional[str] = None repo_type: Optional[str] = None token: Union[str, bool, None] = None ) → List[Union[RepoFile, RepoFolder]]
Parameters
- repo_id (
str
) — A namespace (user or an organization) and a repo name separated by a/
. - paths (
Union[List[str], str]
, optional) — The paths to get information about. If a path do not exist, it is ignored without raising an exception. - expand (
bool
, optional, defaults toFalse
) — Whether to fetch more information about the paths (e.g. last commit and files’ security scan results). This operation is more expensive for the server so only 50 results are returned per page (instead of 1000). As pagination is implemented inhuggingface_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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
List[Union[RepoFile, RepoFolder]]
The information about the paths, as a list of RepoFile
and RepoFolder
objects.
Raises
- 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 information about a repo’s paths.
Example:
>>> from huggingface_hub import get_paths_info
>>> paths_info = get_paths_info("allenai/c4", ["README.md", "en"], repo_type="dataset")
>>> paths_info
[
RepoFile(path='README.md', size=2379, blob_id='f84cb4c97182890fc1dbdeaf1a6a468fd27b4fff', lfs=None, last_commit=None, security=None),
RepoFolder(path='en', tree_id='dc943c4c40f53d02b31ced1defa7e5f438d5862e', last_commit=None)
]
get_repo_discussions
< source >( repo_id: str author: Optional[str] = None discussion_type: Optional[DiscussionTypeFilter] = None discussion_status: Optional[DiscussionStatusFilter] = None repo_type: Optional[str] = None token: Union[bool, str, None] = None ) → Iterator[Discussion]
Parameters
- repo_id (
str
) — A namespace (user or an organization) and a repo name separated by a/
. - author (
str
, optional) — Pass a value to filter by discussion author.None
means no filter. Default isNone
. - discussion_type (
str
, optional) — Set to"pull_request"
to fetch only pull requests,"discussion"
to fetch only discussions. Set to"all"
orNone
to fetch both. Default isNone
. - discussion_status (
str
, optional) — Set to"open"
(respectively"closed"
) to fetch only open (respectively closed) discussions. Set to"all"
orNone
to fetch both. Default isNone
. - 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 isNone
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
Iterator[Discussion]
An iterator of Discussion objects.
Fetches Discussions and Pull Requests for the given repo.
Example:
get_safetensors_metadata
< source >( repo_id: str repo_type: Optional[str] = None revision: Optional[str] = None token: Union[bool, str, None] = None ) → SafetensorsRepoMetadata
Parameters
- repo_id (
str
) — A user or an organization name and a repo name separated by a/
. - filename (
str
) — The name of the file in the repo. - repo_type (
str
, optional) — Set to"dataset"
or"space"
if the file is in a dataset or space,None
or"model"
if in a model. Default isNone
. - revision (
str
, optional) — The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the head of the"main"
branch. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
SafetensorsRepoMetadata
information related to safetensors repo.
Raises
NotASafetensorsRepoError
or SafetensorsParsingError
NotASafetensorsRepoError
— If the repo is not a safetensors repo i.e. doesn’t have either amodel.safetensors
or amodel.safetensors.index.json
file.SafetensorsParsingError
— If a safetensors file header couldn’t be parsed correctly.
Parse metadata for a safetensors repo on the Hub.
We first check if the repo has a single safetensors file or a sharded safetensors repo. If it’s a single safetensors file, we parse the metadata from this file. If it’s a sharded safetensors repo, we parse the metadata from the index file and then parse the metadata from each shard.
To parse metadata from a single safetensors file, use parse_safetensors_file_metadata().
For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format.
Example:
# Parse repo with single weights file
>>> metadata = get_safetensors_metadata("bigscience/bloomz-560m")
>>> metadata
SafetensorsRepoMetadata(
metadata=None,
sharded=False,
weight_map={'h.0.input_layernorm.bias': 'model.safetensors', ...},
files_metadata={'model.safetensors': SafetensorsFileMetadata(...)}
)
>>> metadata.files_metadata["model.safetensors"].metadata
{'format': 'pt'}
# Parse repo with sharded model
>>> metadata = get_safetensors_metadata("bigscience/bloom")
Parse safetensors files: 100%|██████████████████████████████████████████| 72/72 [00:12<00:00, 5.78it/s]
>>> metadata
SafetensorsRepoMetadata(metadata={'total_size': 352494542848}, sharded=True, weight_map={...}, files_metadata={...})
>>> len(metadata.files_metadata)
72 # All safetensors files have been fetched
# Parse repo with sharded model
>>> get_safetensors_metadata("runwayml/stable-diffusion-v1-5")
NotASafetensorsRepoError: 'runwayml/stable-diffusion-v1-5' is not a safetensors repo. Couldn't find 'model.safetensors.index.json' or 'model.safetensors' files.
get_space_runtime
< source >( repo_id: str token: Union[bool, str, None] = None ) → SpaceRuntime
Parameters
- repo_id (
str
) — ID of the repo to update. Example:"bigcode/in-the-stack"
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
Runtime information about a Space including Space stage and hardware.
Gets runtime information about a Space.
get_space_variables
< source >( repo_id: str token: Union[bool, str, None] = None )
Parameters
- repo_id (
str
) — ID of the repo to query. Example:"bigcode/in-the-stack"
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
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
< source >( token: Union[bool, str, None] = None ) → Literal["read", "write", None]
Parameters
- token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
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.
get_user_overview
< source >( username: str ) → User
Get an overview of a user on the Hub.
get_webhook
< source >( webhook_id: str token: Union[bool, str, None] = None ) → WebhookInfo
Parameters
- webhook_id (
str
) — The unique identifier of the webhook to get. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved token, which is the recommended
method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
Info about the webhook.
Get a webhook by its id.
Example:
>>> from huggingface_hub import get_webhook
>>> webhook = get_webhook("654bbbc16f2ec14d77f109cc")
>>> print(webhook)
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
secret="my-secret",
domains=["repo", "discussion"],
disabled=False,
)
grant_access
< source >( repo_id: str user: str repo_type: Optional[str] = None token: Union[bool, str, None] = None )
Parameters
- repo_id (
str
) — The id of the repo to grant access to. - user (
str
) — The username of the user to grant access. - repo_type (
str
, optional) — The type of the repo to grant access to. Must be one ofmodel
,dataset
orspace
. Defaults tomodel
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Raises
HTTPError
HTTPError
— HTTP 400 if the repo is not gated.HTTPError
— HTTP 400 if the user already has access to the repo.HTTPError
— HTTP 403 if you only have read-only access to the repo. This can be the case if you don’t havewrite
oradmin
role in the organization the repo belongs to or if you passed aread
token.HTTPError
— HTTP 404 if the user does not exist on the Hub.
Grant access to a user for a given gated repo.
Granting access don’t require for the user to send an access request by themselves. The user is automatically added to the accepted list meaning they can download the files You can revoke the granted access at any time using cancel_access_request() or reject_access_request().
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
hf_hub_download
< source >( 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 force_download: bool = False proxies: Optional[Dict] = None etag_timeout: float = 10 token: Union[bool, str, None] = None local_files_only: bool = False resume_download: Optional[bool] = None legacy_cache_layout: bool = False force_filename: Optional[str] = None local_dir_use_symlinks: Union[bool, Literal['auto']] = 'auto' ) → str
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 isNone
. - 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
orPath
, optional) — If provided, the downloaded file will be placed under this directory. - force_download (
bool
, optional, defaults toFalse
) — 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 torequests.request
. - etag_timeout (
float
, optional, defaults to10
) — When fetching ETag, how many seconds to wait for the server to send data before giving up which is passed torequests.request
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - local_files_only (
bool
, optional, defaults toFalse
) — IfTrue
, avoid downloading the file and return the path to the local cached file if it exists.
Returns
str
Local path of file or if networking is off, last version of file cached on disk.
Raises
RepositoryNotFoundError or RevisionNotFoundError or EntryNotFoundError or LocalEntryNotFoundError or EnvironmentError
or OSError
or ValueError
- 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.
- EntryNotFoundError — If the file to download cannot be found.
- LocalEntryNotFoundError — If network is disabled or unavailable and file is not found in cache.
EnvironmentError
— Iftoken=True
but the token cannot be found.OSError
— If ETag cannot be determined.ValueError
— If some parameter value is invalid.
Download a given file if it’s not already present in the local cache.
The new cache file layout looks like this:
- The cache directory contains one subfolder per repo_id (namespaced by repo type)
- inside each repo folder:
- refs is a list of the latest known revision => commit_hash pairs
- blobs contains the actual file blobs (identified by their git-sha or sha256, depending on whether they’re LFS files or not)
- snapshots contains one subfolder per commit, each “commit” contains the subset of the files that have been resolved at that particular commit. Each filename is a symlink to the blob at that particular commit.
[ 96] .
└── [ 160] models--julien-c--EsperBERTo-small
├── [ 160] blobs
│ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
│ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e
│ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812
├── [ 96] refs
│ └── [ 40] main
└── [ 128] snapshots
├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
│ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
│ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
└── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48
├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
└── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
If local_dir
is provided, the file structure from the repo will be replicated in this location. When using this
option, the cache_dir
will not be used and a .cache/huggingface/
folder will be created at the root of local_dir
to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
cache-system, it’s optimized for regularly pulling the latest version of a repository.
hide_discussion_comment
< source >( repo_id: str discussion_num: int comment_id: str token: Union[bool, str, None] = 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 isNone
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
the hidden comment
Hides a comment on a Discussion / Pull Request.
Raises the following errors:
HTTPError
if the HuggingFace API returned an errorValueError
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
< source >( repo_id: str token: Union[bool, str, None] = None repo_type: Optional[str] = None )
Parameters
- repo_id (
str
) — The repository to like. Example:"user/my-cool-model"
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
. - repo_type (
str
, optional) — Set to"dataset"
or"space"
if liking a dataset or space,None
or"model"
if liking a model. Default isNone
.
Raises
- 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().
list_accepted_access_requests
< source >( repo_id: str repo_type: Optional[str] = None token: Union[bool, str, None] = None ) → List[AccessRequest]
Parameters
- repo_id (
str
) — The id of the repo to get access requests for. - repo_type (
str
, optional) — The type of the repo to get access requests for. Must be one ofmodel
,dataset
orspace
. Defaults tomodel
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
List[AccessRequest]
A list of AccessRequest
objects. Each time contains a username
, email
,
status
and timestamp
attribute. If the gated repo has a custom form, the fields
attribute will
be populated with user’s answers.
Raises
HTTPError
Get accepted access requests for a given gated repo.
An accepted request means the user has requested access to the repo and the request has been accepted. The user can download any file of the repo. If the approval mode is automatic, this list should contains by default all requests. Accepted requests can be cancelled or rejected at any time using cancel_access_request() and reject_access_request(). A cancelled request will go back to the pending list while a rejected request will go to the rejected list. In both cases, the user will lose access to the repo.
For more info about gated repos, see https://huggingface.co/docs/hub/models-gated.
Example:
>>> from huggingface_hub import list_accepted_access_requests
>>> requests = list_accepted_access_requests("meta-llama/Llama-2-7b")
>>> len(requests)
411
>>> requests[0]
[
AccessRequest(
username='clem',
fullname='Clem 🤗',
email='***',
timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
status='accepted',
fields=None,
),
...
]
list_collections
< source >( owner: Union[List[str], str, None] = None item: Union[List[str], str, None] = None sort: Optional[Literal['lastModified', 'trending', 'upvotes']] = None limit: Optional[int] = None token: Union[bool, str, None] = None ) → Iterable[Collection]
Parameters
- owner (
List[str]
orstr
, optional) — Filter by owner’s username. - item (
List[str]
orstr
, optional) — Filter collections containing a particular items. Example:"models/teknium/OpenHermes-2.5-Mistral-7B"
,"datasets/squad"
or"papers/2311.12983"
. - sort (
Literal["lastModified", "trending", "upvotes"]
, optional) — Sort collections by last modified, trending or upvotes. - limit (
int
, optional) — Maximum number of collections to be returned. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
Iterable[Collection]
an iterable of Collection objects.
List collections on the Huggingface Hub, given some filters.
When listing collections, the item list per collection is truncated to 4 items maximum. To retrieve all items from a collection, you must use get_collection().
list_datasets
< source >( filter: Union[str, Iterable[str], None] = None author: Optional[str] = None benchmark: Optional[Union[str, List[str]]] = None dataset_name: Optional[str] = None language_creators: Optional[Union[str, List[str]]] = None language: Optional[Union[str, List[str]]] = None multilinguality: Optional[Union[str, List[str]]] = None size_categories: Optional[Union[str, List[str]]] = None tags: Optional[Union[str, List[str]]] = None task_categories: Optional[Union[str, List[str]]] = None task_ids: Optional[Union[str, List[str]]] = None search: Optional[str] = None sort: Optional[Union[Literal['last_modified'], str]] = None direction: Optional[Literal[-1]] = None limit: Optional[int] = None expand: Optional[List[ExpandDatasetProperty_T]] = None full: Optional[bool] = None token: Union[bool, str, None] = None ) → Iterable[DatasetInfo]
Parameters
- filter (
str
orIterable[str]
, optional) — A string or list of string to filter datasets on the hub. - author (
str
, optional) — A string which identify the author of the returned datasets. - benchmark (
str
orList
, optional) — A string or list of strings that can be used to identify datasets on the Hub by their official benchmark. - dataset_name (
str
, optional) — A string or list of strings that can be used to identify datasets on the Hub by its name, such asSQAC
orwikineural
- language_creators (
str
orList
, optional) — A string or list of strings that can be used to identify datasets on the Hub with how the data was curated, such ascrowdsourced
ormachine_generated
. - language (
str
orList
, optional) — A string or list of strings representing a two-character language to filter datasets by on the Hub. - multilinguality (
str
orList
, optional) — A string or list of strings representing a filter for datasets that contain multiple languages. - size_categories (
str
orList
, optional) — A string or list of strings that can be used to identify datasets on the Hub by the size of the dataset such as100K<n<1M
or1M<n<10M
. - tags (
str
orList
, optional) — A string tag or a list of tags to filter datasets on the Hub. - task_categories (
str
orList
, optional) — A string or list of strings that can be used to identify datasets on the Hub by the designed task, such asaudio_classification
ornamed_entity_recognition
. - task_ids (
str
orList
, optional) — A string or list of strings that can be used to identify datasets on the Hub by the specific task such asspeech_emotion_recognition
orparaphrase
. - search (
str
, optional) — A string that will be contained in the returned datasets. - sort (
Literal["last_modified"]
orstr
, 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]
orint
, 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 toNone
fetches all datasets. - expand (
List[ExpandDatasetProperty_T]
, optional) — List properties to return in the response. When used, only the properties in the list will be returned. This parameter cannot be used iffull
is passed. Possible values are"author"
,"cardData"
,"citation"
,"createdAt"
,"disabled"
,"description"
,"downloads"
,"downloadsAllTime"
,"gated"
,"lastModified"
,"likes"
,"paperswithcode_id"
,"private"
,"siblings"
,"sha"
and"tags"
. - full (
bool
, optional) — Whether to fetch all dataset data, including thelast_modified
, thecard_data
and the files. Can contain useful information such as the PapersWithCode ID. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
Iterable[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")
# List only the datasets in russian for language modeling
>>> api.list_datasets(
... filter=("language:ru", "task_ids:language-modeling")
... )
# List FiftyOne datasets (identified by the tag "fiftyone" in dataset card)
>>> api.list_datasets(tags="fiftyone")
list_inference_endpoints
< source >( namespace: Optional[str] = None token: Union[bool, str, None] = 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 (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
A list of all inference endpoints for the given namespace.
Lists all inference endpoints for the given namespace.
list_liked_repos
< source >( user: Optional[str] = None token: Union[bool, str, None] = None ) → UserLikes
Parameters
- user (
str
, optional) — Name of the user for which you want to fetch the likes. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
object containing the user name and 3 lists of repo ids (1 for models, 1 for datasets and 1 for Spaces).
Raises
ValueError
ValueError
— Ifuser
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.
list_metrics
< source >( ) → List[MetricInfo]
Returns
List[MetricInfo]
a list of MetricInfo
objects which.
Get the public list of all the metrics on huggingface.co
list_models
< source >( filter: Union[str, Iterable[str], None] = None author: Optional[str] = None library: Optional[Union[str, List[str]]] = None language: Optional[Union[str, List[str]]] = None model_name: Optional[str] = None task: Optional[Union[str, List[str]]] = None trained_dataset: Optional[Union[str, List[str]]] = None tags: Optional[Union[str, List[str]]] = None search: Optional[str] = None pipeline_tag: 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 expand: Optional[List[ExpandModelProperty_T]] = None full: Optional[bool] = None cardData: bool = False fetch_config: bool = False token: Union[bool, str, None] = None ) → Iterable[ModelInfo]
Parameters
- filter (
str
orIterable[str]
, optional) — A string or list of string to filter models on the Hub. - author (
str
, optional) — A string which identify the author (user or organization) of the returned models - library (
str
orList
, optional) — A string or list of strings of foundational libraries models were originally trained from, such as pytorch, tensorflow, or allennlp. - language (
str
orList
, optional) — A string or list of strings of languages, both by name and country code, such as “en” or “English” - model_name (
str
, optional) — A string that contain complete or partial names for models on the Hub, such as “bert” or “bert-base-cased” - task (
str
orList
, optional) — A string or list of strings of tasks models were designed for, such as: “fill-mask” or “automatic-speech-recognition” - trained_dataset (
str
orList
, optional) — A string tag or a list of string tags of the trained dataset for a model on the Hub. - tags (
str
orList
, optional) — A string tag or a list of tags to filter models on the Hub by, such astext-generation
orspacy
. - search (
str
, optional) — A string that will be contained in the returned model ids. - pipeline_tag (
str
, optional) — A string pipeline tag to filter models on the Hub by, such assummarization
. - 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"]
orstr
, 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]
orint
, 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 toNone
fetches all models. - expand (
List[ExpandModelProperty_T]
, optional) — List properties to return in the response. When used, only the properties in the list will be returned. This parameter cannot be used iffull
,cardData
orfetch_config
are passed. Possible values are"author"
,"cardData"
,"config"
,"createdAt"
,"disabled"
,"downloads"
,"downloadsAllTime"
,"gated"
,"inference"
,"lastModified"
,"library_name"
,"likes"
,"mask_token"
,"model-index"
,"pipeline_tag"
,"private"
,"safetensors"
,"sha"
,"siblings"
,"spaces"
,"tags"
,"transformersInfo"
and"widgetData"
. - full (
bool
, optional) — Whether to fetch all model data, including thelast_modified
, thesha
, the files and thetags
. This is set toTrue
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 infull
due to its size. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
Iterable[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")
# List only models from the AllenNLP library
>>> api.list_models(filter="allennlp")
list_organization_members
< source >( organization: str ) → Iterable[User]
List of members of an organization on the Hub.
list_pending_access_requests
< source >( repo_id: str repo_type: Optional[str] = None token: Union[bool, str, None] = None ) → List[AccessRequest]
Parameters
- repo_id (
str
) — The id of the repo to get access requests for. - repo_type (
str
, optional) — The type of the repo to get access requests for. Must be one ofmodel
,dataset
orspace
. Defaults tomodel
. - token (Union[bool, str, None], optional) —
A valid user access token (string). Defaults to the locally saved
token, which is the recommended method for authentication (see
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
To disable authentication, pass
False
.
Returns
List[AccessRequest]
A list of AccessRequest
objects. Each time contains a username
, email
,
status
and timestamp
attribute. If the gated repo has a custom form, the fields
attribute will
be populated with user’s answers.
Raises
HTTPError
HTTPError
— HTTP 400 if the repo is not