Hub Python Library documentation

HfApi 客户端

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

HfApi 客户端

以下是 HfApi 类的文档,它作为 Hugging Face Hub API 的 Python 封装。

HfApi 中的所有方法也可以直接从包的根级别访问。以下详细介绍了这两种方式。

使用 root 方法更为直接,但 HfApi 类提供了更高的灵活性。 具体来说,你可以传入一个令牌,该令牌将在所有 HTTP 调用中复用。这与 hf auth login 或 login() 不同,因为令牌不会持久化到机器上。 你还可以提供不同的端点或配置自定义的 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

类 huggingface_hub.HfApi

< >

( endpoint: str | None = Nonetoken: str | bool | None = Nonelibrary_name: str | None = Nonelibrary_version: str | None = Noneuser_agent: dict | str | None = Noneheaders: dict[str, str] | None = None )

参数

  • endpoint (str,可选) — Hub 的端点。默认为 https://huggingface.co。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • library_name (str, 可选) — 发起 HTTP 请求的库的名称。将被添加到 user-agent 请求头中。示例:"transformers"。
  • library_version (str, 可选) — 发起 HTTP 请求的库的版本。该值将被添加到 user-agent 请求头中。示例:"4.24.0"。
  • user_agent (str, dict, 可选) — 以字典或单个字符串形式提供的用户代理信息。它将与已安装软件包的相关信息一起补全。
  • headers (dict, 可选) — 随每个请求发送的附加请求头。示例:{"X-My-Header": "value"}。 在此处传递的请求头优先于默认请求头。

用于通过 HTTP 与 Hugging Face Hub 交互的客户端。

客户端使用一些高级设置进行初始化,这些设置会应用于向 Hub 发出的所有请求(HF 端点、身份验证、用户代理等)。建议使用 HfApi 客户端,但这并非强制要求,因为其所有公开方法都直接暴露在 huggingface_hub 的根级别。

accept_access_request

< >

( repo_id: struser: str | None = Nonerequest_id: str | None = Nonerepo_type: str | None = Nonetoken: bool | str | None = None )

参数

  • repo_id (str) — 要接受访问请求的仓库的 id。
  • user (str, 可选) — 应接受其访问请求的用户名。必须且只能提供 user 或 request_id 中的一个。
  • request_id (str, 可选) — 要接受的访问请求的 id(参见 AccessRequest)。当仓库配置为不共享请求者用户名时,此项为必填。必须且只能提供 user 或 request_id 其中之一。
  • repo_type (str, 可选) — 要接受访问请求的仓库类型。必须是 model、dataset 或 space 之一。 默认为 model。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果仓库未开放访问,则返回 HTTP 400。
  • HfHubHTTPError — 如果您仅对仓库具有只读访问权限,则会返回 HTTP 403。如果您在仓库所属的组织中没有 write 或 admin 角色,或者您传递了 read 令牌,就可能出现这种情况。
  • HfHubHTTPError — 如果该用户在 Hub 上不存在,则返回 HTTP 404。
  • HfHubHTTPError — 如果找不到用户的访问请求,则返回 HTTP 404。
  • HfHubHTTPError — 如果用户的访问请求已在接受列表中,则返回 HTTP 404。

接受用户对指定受限仓库的访问请求。

请求被接受后,用户即可下载该仓库中的任意文件并访问社区标签页。如果审批模式为自动,则无需手动接受请求。已接受的请求可随时使用 cancel_access_request() 和 reject_access_request() 进行取消或拒绝。

有关受控仓库的更多信息,请参阅 https://huggingface.co/docs/hub/models-gated。

add_collection_item

< >

( collection_slug: stritem_id: stritem_type: CollectionItemType_Tnote: str | None = Noneexists_ok: bool = Falsetoken: bool | str | None = None )

参数

  • collection_slug (str) — 要更新的集合的 Slug。示例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。
  • item_id (str) — 要添加到集合中的项目的 ID。对于仓库/空间/数据集,请使用 repo_id;对于论文,请使用论文 ID;对于另一个集合,请使用其 slug(例如 "moonshotai/kimi-k2");或者使用桶 ID(例如 "namespace/bucket-name")。
  • item_type (str) — 要添加的项的类型。可以是 "model"、"dataset"、"space"、"paper"、"collection" 或 "bucket"。
  • note (str, 可选) — 要附加到集合中该项目的备注。备注的最大长度为 500 个字符。
  • exists_ok (bool, 可选) — 如果为 True,则当项目已存在时不引发错误。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果您仅对仓库具有只读访问权限,则会返回 HTTP 403。如果您在仓库所属的组织中没有 write 或 admin 角色,或者您传递了 read 令牌,就可能出现这种情况。
  • HfHubHTTPError — 如果您尝试添加到集合中的项目在 Hub 上不存在,则会返回 HTTP 404。
  • HfHubHTTPError — 如果您尝试添加到集合中的项目已存在于该集合中(且 exists_ok=False),则返回 HTTP 409

在 Hub 上的集合中添加一个项目。

返回:Collection

示例:

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

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

add_space_secret

< >

( repo_id: strkey: strvalue: strdescription: str | None = Nonetoken: bool | str | None = None )

参数

  • repo_id (str) — 要更新的仓库 ID。示例:"bigcode/in-the-stack"。
  • key (str) — 密钥。示例:"GITHUB_API_KEY"
  • value (str) — 密钥值。示例:"your_github_api_key"。
  • description (str, 可选) — 密钥描述。示例:"Github API key to access the Github API"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

在 Space 中添加或更新一个密钥。

Secrets 允许在不硬编码的情况下,为 Space 设置密钥或令牌。 有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。

add_space_variable

< >

( repo_id: strkey: strvalue: strdescription: str | None = Nonetoken: bool | str | None = None )

参数

  • repo_id (str) — 要更新的仓库 ID。示例:"bigcode/in-the-stack"。
  • key (str) — 变量键。示例:"MODEL_REPO_ID"
  • value (str) — 变量值。示例:"the_model_repo_id"。
  • description (str) — 变量的描述。示例:"Model Repo ID of the implemented model"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

在 Space 中添加或更新一个变量。

Variables 允许为 Space 设置环境变量,而无需将其硬编码。 有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables

auth_check

< >

( repo_id: strrepo_type: str | None = Nonetoken: bool | str | None = Nonewrite: bool = False )

参数

  • repo_id (str) — 要检查访问权限的仓库。格式应为 "user/repo_name"。 示例:"user/my-cool-model"。
  • repo_type (str, 可选) — 仓库的类型。应为 "model"、"dataset" 或 "space" 之一。 如果未指定,默认值为 "model"。
  • token (Union[bool, str, None], 可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
  • write (bool,可选) — 如果为 True,则检查用户是否具有该仓库的内容写入权限。 如果为 False(默认值),则仅检查读取权限。
  • RepositoryNotFoundError — 如果仓库不存在、为私有仓库,或用户没有访问权限,则会引发此错误。如果 repo_id 或 repo_type 不正确,或者仓库是私有的但用户未进行身份验证,则可能会发生此情况。

  • GatedRepoError — 如果仓库存在但受访问限制,且用户没有权限访问,则引发此错误。

检查提供的用户令牌是否有权访问 Hugging Face Hub 上的特定仓库。

此方法用于验证通过提供的令牌进行身份验证的用户是否有权访问指定的仓库。如果未找到该仓库,或者用户缺乏访问该仓库所需的权限,此方法将抛出相应的异常。

示例:

检查用户是否有权访问某个仓库:

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

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

在此示例中:

  • 如果用户拥有访问权限,该方法将成功完成。
  • 如果仓库受到访问限制或不存在,则会抛出相应的异常,以便用户进行相应处理。

batch_bucket_files

< >

( bucket_id: stradd: list[tuple[str | Path | bytes, str]] | None = Nonecopy: list[tuple[str, str, str, str]] | None = Nonedelete: list[str] | None = Nonetoken: str | bool | None = None )

参数

  • bucket_id (str) — 存储桶的 ID(例如 "username/my-bucket")。
  • add (list of tuple, 可选) — 要上传的文件。每个元素都是一个 (source, destination) 元组,其中 source 是本地文件的路径(str 或 Path)或原始 bytes 内容,destination 是存储桶中的路径。
  • copy (list 的 tuple, 可选) — 通过 xet 哈希复制的文件。每个元素是一个 (source_repo_type, source_repo_id, xet_hash, destination) 元组,其中:
    • source_repo_type 是源仓库的类型:"model"、"dataset"、"space" 或 "bucket"。
    • source_repo_id 是源仓库或存储桶的 ID(例如 "username/my-model")。
    • xet_hash 是待复制文件的 xet 哈希值。
    • destination 是存储桶中的目标路径。 这是一个服务器端操作——不会下载或重新上传任何数据。
  • delete (list of str, 可选) — 要从存储桶中删除的文件路径。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

引发

BucketBatchError

  • BucketBatchError — 如果服务器报告某些操作失败。该错误在所有操作都发送完毕后才会抛出,因此该批次中的其他操作已被应用。

在存储桶中添加、复制和/或删除文件。

这是一个非事务性操作。如果过程中发生错误,部分文件可能已被上传、复制或删除,而其他文件则未受影响。

示例:

>>> from huggingface_hub import batch_bucket_files

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

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

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

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

bucket_info

< >

( bucket_id: strtoken: bool | str | None = None ) → BucketInfo

参数

返回值

BucketInfo

桶信息。

引发

BucketNotFoundError 或 or

  • BucketNotFoundError — 如果找不到存储桶。这可能是因为它不存在,
  • or — 因为它被设置为 private,且您没有访问权限。

获取 Hub 上特定存储桶的信息。

示例:

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

cancel_access_request

< >

( repo_id: struser: str | None = Nonerequest_id: str | None = Nonerepo_type: str | None = Nonetoken: bool | str | None = None )

参数

  • repo_id (str) — 要取消访问请求的仓库的 id。
  • user (str, 可选) — 需要取消访问请求的用户名。必须且只能提供 user 或 request_id 中的一个。
  • request_id (str, 可选) — 要取消的访问请求的 id(参见 AccessRequest)。当仓库配置为不共享请求者用户名时,此项为必填。必须且只能提供 user 或 request_id 中的一个。
  • repo_type (str, 可选) — 要取消访问请求的仓库类型。必须是 model、dataset 或 space 之一。 默认为 model。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果仓库未开放访问,则返回 HTTP 400。
  • HfHubHTTPError — 如果您仅对仓库具有只读访问权限,则会返回 HTTP 403。如果您在仓库所属的组织中没有 write 或 admin 角色,或者您传递了 read 令牌,就可能出现这种情况。
  • HfHubHTTPError — 如果该用户在 Hub 上不存在,则返回 HTTP 404。
  • HfHubHTTPError — 如果找不到用户的访问请求,则返回 HTTP 404。
  • HfHubHTTPError — 如果用户的访问请求已在待处理列表中,则返回 HTTP 404。

取消用户对指定受限仓库的访问请求。

已取消的请求将返回待处理列表,并且用户将失去对该仓库的访问权限。

有关受控仓库的更多信息,请参阅 https://huggingface.co/docs/hub/models-gated。

cancel_job

< >

( job_id: strnamespace: str | None = Nonetoken: bool | str | None = None )

参数

  • job_id (str) — Job 的 ID。
  • namespace (str,可选) — Job 运行的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

在 Hugging Face 基础设施上取消一个计算 Job。

change_discussion_status

< >

( repo_id: strdiscussion_num: intnew_status: Literal['open', 'closed']token: bool | str | None = Nonecomment: str | None = Nonerepo_type: str | None = None ) → DiscussionStatusChange

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • discussion_num (int) — 讨论或拉取请求的编号。必须是一个严格大于零的整数。
  • new_status (str) — 讨论的新状态,为 "open" 或 "closed"。
  • comment (str, 可选) — 用于随状态变更一起发布的可选评论。
  • repo_type (str, 可选) — 如果上传到数据集或 space,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

状态变更事件

关闭或重新打开讨论或拉取请求。

示例:

>>> HfApi().change_discussion_status(
...     repo_id="username/repo_name",
...     discussion_num=34,
...     new_status="closed"
... )
# DiscussionStatusChange(id='deadbeef0000000', type='status-change', ...)

引发以下错误:

  • 如果 HuggingFace API 返回了错误,则抛出 HTTPError
  • 如果某些参数值无效,则抛出 ValueError
  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。

comment_discussion

< >

( repo_id: strdiscussion_num: intcomment: strtoken: bool | str | None = Nonerepo_type: str | None = None ) → DiscussionComment

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • discussion_num (int) — 讨论或拉取请求的编号。必须是一个严格大于零的整数。
  • comment (str) — 要创建的评论内容。评论支持 markdown 格式。
  • repo_type (str, 可选) — 如果上传到数据集或 space,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

讨论评论

新创建的评论

在指定的讨论中创建新评论。

示例:


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

引发以下错误:

  • 如果 HuggingFace API 返回了错误,则抛出 HTTPError
  • 如果某些参数值无效,则抛出 ValueError
  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。

copy_files

< >

( source: strdestination: strtoken: str | bool | None = None )

参数

  • source (str) — 以 hf:// URI 形式表示的源位置。可以是存储桶路径(例如 "hf://buckets/my-bucket/path/to/file") 或仓库路径(例如 "hf://username/my-model/weights.bin"、"hf://datasets/username/my-dataset/data/")。
  • destination (str) — 目标位置,为一个指向存储桶(例如 "hf://buckets/my-bucket/target/path") 或仓库(例如 "hf://username/my-model/target/path")的 hf:// URI。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

引发

ValueError

  • ValueError — 如果源/目标 URI 无效,或者尝试从存储桶复制到仓库。

在 Hub 上的不同位置之间复制文件。

将文件从存储桶或仓库(模型、数据集、空间)复制到存储桶或另一个仓库。 支持单个文件和整个文件夹。

在复制文件夹时,源路径末尾的 / 采用 rsync 风格的语义:将文件夹的内容复制到目标位置,而不嵌套源文件夹本身。如果没有末尾的 /, 源文件夹会嵌套在目标位置内部(类似于 cp -r)。

从仓库复制到存储桶时,.gitattributes 文件会被自动排除,因为它们是 git 特有的元数据,在存储桶上下文中并不相关。

仓库到仓库的复制在底层使用 CommitOperationCopy,并在目标仓库中创建一个提交。不支持从存储桶到仓库的复制。

服务器端副本仅在同一个存储区域内有效。

示例:

>>> from huggingface_hub import copy_files

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

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

# Copy folder contents (trailing /): files go directly into backup/
>>> copy_files("hf://buckets/my-bucket/models/", "hf://buckets/other-bucket/backup/")

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

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

# Copy files between repositories
>>> copy_files("hf://username/source-model/", "hf://username/dest-model/")

# Copy a file from one repo to another
>>> copy_files("hf://username/source-model/config.json", "hf://username/dest-model/config.json")

create_branch

< >

( repo_id: strbranch: strrevision: str | None = Nonetoken: bool | str | None = Nonerepo_type: str | None = Noneexist_ok: bool = False )

参数

  • repo_id (str) — 将创建分支的仓库。 示例:"user/my-cool-model"。
  • branch (str) — 要创建的分支名称。
  • revision (str, 可选) — 用于创建分支的 git 修订版本。它可以是分支名称,也可以是提交(commit)的 OID/SHA,以十六进制字符串形式表示。默认值为 "main" 分支的头部。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • repo_type (str, 可选) — 如果要在数据集或 space 上创建分支,请设置为 "dataset" 或 "space";如果要对模型进行标记,请设置为 None 或 "model"。默认值为 None。
  • exist_ok (bool,可选,默认为 False) — 如果 True,则当分支已存在时不引发错误。
  • RepositoryNotFoundError — 如果未找到仓库(错误 404):repo_id/repo_type 错误、仓库为私有但未进行身份验证,或仓库不存在。
  • BadRequestError — 如果分支引用无效。例如:refs/pr/5 或 ‘refs/foo/bar’。
  • HfHubHTTPError — 如果该分支已存在于仓库中(错误 409),且 exist_ok 设置为 False。

在 Hub 上为仓库创建新分支,从指定的修订版本开始(默认为 main)。 要找到适合您需求的修订版本,可以使用 list_repo_refs() 或 list_repo_commits()。

create_bucket

< >

( bucket_id: strprivate: bool | None = Nonevisibility: Literal['public', 'private'] | None = Noneresource_group_id: str | None = Noneregion: REPO_REGIONS | None = Noneexist_ok: bool = Falsetoken: bool | str | None = None ) → BucketUrl

参数

  • bucket_id (str) — 由 / 分隔的命名空间(用户或组织)和存储桶名称。 如果未提供命名空间,则会在当前用户的命名空间中创建该存储桶。
  • private (bool,可选) — 是否将存储桶设为私有。如果为 None(默认值),除非组织的默认设置为私有,否则存储桶将是公开的。不能与 visibility 同时传入。
  • visibility (Literal["public", "private"],可选) — 存储桶的可见性。可以是 "public" 或 "private"。如果为 None(默认值),除非组织的默认设置为私有,否则存储桶将是公开的。
  • resource_group_id (str, 可选) — 用于创建存储桶的资源组。资源组仅适用于企业版 Hub 组织,可用于定义组织内哪些成员可以访问该资源。资源组的 ID 可以在 Hub 上该资源页面的 URL 中找到(例如 "66670e5163145ca562cb1988")。要了解有关资源组的更多信息,请参阅 https://huggingface.co/docs/hub/en/security-resource-groups。
  • region (Literal["us", "eu"], 可选) — 创建存储桶所在的云区域。可以是 "us" 或 "eu" 之一。如果未指定,存储桶将在默认区域中创建。需要 Team 计划或更高版本。
  • exist_ok (bool,可选,默认为 False) — 如果 True,则当存储桶已存在时不引发错误。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

BucketUrl

指向新创建的存储桶的 URL,其中包含诸如 endpoint、namespace 和 bucket_id 等属性。

在 Hub 上创建一个存储桶。

示例:

>>> from huggingface_hub import create_bucket

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

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

>>> create_bucket(bucket_id="my-bucket", region="us")
BucketUrl(...)

create_collection

< >

( title: strnamespace: str | None = Nonedescription: str | None = Noneprivate: bool = Falseresource_group_id: str | None = Noneexists_ok: bool = Falsetoken: bool | str | None = None )

参数

  • title (str) — 要创建的集合的标题。示例:"Recent models"。
  • namespace (str,可选) — 要创建的集合的命名空间(用户名或组织)。默认值为所有者名称。
  • description (str, 可选) — 要创建的集合的描述。描述的最大长度为 150 个字符。
  • private (bool,可选) — 是否将集合设为私有。默认为 False(即公开集合)。
  • resource_group_id (str, 可选) — 将集合分配给所属组织的资源组。仅对组织拥有的集合有效。资源组 ID 是一个 24 字符的十六进制字符串。
  • exists_ok (bool, 可选) — 如果为 True,则当集合已存在时不引发错误。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

在 Hub 上创建一个新的 Collection。

返回:Collection

示例:

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

create_commit

< >

( repo_id: stroperations: Iterable[CommitOperation]commit_message: strcommit_description: str | None = Nonetoken: str | bool | None = Nonerepo_type: str | None = Nonerevision: str | None = Nonecreate_pr: bool | None = Nonenum_threads: int = 5parent_commit: str | None = Nonerun_as_future: bool = False_hot_reload: bool | None = None ) → CommitInfo or Future

参数

  • repo_id (str) — 将创建提交的仓库,例如: "username/custom_transformers"
  • operations (Iterable 的 ~hf_api.CommitOperation) — 要包含在提交中的操作的可迭代对象,可以是:
    • 使用 ~hf_api.CommitOperationAdd 上传文件
    • 使用 ~hf_api.CommitOperationDelete 删除文件
    • 使用 ~hf_api.CommitOperationCopy 复制文件

    操作对象会被修改以包含与上传相关的信息。请勿将同一对象用于多次提交。

  • commit_message (str) — 将创建的提交的摘要(第一行)。
  • commit_description (str, 可选) — 将创建的提交的描述
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • repo_type (str, 可选) — 如果上传到数据集、空间或内核仓库,请设置为 "dataset"、"space" 或 "kernel";如果上传到模型,请设置为 None 或 "model"。默认值为 None。
  • revision (str, 可选) — 要从中提交内容的 git 修订版本。默认为 "main" 分支的头部。
  • create_pr (boolean, 可选) — 是否使用该提交创建 Pull Request。默认为 False。 如果未设置 revision,则针对 "main" 分支打开 PR。如果 设置了 revision 且它是一个分支,则针对该分支打开 PR。如果 设置了 revision 但它不是分支名称(例如:一个 commit oid),服务器将返回 RevisionNotFoundError。
  • num_threads (int, 可选) — 用于上传文件的并发线程数。默认值为 5。 将其设置为 2 表示最多同时上传 2 个文件。
  • parent_commit (str, 可选) — 父提交的 OID / SHA,以十六进制字符串表示。 也支持简写形式(前 7 个字符)。如果指定了该参数且 create_pr 为 False, 当 revision 未指向 parent_commit 时,提交将失败。如果指定了该参数且 create_pr 为 True,则将从 parent_commit 创建拉取请求。指定 parent_commit 可确保在提交更改之前仓库未发生变化,这在仓库被并发更新 / 提交时尤为有用。
  • run_as_future (bool, 可选) — 是否将此方法在后台运行。后台任务按顺序执行,不会阻塞主线程。传入 run_as_future=True 将返回一个 Future 对象。默认为 False。

返回值

CommitInfo 或 Future

包含新创建提交(提交哈希、提交 URL、PR URL、提交信息……)信息的 CommitInfo 实例。如果传入 run_as_future=True,则返回一个 Future 对象,该对象在执行后将包含结果。

引发

ValueError 或 RepositoryNotFoundError

  • ValueError — 如果提交信息为空。
  • ValueError — 如果父提交不是有效的提交 OID。
  • ValueError — 如果提交的 README.md 文件包含无效的元数据部分。在这种情况下,提交会在尝试上传任何文件之前提前失败。
  • ValueError — 如果 create_pr 为 True,且 revision 既不是 None 也不是 "main"。
  • RepositoryNotFoundError — 如果未找到仓库(错误 404):repo_id/repo_type 错误、仓库为私有但未进行身份验证,或仓库不存在。

在指定的仓库中创建一个提交,并根据需要删除和上传文件。

在提交过程中,CommitOperation 的输入列表会被修改。请勿在多次提交中重复使用相同的对象。

create_commit 假定该仓库已存在于 Hub 上。如果遇到 Client error 404,请确保您已完成身份验证,您的令牌具有所需的权限, 并且 repo_id 和 repo_type 设置正确。如果仓库不存在, 请先使用 create_repo() 创建它。

create_commit 最多支持 25k 个 LFS 文件,且常规文件的负载上限为 1GB。

create_discussion

< >

( repo_id: strtitle: strtoken: bool | str | None = Nonedescription: str | None = Nonerepo_type: str | None = Nonepull_request: bool = False )

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • title (str) — 讨论的标题。长度最多为 200 个字符,且至少为 3 个字符。首尾的空白字符将被去除。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • description (str, 可选) — Pull Request 的可选描述。 默认为 "Discussion opened with the huggingface_hub Python library"
  • pull_request (bool, 可选) — 是否创建 Pull Request 或讨论。如果为 True,则创建 Pull Request。 如果为 False,则创建讨论。默认为 False。
  • repo_type (str, 可选) — 如果上传到数据集或 space,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。默认值为 None。

创建讨论或拉取请求。

通过编程方式创建的 Pull Requests 将处于 "draft" 状态。

使用 HfApi.create_commit() 也可以一次性创建包含更改的 Pull Request。

返回:DiscussionWithDetails

引发以下错误:

  • 如果 HuggingFace API 返回了错误,则抛出 HTTPError
  • 如果某些参数值无效,则抛出 ValueError
  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。

create_inference_endpoint

< >

( name: strrepository: strframework: straccelerator: strinstance_size: strinstance_type: strregion: strvendor: straccount_id: str | None = Noneprivate_link_account_id: str | None = Noneprivate_link_region: str | None = Nonemin_replica: int = 1max_replica: int = 1scaling_metric: InferenceEndpointScalingMetric | None = Nonescaling_threshold: float | None = Nonescale_to_zero_timeout: int | None = Nonerevision: str | None = Nonetask: str | None = Nonecustom_image: dict | None = Nonecontainer_registry_username: str | None = Nonecontainer_registry_password: str | None = Nonecontainer_command: list[str] | None = Nonecontainer_args: list[str] | None = Noneenv: dict[str, str] | None = Nonesecrets: dict[str, str] | None = Nonetype: InferenceEndpointType | str = <InferenceEndpointType.AUTHENTICATED: 'authenticated'>domain: str | None = Nonepath: str | None = Nonecache_http_responses: bool | None = Nonetags: list[str] | None = Nonenamespace: str | None = Nonetoken: bool | str | None = None ) → InferenceEndpoint

参数

  • name (str) — 新 Inference Endpoint 的唯一名称。
  • repository (str) — 与 Inference Endpoint 关联的模型仓库名称(例如 "gpt2")。
  • framework (str) — 用于该模型的机器学习框架(例如 "custom")。
  • accelerator (str) — 用于推理的硬件加速器(例如 "cpu")。
  • instance_size (str) — 用于托管模型的实例大小或类型(例如 "x4")。
  • instance_type (str) — Inference Endpoint 将部署到的云实例类型(例如 "intel-icl")。
  • region (str) — 将创建推理端点的云区域(例如 "us-east-1")。
  • vendor (str) — Inference Endpoint 将托管的云服务提供商或供应商(例如 "aws")。
  • account_id (str, 可选) — 已弃用且被忽略。请使用 private_link_account_id 和 private_link_region 来配置 AWS PrivateLink。
  • private_link_account_id (str, 可选) — 允许通过 AWS PrivateLink 访问推理端点的 AWS 账户 ID。需要 private_link_region。
  • private_link_region (str, 可选) — PrivateLink 入口点的 AWS 区域("us-east-1" 或 "eu-west-1"),private_link_account_id 的 VPC 端点将连接到此区域。与计算 region 和 vendor 无关。
  • min_replica (int, 可选) — Inference Endpoint 保持运行的最小副本(实例)数量。若要启用缩容至零,请将此值设置为 0,并相应调整 scale_to_zero_timeout。默认值为 1。
  • max_replica (int, 可选) — Inference Endpoint 可扩缩容的最大副本(实例)数。默认值为 1。
  • scaling_metric (str 或 InferenceEndpointScalingMetric ,可选) — 用于缩放的指标引用。提供时,取值应为 “pendingRequests” 或 “hardwareUsage”。默认值为 None(含义:由 HF Endpoints 服务指定指标)。
  • scaling_threshold (float, 可选) — 用于触发扩容的缩放指标阈值。在未提供缩放指标时将被忽略。 默认值为 None(含义:由 HF Endpoints 服务指定阈值)。
  • scale_to_zero_timeout (int, 可选) — 端点在不活动后缩容至零之前的时长(以分钟为单位)。如果设置为 None 且 min_replica 不为 0,则不会缩容至零。默认值为 None。
  • revision (str, 可选) — 要在 Inference Endpoint 上部署的特定模型修订版本(例如 "6c0e6080953db56375760c0471a8c5f2929baf11")。
  • task (str,可选) — 用于部署模型的任务(例如 "text-classification")。
  • custom_image (dict, 可选) — 要运行的容器镜像。可以是按镜像变体(例如 {"vLLM": {"url": "vllm/vllm-openai:v0.23.0", "port": 8000}‌},也可以是 sGLang、tgi、tei、llamacpp、hfServe 等)为键的字典,该字典将原样转发;也可以是一个描述自定义容器的扁平字典(例如 {"url": ..., "port": ...}),该字典将作为 {"custom": ...} 发送(参见示例)。默认使用 Hugging Face 托管的镜像。
  • container_registry_username (str, 可选) — 用于向托管自定义容器镜像的注册表进行身份验证的用户名。
  • container_registry_password (str, 可选) — 用于向托管自定义容器镜像的注册表进行身份验证的密码。需要 container_registry_username。如果未提供,则不会包含在 API 负载中。
  • container_command (list[str], 可选) — 覆盖容器的入口点命令(对应 API 负载中的 model.command)。适用于托管引擎镜像(例如 vLLM、SGLang)和自定义镜像。
  • container_args (list[str], 可选) — 附加到容器入口点的参数(对应 API 负载中的 model.args)。适用于托管引擎镜像(例如 vLLM、SGLang)和自定义镜像。
  • env (dict[str, str],可选) — 要注入到容器环境中的非机密环境变量。
  • secrets (dict[str, str], 可选) — 要注入到容器环境中的机密值。
  • type ([`InferenceEndpointType], *optional*) -- The type of the Inference Endpoint, which can be “authenticated”(default),“public”or“private”`.
  • domain (str, 可选) — Inference Endpoint 部署的自定义域名。如果已设置,推理端点将可通过该域名访问(例如 "my-new-domain.cool-website.woof")。
  • path (str, 可选) — 已部署模型的自定义路径,应以 / 开头(例如 "/models/google-bert/bert-base-uncased")。
  • cache_http_responses (bool, 可选) — 是否缓存来自 Inference Endpoint 的 HTTP 响应。默认值为 False。
  • tags (list[str],可选) — 要关联到推理端点的标签列表。
  • namespace (str, 可选) — 将创建 Inference Endpoint 的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

有关更新后的 Inference Endpoint 的信息。

创建一个新的Inference Endpoint。

accelerator、instance_size、instance_type、region 和 vendor 的值相互依赖;请使用 list_inference_endpoints_hardware() 列出有效的组合。

示例:

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

create_inference_endpoint_from_catalog

< >

( repo_id: str | None = Nonerecipe_id: str | None = Nonename: str | None = Noneaccelerator: Literal['cpu', 'gpu', 'neuron'] | str | None = Nonegguf_file: str | None = Nonetoken: bool | str | None = Nonenamespace: str | None = None ) → InferenceEndpoint

参数

  • repo_id (str, 可选) — 要部署为 Inference Endpoint 的目录中模型的 ID。与 recipe_id 互斥。
  • recipe_id (str, 可选) — 要部署的目录配方的 ID(参见 InferenceCatalogRecipe)。与 repo_id 互斥。
  • name (str, 可选) — 新 Inference Endpoint 的唯一名称。如果未提供,将生成一个随机名称。
  • accelerator (str,可选) — 用于推理的硬件加速器。可能的值包括 "cpu"、"gpu" 和 "neuron"。如果未提供,服务器将使用适合该模型的默认值。仅在 repo_id 有效时可用。
  • gguf_file (str, 可选) — 要部署的 GGUF 文件,适用于每种量化都有一个配方的模型(例如 "Qwen2.5-Coder-32B-Instruct-Q4_K_M.gguf")。仅与 repo_id 配合有效。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。
  • namespace (str, 可选) — 将创建 Inference Endpoint 的命名空间。默认值为当前用户的命名空间。

有关新推理端点的信息。

从 Hugging Face Inference Catalog 创建一个新的 Inference Endpoint。

Inference Catalog 的目标是提供一份经过筛选的模型列表,这些模型针对推理进行了优化,并且其默认配置已经过测试。有关目录中可用模型的列表,请参阅 /static-proxy?url=https%3A%2F%2Fendpoints.huggingface.co%2Fcatalog%3C%2Fa%3E%E3%80%82%3C%2Fp%3E

每个目录模型都通过一个配方进行部署:即针对该模型经过测试的硬件与引擎组合。传入repo_id可部署模型的默认配方,并可选地通过accelerator和gguf_file进行细化;或者传入recipe_id以部署由list_inference_catalog()列出的某个确切配方。

create_inference_endpoint_from_catalog 目前处于实验阶段,其 API 未来可能会发生变化。如果您有任何建议或需求,请提供反馈。

create_pull_request

< >

( repo_id: strtitle: strtoken: bool | str | None = Nonedescription: str | None = Nonerepo_type: str | None = None )

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • title (str) — 讨论的标题。长度最多为 200 个字符,且至少为 3 个字符。首尾的空白字符将被去除。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • description (str, 可选) — Pull Request 的可选描述。 默认为 "Discussion opened with the huggingface_hub Python library"
  • repo_type (str, 可选) — 如果上传到数据集或 space,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。默认值为 None。

创建一个 Pull Request。以编程方式创建的 Pull Request 将处于 "draft" 状态。

使用 HfApi.create_commit() 也可以一次性创建包含更改的 Pull Request;

这是 HfApi.create_discussion() 的封装。

返回:DiscussionWithDetails

引发以下错误:

  • 如果 HuggingFace API 返回了错误,则抛出 HTTPError
  • 如果某些参数值无效,则抛出 ValueError
  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。

create_repo

< >

( repo_id: strtoken: str | bool | None = Noneprivate: bool | None = Nonevisibility: RepoVisibility_T | None = Nonerepo_type: str | None = Noneexist_ok: bool = Falseresource_group_id: str | None = Noneregion: REPO_REGIONS | None = Nonespace_sdk: str | None = Nonespace_hardware: SpaceHardware | None = Nonespace_sleep_time: int | None = Nonespace_secrets: list[dict[str, str]] | None = Nonespace_variables: list[dict[str, str]] | None = Nonespace_volumes: list[Volume] | None = Nonespace_template: str | None = None ) → RepoUrl

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • private (bool,可选) — 是否将仓库设为私有。如果为 None(默认值),除非组织的默认设置为私有,否则仓库将是公开的。如果仓库已存在,则忽略此值。不能与 visibility 同时传递。
  • visibility (Literal["public", "private", "protected"], 可选) — 仓库的可见性。可以是 "public" 或 "private",对于 Spaces 也可以是 "protected"。如果为 None (默认值),除非组织的默认设置为私有,否则仓库将是公开的。如果仓库已存在,则忽略此值。
  • repo_type (str, 可选) — 如果上传到数据集或 space,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。默认值为 None。
  • exist_ok (bool,可选,默认为 False) — 如果 True,则当仓库已存在时不引发错误。
  • resource_group_id (str, 可选) — 用于创建仓库的资源组。资源组仅适用于企业版 Hub 组织,可用于定义组织内哪些成员可以访问该资源。资源组的 ID 可以在 Hub 上该资源页面的 URL 中找到(例如 "66670e5163145ca562cb1988")。要了解有关资源组的更多信息,请参阅 https://huggingface.co/docs/hub/en/security-resource-groups。
  • region (Literal["us", "eu"], 可选) — 创建仓库所在的云区域。可以是 "us" 或 "eu" 之一。如果未指定,仓库将在默认区域中创建。需要 Team 计划或更高版本。
  • space_sdk (str, 可选) — 当 repo_type 为 “space” 时,选择要使用的 SDK。可以是 “streamlit”、“gradio”、“docker” 或 “static”。 "static" Spaces 对所有人免费。其他 SDK 在计算资源上运行:在免费的 cpu-basic 硬件上, 它们需要订阅(用户为 PRO,组织为 Team 或 Enterprise),而付费硬件 仅需账单(一种支付方式和预付费额度)。
  • space_hardware (SpaceHardware 或 str,可选) — 当 repo_type 为 “space” 时,选择硬件。完整列表请参见 SpaceHardware。
  • space_sleep_time (int, 可选) — Space 进入休眠状态前等待的无活动秒数。如果不想让 Space 休眠,请设置为 -1(这是升级后硬件的默认行为)。对于免费硬件,无法配置休眠时间(该值固定为 48 小时无活动)。 有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。
  • space_secrets (list[dict[str, str]],可选) — 要在您的 Space 中设置的密钥列表。每个项的格式为 {"key": ..., "value": ..., "description": ...},其中 description 是可选的。 更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。
  • space_variables (list[dict[str, str]], 可选) — 要在您的 Space 中设置的公开环境变量列表。每个项的格式为 {"key": ..., "value": ..., "description": ...},其中 description 是可选的。 更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables。
  • space_volumes (list[Volume], 可选) — 在创建 Space 时要挂载的 Volume 对象列表。每个卷都有一个 type ("bucket"、"model"、"dataset" 或 "space")、一个 source(仓库或存储桶 ID)、一个 mount_path (容器内的路径),以及可选的 revision、read_only 和 path 字段。 仅当 repo_type 为 “space” 时适用。
  • space_template (str, 可选) — 从官方模板初始化新的 Space。可以是模板仓库 ID(例如 "SpacesExamples/jupyterlab")或其短名称(例如 "JupyterLab")。使用 HfApi.list_space_templates() 列出可用模板。仅当 repo_type 为 “space” 时适用。如果模板建议设为私有且未显式设置 visibility,则 Space 将创建为私有。

返回值

RepoUrl

新创建的仓库的 URL。值为 str 的子类,包含 endpoint、repo_type 和 repo_id 等属性。

在 HuggingFace Hub 上创建一个空仓库。

create_scheduled_job

< >

( image: strcommand: list[str]schedule: strsuspend: bool | None = Noneconcurrency: bool | None = Noneenv: dict[str, Any] | None = Nonesecrets: dict[str, Any] | None = Noneflavor: JobHardware | str | None = Nonetimeout: int | float | str | None = Noneattempts: int | None = Nonename: str | None = Nonelabels: dict[str, str] | None = Nonevolumes: list[Volume] | None = Noneexpose: list[int] | None = Noneexpose_public: list[int] | None = Noneresource_group_id: str | None = Nonenamespace: str | None = Nonetoken: bool | str | None = None )

参数

  • image (str) — 要使用的 Docker 镜像。 示例:"ubuntu"、"python:3.12"、"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"。 使用来自 Space 的镜像的示例:"hf.co/spaces/lhoestq/duckdb"。
  • command (list[str]) — 要运行的命令。示例:["echo", "hello"]。
  • schedule (str) — “@annually”、“@yearly”、“@monthly”、“@weekly”、“@daily”、“@hourly” 之一,或 CRON 调度表达式(例如,‘0 9 * * 1’ 表示每周一上午 9 点)。
  • suspend (bool,可选) — 如果为 True,则暂停(挂起)已调度的 Job。默认为 False。
  • concurrency (bool,可选) — 如果为 True,则此 Job 的多个实例可以并发运行。默认为 False。
  • env (dict[str, Any],可选) — 定义 Job 的环境变量。
  • secrets (dict[str, Any], 可选) — 定义 Job 的机密环境变量。
  • flavor (str, 可选) — 硬件的规格。有关可能的值,请参阅 JobHardware。 默认值为 "cpu-basic"。
  • timeout (Union[int, float, str], 可选) — Job 的最大持续时间:int 类型,单位为 s(秒,默认)、m(分钟)、h(小时)或 d(天)。 示例:300 或 "5m" 表示 5 分钟。
  • attempts (int, 可选) — 每次运行的最大尝试次数,包括初始尝试。默认为 1。
  • name (str, 可选) — 计划任务的名称。作为 name 标签存储。不能与 labels 中的 name 键同时传入。名称无需唯一。默认值由镜像和命令派生(带有短哈希后缀)。
  • labels (dict[str, str],可选) — 要附加到任务上的标签(键值对)。
  • volumes (list[Volume],可选) — 要挂载到作业容器中的 Hugging Face Buckets 或 Repos。 每个卷都是一个 Volume,包含 type("bucket"、"model"、"dataset" 或 "space")、 source(例如 "username/my-bucket")以及 mount_path(例如 "/data")。
  • expose (list[int], 可选) — 通过 jobs 代理暴露的容器端口。列表中指定的每个端口都可通过公共 jobs 域名访问(例如 https://<job_id>--8000.hf.jobs)。访问始终需要具有该 job 命名空间读取权限的 HF token。如需未认证访问,请使用 expose_public。
  • expose_public (list[int], 可选) — 通过 Jobs 代理公开且无需身份验证的端口。这些端口无需在 expose 中列出。
  • resource_group_id (str, 可选) — 用于在其中创建计划任务的资源组的 ID。用于控制组织内资源的访问权限,以及成本归属/支出限制功能。如果未提供,则计划任务将在任何资源组之外创建。
  • namespace (str,可选) — Job 将创建所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

在 Hugging Face 基础设施上创建计划计算任务。

示例:

创建您的第一个定时任务:

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

使用 CRON 调度表达式:

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

创建计划 GPU 任务:

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

create_scheduled_uv_job

< >

( script: strscript_args: list[str] | None = Noneschedule: strsuspend: bool | None = Noneconcurrency: bool | None = Nonedependencies: list[str] | None = Nonepython: str | None = Noneimage: str | None = Noneenv: dict[str, Any] | None = Nonesecrets: dict[str, Any] | None = Noneflavor: JobHardware | str | None = Nonetimeout: int | float | str | None = Noneattempts: int | None = Nonename: str | None = Nonelabels: dict[str, str] | None = Nonevolumes: list[Volume] | None = Noneexpose: list[int] | None = Noneexpose_public: list[int] | None = Noneresource_group_id: str | None = Nonenamespace: str | None = Nonetoken: bool | str | None = None )

参数

  • script (str) — UV 脚本的路径或 URL,或一个命令。
  • script_args (list[str], 可选) — 传递给脚本或命令的参数。
  • schedule (str) — “@annually”、“@yearly”、“@monthly”、“@weekly”、“@daily”、“@hourly” 之一,或 CRON 调度表达式(例如,‘0 9 * * 1’ 表示每周一上午 9 点)。
  • suspend (bool,可选) — 如果为 True,则暂停(挂起)已调度的 Job。默认为 False。
  • concurrency (bool,可选) — 如果为 True,则此 Job 的多个实例可以并发运行。默认为 False。
  • dependencies (list[str], 可选) — 用于运行 UV 脚本的依赖项。
  • python (str,可选) — 使用特定的 Python 版本。默认为 3.12。
  • image (str,可选,默认为 “ghcr.io/astral-sh/uv —python3.12-bookworm”): 使用已安装 uv 的自定义 Docker 镜像。
  • env (dict[str, Any],可选) — 定义 Job 的环境变量。
  • secrets (dict[str, Any], 可选) — 定义 Job 的机密环境变量。
  • flavor (str, 可选) — 硬件的规格。有关可能的值,请参阅 JobHardware。 默认值为 "cpu-basic"。
  • timeout (Union[int, float, str], 可选) — Job 的最大持续时间:int 类型,单位为 s(秒,默认)、m(分钟)、h(小时)或 d(天)。 示例:300 或 "5m" 表示 5 分钟。
  • attempts (int, 可选) — 每次运行的最大尝试次数,包括初始尝试。默认为 1。
  • name (str, 可选) — 计划任务的名称。作为 name 标签存储。不能与 labels 中的 name 键同时传入。名称无需唯一。默认值由脚本及其参数派生(附带一个短哈希后缀)。
  • labels (dict[str, str],可选) — 要附加到任务上的标签(键值对)。
  • volumes (list[Volume],可选) — 要挂载到作业容器中的 Hugging Face Buckets 或 Repos。 每个卷都是一个 Volume,包含 type("bucket"、"model"、"dataset" 或 "space")、 source(例如 "username/my-bucket")以及 mount_path(例如 "/data")。
  • expose (list[int], 可选) — 通过 jobs 代理暴露的容器端口。列表中指定的每个端口都可通过公共 jobs 域名访问(例如 https://<job_id>--8000.hf.jobs)。访问始终需要具有该 job 命名空间读取权限的 HF token。如需未认证访问,请使用 expose_public。
  • expose_public (list[int], 可选) — 通过 Jobs 代理公开且无需身份验证的端口。这些端口无需在 expose 中列出。
  • resource_group_id (str, 可选) — 用于在其中创建计划任务的资源组的 ID。用于控制组织内资源的访问权限,以及成本归属/支出限制功能。如果未提供,则计划任务将在任何资源组之外创建。
  • namespace (str,可选) — Job 将创建所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

在 Hugging Face 基础设施上运行 UV 脚本任务。

与 hf jobs uv run 不同,此方法会忽略 UV 脚本的 PEP 723 头部中可能携带的可选 [tool.hf-jobs] 表(参见 Jobs 指南):启动配置必须在此处显式传入。

示例:

从 URL 调度脚本:

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

调度本地脚本:

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

调度命令:

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

create_tag

< >

( repo_id: strtag: strtag_message: str | None = Nonerevision: str | None = Nonetoken: bool | str | None = Nonerepo_type: str | None = Noneexist_ok: bool = False )

参数

  • repo_id (str) — 将为其提交打标签的仓库。 示例:"user/my-cool-model"。
  • tag (str) — 要创建的标签名称。
  • tag_message (str, 可选) — 要创建的标签的描述。
  • revision (str, 可选) — 要标记的 git 修订版本。它可以是分支名称,也可以是提交(commit)的 OID/SHA,以十六进制字符串表示。也支持简写形式(前 7 个字符)。默认值为 "main" 分支的头部。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • repo_type (str, 可选) — 如果为数据集或 space 打标签,请设置为 "dataset" 或 "space";如果为模型打标签,请设置为 None 或 "model"。默认值为 None。
  • exist_ok (bool,可选,默认为 False) — 如果 True,当标签已存在时不引发错误。
  • RepositoryNotFoundError — 如果未找到仓库(错误 404):repo_id/repo_type 错误、仓库为私有但未进行身份验证,或仓库不存在。
  • RevisionNotFoundError — 如果在仓库中未找到该 revision(错误 404)。
  • HfHubHTTPError — 如果该分支已存在于仓库中(错误 409),且 exist_ok 设置为 False。

为 Hub 上某个仓库的指定提交添加标签。

create_webhook

< >

( url: str | None = Nonejob_id: str | None = Nonewatched: list[dict | WebhookWatchedItem]domains: list[constants.WEBHOOK_DOMAIN_T] | None = Nonesecret: str | None = Nonesecrets: dict[str, str] | None = Nonetoken: bool | str | None = None ) → WebhookInfo

参数

  • url (str) — 用于发送负载的 URL。
  • job_id (str) — 源 Job 的 ID,用于通过环境变量 WEBHOOK_PAYLOAD 中的 webhook 负载触发该 Job。 为了方便使用,还提供了以下额外的环境变量:WEBHOOK_REPO_ID、WEBHOOK_REPO_TYPE 和 WEBHOOK_SECRET。
  • watched (list[WebhookWatchedItem]) — Webhook 要监控的 WebhookWatchedItem 列表。可以是用户、组织、模型、数据集、空间或存储桶。 被监控的项目也可以以普通字典的形式提供。
  • domains (list[Literal["repo", "discussion"]], optional) — 要监控的域列表。可以是“repo”、“discussion”或两者。默认值为两者。
  • secret (str, 可选) — 用于对负载进行签名的密钥。
  • secrets (dict[str, str], optional) — 由 webhook 触发的 Job 的机密环境变量(例如 {"HF_TOKEN": "hf_***"})。 仅在 job_id 有效时可用。源 Job 的机密不会复制到 webhook,因此请在此处传入。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

WebhookInfo

新创建的 webhook 的相关信息。

创建新的 webhook。

Webhook 可以将负载发送到 URL,或者触发在 Hugging Face 基础设施上运行的 Job。 此函数应使用 url 或 job_id 之一进行调用,但不能同时使用两者。

示例:

创建一个 Webhook,用于向 URL 发送负载

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

运行一个 Job,然后创建一个 webhook 来触发该 Job

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

数据集信息

< >

( repo_id: strrevision: str | None = Nonetimeout: float | None = Nonefiles_metadata: bool = Falseexpand: list[ExpandDatasetProperty_T] | None = Nonetoken: bool | str | None = None ) → hf_api.DatasetInfo

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • revision (str, 可选) — 用于获取信息的 数据集仓库的版本。
  • timeout (float, 可选) — 是否为向 Hub 发送的请求设置超时时间。
  • files_metadata (bool, 可选) — 是否获取仓库中文件的元数据(大小、LFS 元数据等)。默认为 False。
  • expand (list[ExpandDatasetProperty_T], 可选) — 要在响应中返回的属性列表。使用此参数时,仅返回列表中的属性。 如果传递了 files_metadata,则不能使用此参数。 可能的值为 "author"、"cardData"、"citation"、"createdAt"、"disabled"、"description"、"downloads"、"downloadsAllTime"、"gated"、"lastModified"、"likes"、"mainSize"、"paperswithcode_id"、"private"、"siblings"、"sha"、"tags"、"trendingScore"、"usedStorage" 和 "resourceGroup"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

数据集仓库信息。

获取 huggingface.co 上某个特定数据集的信息。

如果传递了可接受的令牌,Dataset 可以是私有的。

引发以下错误:

  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。
  • RevisionNotFoundError 如果找不到要下载的修订版本。

delete_branch

< >

( repo_id: strbranch: strtoken: bool | str | None = Nonerepo_type: str | None = None )

参数

  • repo_id (str) — 要删除分支的仓库。 示例:"user/my-cool-model"。
  • branch (str) — 要删除的分支名称。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • repo_type (str, 可选) — 如果要在数据集或 space 上创建分支,请设置为 "dataset" 或 "space";如果要对模型进行标记,请设置为 None 或 "model"。默认值为 None。
  • RepositoryNotFoundError — 如果未找到仓库(错误 404):repo_id/repo_type 错误、仓库为私有但未进行身份验证,或仓库不存在。
  • HfHubHTTPError — 尝试删除受保护的分支时抛出。例如:main 无法被删除。
  • HfHubHTTPError — 如果尝试删除一个不存在的分支。

从 Hub 上的仓库中删除一个分支。

delete_bucket

< >

( bucket_id: strmissing_ok: bool = Falsetoken: bool | str | None = None )

参数

  • bucket_id (str) — 存储桶的 ID(例如 "username/my-bucket")。
  • missing_ok (bool,可选,默认为 False) — 如果 True,当 bucket 不存在时不引发错误。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

引发

BucketNotFoundError

  • BucketNotFoundError — 如果找不到存储桶且 missing_ok 设置为 False(默认值)。

从 Hub 中删除一个存储桶。

示例:

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

delete_collection

< >

( collection_slug: strmissing_ok: bool = Falsetoken: bool | str | None = None )

参数

  • collection_slug (str) — 要删除的集合的 Slug。示例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。
  • missing_ok (bool,可选) — 如果为 True,当集合不存在时不引发错误。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

在 Hub 上删除一个集合。

示例:

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

这是一个不可撤销的操作。已删除的集合无法恢复。

delete_collection_item

< >

( collection_slug: stritem_object_id: strmissing_ok: bool = Falsetoken: bool | str | None = None )

参数

  • collection_slug (str) — 要更新的集合的 Slug。示例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。
  • item_object_id (str) — 集合中该项目的 ID。这不是该项目在 Hub 上的 ID(repo_id 或 paper id)。 必须从 CollectionItem 对象中获取。示例:collection.items[0].item_object_id。
  • missing_ok (bool,可选) — 如果为 True,当该项不存在时不引发错误。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

从集合中删除一个项目。

示例:

>>> from huggingface_hub import get_collection, delete_collection_item

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

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

delete_file

< >

( path_in_repo: strrepo_id: strtoken: str | bool | None = Nonerepo_type: str | None = Nonerevision: str | None = Nonecommit_message: str | None = Nonecommit_description: str | None = Nonecreate_pr: bool | None = Noneparent_commit: str | None = None )

参数

  • path_in_repo (str) — 仓库中的相对文件路径,例如: "checkpoints/1fec34a/weights.bin"
  • repo_id (str) — 要从中删除文件的仓库,例如: "username/custom_transformers"
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • repo_type (str, 可选) — 如果文件位于数据集或空间中,请设置为 "dataset" 或 "space";如果位于模型中,则设置为 None 或 "model"。默认值为 None。
  • revision (str, 可选) — 要从中提交内容的 git 修订版本。默认为 "main" 分支的头部。
  • commit_message (str, 可选) — 生成的提交的摘要 / 标题 / 第一行。默认为 f"Delete {path_in_repo} with huggingface_hub"。
  • commit_description (str, 可选) — 生成的提交的描述
  • create_pr (boolean, 可选) — 是否使用该提交创建 Pull Request。默认为 False。 如果未设置 revision,则针对 "main" 分支打开 PR。如果 设置了 revision 且它是一个分支,则针对该分支打开 PR。如果 设置了 revision 但它不是分支名称(例如:一个 commit oid),服务器将返回 RevisionNotFoundError。
  • parent_commit (str, 可选) — 父提交的 OID / SHA,以十六进制字符串表示。也支持简写形式(前 7 个字符)。 如果指定了该参数且 create_pr 为 False,当 revision 未指向 parent_commit 时,提交将失败。 如果指定了该参数且 create_pr 为 True,拉取请求将从 parent_commit 创建。 指定 parent_commit 可确保在提交更改之前仓库未发生变化,这在仓库被并发更新 / 提交时尤为有用。

删除给定仓库中的文件。

引发以下错误:

delete_files

< >

( repo_id: strdelete_patterns: list[str]token: bool | str | None = Nonerepo_type: str | None = Nonerevision: str | None = Nonecommit_message: str | None = Nonecommit_description: str | None = Nonecreate_pr: bool | None = Noneparent_commit: str | None = None )

参数

  • repo_id (str) — 将从中删除该文件夹的仓库,例如: "username/custom_transformers"
  • delete_patterns (list[str]) — 要删除的文件或文件夹列表。每个字符串可以是文件路径、文件夹路径或通配符模式。模式是标准通配符(globbing 模式),文档见 此处。 模式匹配基于 fnmatch。 请注意,fnmatch 中的 * 会跨越路径边界进行匹配,这与传统的 Unix shell globbing 不同。 例如 ["file.txt", "folder/", "data/*.parquet"]
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请向存储的令牌传递 False。
  • repo_type (str, 可选) — 要从中删除文件的仓库类型。可以是 "model"、 "dataset" 或 "space"。默认为 "model"。
  • revision (str, 可选) — 要从中提交内容的 git 修订版本。默认为 "main" 分支的头部。
  • commit_message (str, 可选) — 生成的提交的摘要(第一行)。默认为 f"Delete files using huggingface_hub"。
  • commit_description (str, 可选) — 生成的提交的描述。
  • create_pr (boolean, 可选) — 是否使用该提交创建 Pull Request。默认为 False。 如果未设置 revision,则针对 "main" 分支打开 PR。如果 设置了 revision 且它是一个分支,则针对该分支打开 PR。如果 设置了 revision 但它不是分支名称(例如:一个 commit oid),服务器将返回 RevisionNotFoundError。
  • parent_commit (str, 可选) — 父提交的 OID / SHA,以十六进制字符串表示。也支持简写形式(前 7 个字符)。 如果指定了该参数且 create_pr 为 False,当 revision 未指向 parent_commit 时,提交将失败。 如果指定了该参数且 create_pr 为 True,拉取请求将从 parent_commit 创建。 指定 parent_commit 可确保在提交更改之前仓库未发生变化,这在仓库被并发更新 / 提交时尤为有用。

从 Hub 上的存储库中删除文件。

如果提供了文件夹路径,则整个文件夹及其包含的所有文件都会被删除。

delete_folder

< >

( path_in_repo: strrepo_id: strtoken: bool | str | None = Nonerepo_type: str | None = Nonerevision: str | None = Nonecommit_message: str | None = Nonecommit_description: str | None = Nonecreate_pr: bool | None = Noneparent_commit: str | None = None )

参数

  • path_in_repo (str) — 仓库中的相对文件夹路径,例如:"checkpoints/1fec34a"。
  • repo_id (str) — 将从中删除该文件夹的仓库,例如: "username/custom_transformers"
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请向存储的令牌传递 False。
  • repo_type (str, 可选) — 如果该文件夹位于数据集或空间中,请设置为 "dataset" 或 "space";如果位于模型中,则设置为 None 或 "model"。默认值为 None。
  • revision (str, 可选) — 要从中提交内容的 git 修订版本。默认为 "main" 分支的头部。
  • commit_message (str, 可选) — 生成的提交的摘要 / 标题 / 第一行。默认为 f"Delete folder {path_in_repo} with huggingface_hub"。
  • commit_description (str, 可选) — 生成的提交的描述。
  • create_pr (boolean, 可选) — 是否使用该提交创建 Pull Request。默认为 False。 如果未设置 revision,则针对 "main" 分支打开 PR。如果 设置了 revision 且它是一个分支,则针对该分支打开 PR。如果 设置了 revision 但它不是分支名称(例如:一个 commit oid),服务器将返回 RevisionNotFoundError。
  • parent_commit (str, 可选) — 父提交的 OID / SHA,以十六进制字符串表示。也支持简写形式(前 7 个字符)。 如果指定了该参数且 create_pr 为 False,当 revision 未指向 parent_commit 时,提交将失败。 如果指定了该参数且 create_pr 为 True,拉取请求将从 parent_commit 创建。 指定 parent_commit 可确保在提交更改之前仓库未发生变化,这在仓库被并发更新 / 提交时尤为有用。

删除给定仓库中的文件夹。

create_commit() 方法的简单封装。

delete_inference_endpoint

< >

( name: strnamespace: str | None = Nonetoken: bool | str | None = None )

参数

  • name (str) — 要删除的 Inference Endpoint 的名称。
  • namespace (str, 可选) — Inference Endpoint 所在的命名空间。默认值为当前用户。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

删除推理端点。

此操作不可逆。如果您不希望为推理端点产生费用,建议通过 pause_inference_endpoint() 将其暂停,或通过 scale_to_zero_inference_endpoint() 将其缩容至零。

为了方便起见,您也可以使用 InferenceEndpoint.delete() 来删除推理端点。

delete_repo

< >

( repo_id: strtoken: str | bool | None = Nonerepo_type: str | None = Nonemissing_ok: bool = False )

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • repo_type (str, 可选) — 如果上传到数据集或空间,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。
  • missing_ok (bool,可选,默认为 False) — 如果 True,当仓库不存在时不引发错误。
  • RepositoryNotFoundError — 如果找不到要从中删除的仓库,且 missing_ok 设置为 False(默认值)。

从 HuggingFace Hub 删除一个仓库。注意:此操作不可逆。

delete_scheduled_job

< >

( scheduled_job_id: strnamespace: str | None = Nonetoken: bool | str | None = None )

参数

  • scheduled_job_id (str) — 计划任务的 ID。
  • namespace (str,可选) — 计划任务所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

在 Hugging Face 基础设施上删除一个已调度的计算 Job。

delete_space_secret

< >

( repo_id: strkey: strtoken: bool | str | None = None )

参数

  • repo_id (str) — 要更新的仓库 ID。示例:"bigcode/in-the-stack"。
  • key (str) — 密钥。示例:"GITHUB_API_KEY"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

从 Space 中删除一个密钥。

Secrets 允许在不硬编码的情况下,为 Space 设置密钥或令牌。 有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。

delete_space_variable

< >

( repo_id: strkey: strtoken: bool | str | None = None )

参数

  • repo_id (str) — 要更新的仓库 ID。示例:"bigcode/in-the-stack"。
  • key (str) — 变量键。示例:"MODEL_REPO_ID"
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

从 Space 中删除一个变量。

Variables 允许为 Space 设置环境变量,而无需将其硬编码。 有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables

delete_space_volumes

< >

( repo_id: strtoken: bool | str | None = None )

参数

引发

BadRequestError

  • BadRequestError — 如果该 Space 未挂载任何卷。

从 Space 中移除所有卷。

示例:

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

delete_tag

< >

( repo_id: strtag: strtoken: bool | str | None = Nonerepo_type: str | None = None )

参数

  • repo_id (str) — 要删除标签的仓库。 示例:"user/my-cool-model"。
  • tag (str) — 要删除的标签名称。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • repo_type (str, 可选) — 如果为数据集或空间添加标签,请设置为 "dataset" 或 "space";如果为模型添加标签,请设置为 None 或 "model"。默认值为 None。

从 Hub 上的仓库中删除一个标签。

delete_webhook

< >

( webhook_id: strtoken: bool | str | None = None ) → None

参数

返回值

None

删除 Webhook。

示例:

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

禁用空间开发模式

< >

( repo_id: strtoken: bool | str | None = None ) → SpaceRuntime

参数

返回值

SpaceRuntime

有关您的 Space 的运行时信息。

  • RepositoryNotFoundError — 如果未找到您的 Space(错误 404)。最可能的原因是 repo_id 错误,或者您的 Space 是私有的但您尚未进行身份验证。
  • HfHubHTTPError — 403 Forbidden:只有 Space 的所有者才能设置开发模式。如果您想处理一个您不拥有的 Space,请通过发起 Discussion 向所有者提出请求,或者复制该 Space。
  • BadRequestError — 如果您的 Space 是静态 Space。静态 Space 始终处于运行状态,且不会产生任何费用。如果您想隐藏 一个静态 Space,可以将其设置为私有。

在 Space 上禁用开发模式。

Spaces 开发模式可简化应用的调试流程,并允许在不停止 Space 容器本身的情况下重启应用,从而加快 Spaces 的迭代速度。启用开发模式需要 PRO 或 Team & Enterprise 套餐,但禁用开发模式始终是被允许的(例如在订阅过期后)。有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-dev-mode。

禁用 Webhook

< >

( webhook_id: strtoken: bool | str | None = None ) → WebhookInfo

参数

返回值

WebhookInfo

有关已禁用 Webhook 的信息。

禁用 Webhook(将其状态设为“已禁用”)。

示例:

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

download_bucket_files

< >

( bucket_id: strfiles: list[tuple[str | BucketFile, str | Path]]raise_on_missing_files: bool = Falsetoken: str | bool | None = None )

参数

  • bucket_id (str) — 存储桶的 ID(例如 "username/my-bucket")。
  • files (list[tuple[Union[str, BucketFile], Union[str, Path]]]) — 要下载的文件,以元组列表(源,目标)的形式提供。有关格式详情,请参阅上述说明。
  • raise_on_missing_files (bool, 可选) — 如果为 True,当请求的文件在存储桶中不存在时,将引发 EntryNotFoundError。如果为 False(默认值),则跳过缺失的文件并发出警告。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

从存储桶下载文件。

Files 输入是一个 (remote file, local file) 元组列表,其中 remote file 是桶中文件的路径或一个 BucketFile 对象,而 local file 是本地文件系统上的目标路径。当传入 BucketFile 对象(从 list_bucket_tree() 获取)时,该方法将跳过元数据获取步骤并直接下载文件。

示例:

>>> from huggingface_hub import download_bucket_files

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

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

duplicate_repo

< >

( from_id: strto_id: str | None = Nonerepo_type: str | None = Noneprivate: bool | None = Nonevisibility: RepoVisibility_T | None = Nonetoken: bool | str | None = Noneexist_ok: bool = Falseresource_group_id: str | None = Nonespace_hardware: SpaceHardware | None = Nonespace_sleep_time: int | None = Nonespace_secrets: list[dict[str, str]] | None = Nonespace_variables: list[dict[str, str]] | None = Nonespace_volumes: list[Volume] | None = None ) → DuplicatedRepoUrl

参数

  • from_id (str) — 要复制的仓库 ID。示例:"openai/gdpval"。
  • to_id (str, 可选) — 新仓库的 ID。示例:"myorg/my-gdpval"。如果未提供,新仓库将与原仓库同名,但位于您的账户下。
  • repo_type (str, 可选) — 如果复制的是数据集或 Space,请设置为 "dataset" 或 "space"; 如果复制的是模型,请设置为 None 或 "model"。默认值为 None。
  • private (bool,可选) — 新仓库是否应为私有。默认与原始仓库的隐私设置相同。不能与 visibility 同时传入。
  • visibility (Literal["public", "private", "protected"],可选) — 新仓库的可见性。可以是 "public" 或 "private",对于 Spaces 也可以是 "protected"。默认值与原始仓库的可见性相同。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • exist_ok (bool,可选,默认为 False) — 如果 True,则当仓库已存在时不引发错误。
  • resource_group_id (str, 可选) — 用于创建新仓库的资源组。资源组仅适用于企业版 Hub 组织,可用于定义组织内哪些成员可以访问该资源。资源组的 ID 可以在 Hub 上该资源页面的 URL 中找到(例如 "66670e5163145ca562cb1988")。要了解有关资源组的更多信息,请参阅 https://huggingface.co/docs/hub/en/security-resource-groups。
  • space_hardware (SpaceHardware 或 str,可选) — 当 repo_type 为 “space” 时,选择硬件。示例:"t4-medium"。完整列表请参见 SpaceHardware。
  • space_sleep_time (int, 可选) — Space 进入休眠状态前等待的无活动秒数。 如果不想让 Space 休眠,请设置为 -1(这是升级后硬件的默认行为)。对于免费硬件,无法配置休眠时间(值固定为 48 小时无活动)。仅当 repo_type 为 “space” 时适用。 有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。
  • space_secrets (list[dict[str, str]], 可选) — 要在您的 Space 中设置的密钥列表。每个项的格式为 {"key": ..., "value": ..., "description": ...},其中 description 是可选的。 仅当 repo_type 为 “space” 时适用。 更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。
  • space_variables (list[dict[str, str]], 可选) — 要在您的 Space 中设置的公开环境变量列表。每个项的形式为 {"key": ..., "value": ..., "description": ...},其中 description 是可选的。仅当 repo_type 为 “space” 时适用。 有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables。
  • space_volumes (list[Volume], 可选) — 在复制 Space 时挂载的 Volume 对象列表。每个卷都有一个 type ("bucket"、"model"、"dataset" 或 "space")、一个 source(仓库或存储桶 ID)、一个 mount_path (容器内的路径),以及可选的 revision、read_only 和 path 字段。 仅当 repo_type 为 “space” 时适用。

新创建的仓库的 URL。值为 RepoUrl(以及 str)的子类,包含诸如 endpoint、repo_type、repo_id 和 files_copy_pending 等属性。

引发

RepositoryNotFoundError 或 HfHubHTTPError

  • RepositoryNotFoundError — 如果找不到 from_id 或 to_id 之一。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。
  • HfHubHTTPError — 如果 HuggingFace API 返回了错误

在 Hub 上复制一个仓库(模型、数据集或 Space)。

此操作执行服务器端复制,可完整保留 git 历史记录和 LFS 对象,且无需进行本地下载/上传往返。

Git 历史记录会立即复制,但 LFS/Xet 文件可能在此方法返回后仍在后台继续复制。在这种情况下,返回值的 files_copy_pending 为 True,在复制完成之前,从新仓库下载这些文件可能会失败。

示例:

>>> from huggingface_hub import duplicate_repo

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

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

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

edit_discussion_comment

< >

( repo_id: strdiscussion_num: intcomment_id: strnew_content: strtoken: bool | str | None = Nonerepo_type: str | None = None ) → DiscussionComment

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • discussion_num (int) — 讨论或拉取请求的编号。必须是一个严格大于零的整数。
  • comment_id (str) — 要编辑的评论的 ID。
  • new_content (str) — 评论的新内容。评论支持 markdown 格式。
  • repo_type (str, 可选) — 如果上传到数据集或 space,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

讨论评论

编辑后的评论

编辑讨论 / 拉取请求中的评论。

引发以下错误:

  • 如果 HuggingFace API 返回了错误,则抛出 HTTPError
  • 如果某些参数值无效,则抛出 ValueError
  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。

enable_space_dev_mode

< >

( repo_id: strtoken: bool | str | None = None ) → SpaceRuntime

参数

返回值

SpaceRuntime

有关您的 Space 的运行时信息。

  • RepositoryNotFoundError — 如果未找到您的 Space(错误 404)。最可能的原因是 repo_id 错误,或者您的 Space 是私有的但您尚未进行身份验证。
  • HfHubHTTPError — 403 Forbidden:只有 Space 的所有者才能设置开发模式。如果您想处理一个您不拥有的 Space,请通过发起 Discussion 向所有者提出请求,或者复制该 Space。
  • BadRequestError — 如果您的 Space 是静态 Space。静态 Space 始终处于运行状态,且不会产生任何费用。如果您想隐藏 一个静态 Space,可以将其设置为私有。

在 Space 上启用开发模式。

Spaces Dev Mode 简化了应用程序的调试过程,并允许你在不停止 Space 容器本身的情况下重启应用程序,从而加快 Spaces 的迭代速度。此功能包含在 PRO 或 Team & Enterprise 计划中。有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-dev-mode。

enable_webhook

< >

( webhook_id: strtoken: bool | str | None = None ) → WebhookInfo

参数

返回值

WebhookInfo

有关已启用 webhook 的信息。

启用 Webhook(使其处于“激活”状态)。

示例:

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

fetch_job_logs

< >

( job_id: strnamespace: str | None = Nonefollow: bool = Falsetail: int | None = Nonetoken: bool | str | None = None )

参数

  • job_id (str) — Job 的 ID。
  • namespace (str,可选) — Job 运行的命名空间。默认值为当前用户的命名空间。
  • follow (bool, 可选) — 如果为 True,则实时流式传输日志,直到作业完成(阻塞)。 如果为 False(默认值),则仅获取当前可用的日志并立即返回(非阻塞)。
  • tail (int, 可选) — 从日志中返回的最大行数。与 follow=True 结合使用时,从最后 N 行开始并继续流式传输新日志。当 follow=False 时,仅返回当前可用日志中的最后 N 行。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

获取 Hugging Face 基础设施上计算作业的所有日志。

示例:

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

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

>>> # Stream logs starting from the last 100 lines
>>> for log in fetch_job_logs(job_id=job.id, follow=True, tail=100):
...     print(log)

fetch_job_metrics

< >

( job_id: strnamespace: str | None = Nonefollow: bool = Falsetoken: bool | str | None = None )

参数

  • job_id (str) — Job 的 ID。
  • namespace (str,可选) — Job 运行的命名空间。默认值为当前用户的命名空间。
  • follow (bool, 可选) — 如果为 True,则实时流式传输指标,直到任务完成(阻塞)。 如果为 False(默认值),则仅获取当前指标并返回(非阻塞)。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

从 Hugging Face 基础设施上的计算 Job 获取实时指标。

示例:

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

>>> # Stream metrics until the job completes
>>> for metrics in fetch_job_metrics(job_id=job.id, follow=True):
...     print(metrics)

fetch_space_logs

< >

( repo_id: strbuild: bool = Falsefollow: bool = Falsetoken: bool | str | None = None ) → Iterable[str]

参数

  • repo_id (str) — Space 的 ID。示例:"bigcode/in-the-stack"。
  • build (bool,可选,默认为 False) — 如果为 True,则获取容器的构建日志(当 Space 卡在 BUILD_ERROR 时很有用)。如果为 False(默认值),则获取运行日志,即正在运行的应用程序的 stdout/stderr。
  • follow (bool,可选,默认为 False) — 如果为 True,则实时(阻塞地)流式传输日志,直到服务器关闭流或引发 KeyboardInterrupt。如果为 False(默认值),则仅获取当前已缓冲的日志并立即返回(非阻塞,类似于 docker logs)。
  • token (bool 或 str,可选) — 有效的用户访问令牌。默认使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

返回值

Iterable[str]

一个生成器,在日志行可用时逐行产出。

获取 Hub 上某个 Space 的运行或构建日志。

适用于调试构建失败或运行时崩溃的 Space,尤其是在脚本或智能体工作流中,无法通过浏览器查看日志的场景。

示例:

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

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

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

file_exists

< >

( repo_id: strfilename: strrepo_type: str | None = Nonerevision: str | None = Nonetoken: str | bool | None = None )

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • filename (str) — 要检查的文件名称,例如: "config.json"
  • repo_type (str, 可选) — 如果从数据集或 space 获取仓库信息,请设置为 "dataset" 或 "space"; 如果从模型获取仓库信息,请设置为 None 或 "model"。默认值为 None。
  • revision (str, 可选) — 用于获取信息的仓库版本。默认为 "main" 分支。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

检查 Hugging Face Hub 上的仓库中是否存在某个文件。

示例:

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

get_bucket_file_metadata

< >

( bucket_id: strremote_path: strtoken: str | bool | None = None ) → BucketFileMetadata

参数

  • bucket_id (str) — 存储桶的 ID(例如 "username/my-bucket")。
  • remote_path (str) — 文件在存储桶中的路径。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

包含大小和 xet 信息的文件元数据。

获取存储桶中文件的元数据。

示例:

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

get_bucket_paths_info

< >

( bucket_id: strpaths: Iterable[str]token: str | bool | None = None ) → Iterable[BucketFile]

参数

  • bucket_id (str) — 存储桶的 ID(例如 "username/my-bucket")。
  • paths (Iterable[str]) — 要获取信息的路径。如果路径不存在,将被忽略且不会引发异常。 仅支持文件路径。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterable[BucketFile]

路径信息,作为 BucketFile 对象的可迭代对象。

获取有关存储桶路径的信息。

调用以每批 1000 个路径为单位进行。结果在收到时即被返回。

示例:

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

get_collection

< >

( collection_slug: strtoken: bool | str | None = None )

参数

  • collection_slug (str) — Hub 中集合的 Slug。示例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

获取 Hub 上某个 Collection 的信息。

返回:Collection

示例:

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

get_dataset_leaderboard

< >

( repo_id: strbase_model_only: bool | None = Nonetoken: bool | str | None = Nonetimeout: float | None = None ) → list[DatasetLeaderboardEntry]

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。例如:"allenai/olmOCR-bench"。
  • base_model_only (bool 或 None,可选) — 默认情况下,排行榜仅包含未声明 base_model 关系(即规范/根仓库)的模型,这与 Hub 的默认排行榜视图一致。声明了父模型的微调或衍生仓库将被排除。传入 base_model_only=False 可禁用此过滤器,从而包含所有提交的结果,无论模型是否声明了基础模型关系。
  • token (bool 或 str,可选) — 有效的用户访问令牌。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • timeout (float, 可选) — 是否为向 Hub 发送的请求设置超时时间。

返回值

list[DatasetLeaderboardEntry]

一个 DatasetLeaderboardEntry 对象列表,表示排行榜条目,并按排名排序。

获取 Hub 上某个数据集的排行榜。

排行榜根据模型在给定基准数据集上的评估分数对其进行排名。并非所有数据集都有排行榜——只有提交了评估结果的基准数据集才有。这提供了以数据集为中心的分数视图;如需以模型为中心的视图,请使用 model_info() 并设置 expand=["evalResults"]。

引发以下错误:

  • RepositoryNotFoundError 如果找不到该仓库。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。
  • HfHubHTTPError 如果数据集没有排行榜。

示例:

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

# Include fine-tuned / derivative models too
>>> full_leaderboard = api.get_dataset_leaderboard("allenai/olmOCR-bench", base_model_only=False)

get_dataset_tags

< >

( )

将所有有效的数据集标签作为嵌套命名空间对象列出。

get_discussion_details

< >

( repo_id: strdiscussion_num: intrepo_type: str | None = Nonetoken: bool | str | None = None )

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • discussion_num (int) — 讨论或拉取请求的编号。必须是一个严格大于零的整数。
  • repo_type (str, 可选) — 如果上传到数据集或 space,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

从 Hub 获取讨论 / 拉取请求的详细信息。

返回:DiscussionWithDetails

引发以下错误:

  • 如果 HuggingFace API 返回了错误,则抛出 HTTPError
  • 如果某些参数值无效,则抛出 ValueError
  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。

get_full_repo_name

< >

( model_id: strorganization: str | None = Nonetoken: bool | str | None = None ) → str

参数

  • model_id (str) — 模型的名称。
  • organization (str, 可选) — 如果传入,仓库名称将位于组织命名空间,而非用户命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

str

如果未传入组织,则为用户命名空间中的仓库名称 ({username}/{model_id});否则为组织命名空间下的仓库名称 ({organization}/{model_id})。

返回给定模型 ID 和可选组织对应的仓库名称。

get_hf_file_metadata

< >

( url: strtoken: bool | str | None = Nonetimeout: float | None = 10 )

参数

  • url (str) — 文件 URL,例如由 hf_hub_url() 返回。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • timeout (float,可选,默认为 10) — 在放弃之前,等待服务器发送元数据的秒数。

获取 Hub 上给定 url 的文件版本的元数据。

get_inference_endpoint

< >

( name: strnamespace: str | None = Nonetoken: bool | str | None = None ) → InferenceEndpoint

参数

  • name (str) — 要获取其信息的 Inference Endpoint 的名称。
  • namespace (str, 可选) — Inference Endpoint 所在的命名空间。默认值为当前用户。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

有关所请求的推理端点的信息。

获取推理端点的相关信息。

示例:

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

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

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

get_model_tags

< >

( )

将所有有效的模型标签作为嵌套命名空间对象列出

get_organization_overview

< >

( organization: strtoken: bool | str | None = None ) → Organization

参数

返回值

Organization

包含组织概述的 Organization 对象。

引发

HTTPError

  • HTTPError — 如果该组织在 Hub 上不存在,则返回 HTTP 404。

在 Hub 上查看组织的概览。

get_paths_info

< >

( repo_id: strpaths: list[str] | strexpand: bool = Falserevision: str | None = Nonerepo_type: str | None = Nonetoken: str | bool | None = None ) → list[Union[RepoFile, RepoFolder]]

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • paths (Union[list[str], str], 可选) — 要获取信息的路径。如果某个路径不存在,将被忽略,不会引发异常。
  • expand (bool,可选,默认为 False) — 是否获取有关路径的更多信息(例如最后一次提交和文件的安全扫描结果)。此操作对服务器而言开销更大,因此每页仅返回 50 条结果(而非 1000 条)。由于分页功能在 huggingface_hub 中实现,除了获取结果所需的时间外,此过程对您而言是透明的。
  • revision (str, 可选) — 用于获取信息的仓库版本。默认为 "main" 分支。
  • repo_type (str, 可选) — 要从中获取信息的仓库类型("model"、"dataset" 或 "space"。 默认为 "model"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

list[Union[RepoFile, RepoFolder]]

路径信息,以 RepoFile 和 RepoFolder 对象的列表形式呈现。

  • RepositoryNotFoundError — 如果未找到仓库(错误 404):repo_id/repo_type 错误、仓库为私有但未进行身份验证,或仓库不存在。
  • RevisionNotFoundError — 如果在仓库中未找到该 revision(错误 404)。

获取仓库路径的信息。

示例:

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

< >

( repo_id: strauthor: str | None = Nonediscussion_type: constants.DiscussionTypeFilter | None = Nonediscussion_status: constants.DiscussionStatusFilter | None = Nonerepo_type: str | None = Nonetoken: bool | str | None = None ) → Iterator[Discussion]

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • author (str, 可选) — 传入一个值以按讨论作者进行筛选。None 表示不筛选。 默认值为 None。
  • discussion_type (str, 可选) — 设置为 "pull_request" 以仅获取拉取请求,设置为 "discussion" 以仅获取讨论。设置为 "all" 或 None 以同时获取两者。 默认值为 None。
  • discussion_status (str, 可选) — 设置为 "open"(或 "closed")以仅获取开放(或已关闭)的讨论。设置为 "all" 或 None 以获取两者。 默认值为 None。
  • repo_type (str, 可选) — 如果从数据集或空间获取,请设置为 "dataset" 或 "space";如果从模型获取,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterator[Discussion]

Discussion 对象的迭代器。

获取指定仓库的讨论和拉取请求。

示例:

在列表中收集仓库的所有讨论:

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

遍历仓库中的讨论:

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

get_safetensors_metadata

< >

( repo_id: strrepo_type: str | None = Nonerevision: str | None = Nonetoken: bool | str | None = Nonetimeout: float | None = 10 ) → SafetensorsRepoMetadata

参数

  • repo_id (str) — 由/分隔的用户或组织名称以及仓库名称。
  • repo_type (str, 可选) — 如果文件位于数据集或空间中,请设置为 "dataset" 或 "space";如果位于模型中,则设置为 None 或 "model"。默认值为 None。
  • revision (str, 可选) — 要从中获取文件的 git 修订版本。可以是分支名称、标签或提交哈希。默认为 "main" 分支的头部。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • timeout (float, 可选,默认为 10) — 在放弃之前,等待服务器发送数据的秒数,该值会传递给每个获取 safetensors 文件头的请求。将其设置为 None 可禁用超时(不推荐,因为停滞的连接可能会导致调用无限期挂起)。

返回值

SafetensorsRepoMetadata

与 safetensors 仓库相关的信息。

引发

NotASafetensorsRepoError 或 SafetensorsParsingError

  • NotASafetensorsRepoError — 如果该仓库不是 safetensors 仓库,即不包含 model.safetensors 或 model.safetensors.index.json 文件。
  • SafetensorsParsingError — 如果无法正确解析 safetensors 文件的文件头。

解析 Hub 上 safetensors 仓库的元数据。

我们首先检查该仓库是单个 safetensors 文件还是分片的 safetensors 仓库。如果是单个 safetensors 文件,我们会从该文件中解析元数据。如果是分片的 safetensors 仓库,我们会先从索引文件中解析元数据,然后从每个分片中解析元数据。

要从单个 safetensors 文件中解析元数据,请使用 parse_safetensors_file_metadata()。 要在 main 上通过单次请求获取分片模型的所有分片头,请使用 get_sharded_safetensors_metadata()。

有关 safetensors 格式的更多详细信息,请参阅 https://huggingface.co/docs/safetensors/index#format。

示例:

# 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_sharded_safetensors_metadata

< >

( repo_id: strfilename: str = 'model.safetensors.index.json'token: bool | str | None = Nonetimeout: float | None = 10 ) → SafetensorsRepoMetadata

参数

  • repo_id (str) — 由/分隔的用户或组织名称以及仓库名称。
  • filename (str, 可选) — 仓库中 safetensors 索引文件的路径。默认为 "model.safetensors.index.json"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • timeout (float,可选,默认为 10) — 在放弃之前,等待服务器发送数据的秒数。设置为 None 可禁用超时(不推荐,因为停滞的连接可能会导致调用无限期挂起)。

返回值

SafetensorsRepoMetadata

与 get_safetensors_metadata() 相同的元数据。

在 main 分支上,通过单次请求即可获取 Hugging Face Hub 上分片 safetensors 模型所有分片的元数据,而无需 get_safetensors_metadata() 逐个解析每个分片的头部。仅适用于 Hugging Face Hub。

示例:

>>> metadata = get_sharded_safetensors_metadata("HuggingFaceH4/zephyr-7b-beta")
>>> len(metadata.files_metadata)
8

get_space_runtime

< >

( repo_id: strtoken: bool | str | None = None ) → SpaceRuntime

参数

返回值

SpaceRuntime

有关 Space 的运行时信息,包括 Space 阶段和硬件。

获取 Space 的运行时信息。

get_space_secrets

< >

( repo_id: strtoken: bool | str | None = None ) → dict[str, SpaceSecret]

参数

返回值

dict[str, SpaceSecret]

以密钥名称为键的SpaceSecret对象字典。

获取 Space 中的所有密钥。

Secret 值仅可写入,无法读取。仅返回密钥、描述和最后更新时间。

Secrets 允许在不硬编码的情况下,为 Space 设置密钥或令牌。 有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。

示例:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.get_space_secrets("username/my-space")
{'HF_TOKEN': SpaceSecret(key='HF_TOKEN', description='...', updated_at=datetime.datetime(...))}

get_space_variables

< >

( repo_id: strtoken: bool | str | None = None )

参数

获取 Space 中的所有变量。

Variables 允许为 Space 设置环境变量,而无需将其硬编码。 有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables

get_user_overview

< >

( username: strtoken: bool | str | None = None ) → User

参数

返回值

User

包含用户概览的 User 对象。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果该用户在 Hub 上不存在,则返回 HTTP 404。

获取 Hub 上用户的概览信息。

get_webhook

< >

( webhook_id: strtoken: bool | str | None = None ) → WebhookInfo

参数

返回值

WebhookInfo

Webhook 的相关信息。

通过其 id 获取 webhook。

示例:

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

get_zero_gpu_quota

< >

( token: bool | str | None = None ) → ZeroGpuQuota

参数

  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。细粒度令牌必须具有“Billing > Read billing usage and payment method status”权限,而 OAuth 令牌必须具有 read-billing 作用域。

返回值

ZeroGpuQuota

已认证用户的 ZeroGPU 配额。

获取已认证用户的 ZeroGPU 配额。

在通过编程方式调用 ZeroGPU Spaces(例如从应用程序、智能体或 MCP 服务器)时,可用于跟踪 ZeroGPU 的使用情况。有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-zerogpu。

示例:

>>> from huggingface_hub import get_zero_gpu_quota
>>> quota = get_zero_gpu_quota()
>>> quota
ZeroGpuQuota(base=2400, remaining=1810, resets_at=datetime.datetime(2026, 9, 30, 9, 12, 3, tzinfo=datetime.timezone.utc), overquota_used=0)
>>> print(f"{quota.remaining / 60:.1f} minutes left")
30.2 minutes left

grant_access

< >

( repo_id: struser: strrepo_type: str | None = Nonetoken: bool | str | None = None )

参数

  • repo_id (str) — 要授予访问权限的仓库 ID。
  • user (str) — 要授予访问权限的用户名。
  • repo_type (str, 可选) — 要授予访问权限的仓库类型。必须是 model、dataset 或 space 之一。 默认为 model。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果仓库未开放访问,则返回 HTTP 400。
  • HfHubHTTPError — 如果用户已经拥有该仓库的访问权限,则返回 HTTP 400。
  • HfHubHTTPError — 如果您仅对仓库具有只读访问权限,则会返回 HTTP 403。如果您在仓库所属的组织中没有 write 或 admin 角色,或者您传递了 read 令牌,就可能出现这种情况。
  • HfHubHTTPError — 如果该用户在 Hub 上不存在,则返回 HTTP 404。

为指定用户授予对某个受限仓库的访问权限。

授予访问权限无需用户自行发送访问请求。用户会被自动添加到已接受列表中,这意味着他们可以下载文件。您可以随时使用 cancel_access_request() 或 reject_access_request() 撤销已授予的访问权限。

有关受控仓库的更多信息,请参阅 https://huggingface.co/docs/hub/models-gated。

hf_hub_download

< >

( repo_id: strfilename: strsubfolder: str | None = Nonerepo_type: str | None = Nonerevision: str | None = Nonecache_dir: str | Path | None = Nonelocal_dir: str | Path | None = Noneforce_download: bool = Falseetag_timeout: float = 10token: bool | str | None = Nonelocal_files_only: bool = Falsetqdm_class: type[base_tqdm] | None = Nonedry_run: bool = False ) → str or DryRunFileInfo

参数

  • repo_id (str) — 由/分隔的用户或组织名称以及仓库名称。
  • filename (str) — 仓库中文件的名称。
  • subfolder (str,可选) — 对应于仓库内某个文件夹的可选值。
  • repo_type (str, 可选) — 如果从数据集或 space 下载,请设置为 "dataset" 或 "space"; 如果从模型下载,请设置为 None 或 "model"。默认值为 None。
  • revision (str, 可选) — 可选的 Git 修订版本 ID,可以是分支名称、标签或提交哈希值。
  • cache_dir (str, Path, 可选) — 存储缓存文件的文件夹路径。
  • local_dir (str 或 Path,可选) — 如果提供,下载的文件将放置在此目录下。
  • force_download (bool,可选,默认为 False) — 即使文件已存在于本地缓存中,是否仍应下载该文件。
  • etag_timeout (float,可选,默认为 10) — 在获取 ETag 时,等待服务器发送数据的时间(秒数),超时后放弃,该值会传递给 httpx2.request。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • local_files_only (bool,可选,默认为 False) — 如果为 True,则避免下载文件,并在本地缓存文件存在时返回其路径。
  • tqdm_class (tqdm, 可选) — 如果提供,将覆盖进度条的默认行为。传入的参数必须继承自 tqdm.auto.tqdm 或至少模拟其行为。 默认使用自定义的 HF 进度条,可通过设置 HF_HUB_DISABLE_PROGRESS_BARS 环境变量来禁用。
  • dry_run (bool,可选,默认为 False) — 如果为 True,则执行试运行,而不会实际下载文件。返回一个 DryRunFileInfo 对象,其中包含有关将要下载内容的信息。

返回值

str 或 DryRunFileInfo

  • 如果 dry_run=False:文件的本地路径,或者在网络关闭时,磁盘上缓存的文件最后版本。
  • 如果 dry_run=True:一个包含下载信息的 DryRunFileInfo 对象。

引发

RepositoryNotFoundError 或 RevisionNotFoundError 或 ~utils.RemoteEntryNotFoundError 或 LocalEntryNotFoundError 或 EnvironmentError 或 OSError 或 ValueError

  • RepositoryNotFoundError — 如果找不到要下载的仓库。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。
  • RevisionNotFoundError — 如果找不到要下载的 revision。
  • ~utils.RemoteEntryNotFoundError — 如果找不到要下载的文件。
  • LocalEntryNotFoundError — 如果网络被禁用或不可用,且缓存中未找到该文件。
  • EnvironmentError — 如果 token=True 但找不到令牌。
  • OSError — 如果无法确定 ETag。
  • ValueError — 如果某些参数值无效。

如果本地缓存中不存在指定文件,则下载该文件。

新的缓存文件布局如下所示:

  • 缓存目录中每个 repo_id 都有一个子文件夹(按仓库类型进行命名空间划分)
  • 在每个仓库文件夹内:
    • refs 是最新已知修订版本 => commit_hash 对的列表
    • blobs 包含实际的存储对象(根据其是否为 LFS 文件,分别通过 git-sha 或 sha256 进行标识)
    • snapshots 包含每个提交对应的一个子文件夹,每个“提交”包含在该特定提交时已解析的文件子集。每个文件名都是指向该特定提交中对应 blob 的符号链接。
[  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

如果提供了 local_dir,仓库中的文件结构将在此位置进行复制。使用此选项时,cache_dir 将不会被使用,并且会在 local_dir 的根目录下创建一个 .cache/huggingface/ 文件夹,用于存储与下载文件相关的某些元数据。虽然此机制不如主缓存系统那样稳健,但它针对定期拉取仓库最新版本进行了优化。

隐藏讨论评论

< >

( repo_id: strdiscussion_num: intcomment_id: strtoken: bool | str | None = Nonerepo_type: str | None = None ) → DiscussionComment

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • discussion_num (int) — 讨论或拉取请求的编号。必须是一个严格大于零的整数。
  • comment_id (str) — 要编辑的评论的 ID。
  • repo_type (str, 可选) — 如果上传到数据集或 space,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

讨论评论

隐藏的注释

隐藏讨论/拉取请求中的评论。

隐藏评论的内容无法再被检索。隐藏评论是不可逆的。

引发以下错误:

  • 如果 HuggingFace API 返回了错误,则抛出 HTTPError
  • 如果某些参数值无效,则抛出 ValueError
  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。

inspect_job

< >

( job_id: strnamespace: str | None = Nonetoken: bool | str | None = None )

参数

  • job_id (str) — Job 的 ID。
  • namespace (str,可选) — Job 运行的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

在 Hugging Face 基础设施上检查计算任务。

示例:

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

inspect_scheduled_job

< >

( scheduled_job_id: strnamespace: str | None = Nonetoken: bool | str | None = None )

参数

  • scheduled_job_id (str) — 计划任务的 ID。
  • namespace (str,可选) — 计划任务所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

在 Hugging Face 基础设施上查看已调度的计算 Job。

示例:

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

kernel_info

< >

( repo_id: strrevision: str | None = Nonetimeout: float | None = Nonetoken: bool | str | None = None ) → ModelInfo

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • revision (str, 可选) — 用于获取信息的内核仓库的版本。
  • timeout (float, 可选) — 是否为向 Hub 发送的请求设置超时时间。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

ModelInfo

内核仓库信息。

在 huggingface.co 上获取某个特定内核的信息。

list_accepted_access_requests

< >

( repo_id: strrepo_type: str | None = Nonetoken: bool | str | None = None ) → Iterable[AccessRequest]

参数

  • repo_id (str) — 要获取访问请求的仓库 ID。
  • repo_type (str, 可选) — 要获取访问请求的仓库类型。必须是 model、dataset 或 space 之一。 默认为 model。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterable[AccessRequest]

AccessRequest 对象的可迭代对象。每个条目包含 username、request_id、email、status 和 timestamp 属性。如果受控仓库具有自定义表单,则 fields 属性将填充用户的回答。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果仓库未开放访问,则返回 HTTP 400。
  • HfHubHTTPError — 如果您仅对仓库具有只读访问权限,则会返回 HTTP 403。如果您在仓库所属的组织中没有 write 或 admin 角色,或者您传递了 read 令牌,就可能出现这种情况。

获取指定受限仓库的已接受访问请求。

已接受的请求表示用户已申请访问该仓库,且该请求已被接受。用户可以下载仓库中的任意文件。如果审批模式为自动,则此列表默认应包含所有请求。已接受的请求可以随时使用 cancel_access_request() 和 reject_access_request() 进行取消或拒绝。被取消的请求将返回待处理列表,而被拒绝的请求将进入已拒绝列表。在这两种情况下,用户都将失去对该仓库的访问权限。

有关受控仓库的更多信息,请参阅 https://huggingface.co/docs/hub/models-gated。

示例:

>>> from huggingface_hub import list_accepted_access_requests

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

list_bucket_tree

< >

( bucket_id: strprefix: str | None = Nonerecursive: bool | None = Nonetoken: str | bool | None = None ) → Iterable[Union[BucketFile, BucketFolder]]

参数

  • bucket_id (str) — 存储桶的 ID(例如 "username/my-bucket")。
  • prefix (str, 可选) — 将结果筛选为路径以该前缀开头的文件。
  • recursive (bool, 可选) — 如果为 True,则递归列出文件。如果为 False(默认值),则仅列出根目录下的文件和目录。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterable[Union[BucketFile, BucketFolder]]

一个可迭代对象,包含 BucketFile 和 BucketFolder 对象,其中包含文件和目录信息(路径等)。

列出存储桶中的文件。

示例:

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

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

list_buckets

< >

( namespace: str | None = Nonesearch: str | None = Nonetoken: bool | str | None = None ) → Iterable[BucketInfo]

参数

  • namespace (str,可选) — 列出此命名空间(用户或组织)下的存储桶。默认列出用户的存储桶。
  • search (str, 可选) — 用于筛选存储桶名称的搜索字符串。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterable[BucketInfo]

BucketInfo 对象的迭代器。

列出 Hub 中某个命名空间下的存储桶。

示例:

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

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

>>> for bucket in list_buckets(search="my-prefix"): # filter buckets by name
...     print(bucket)

list_collections

< >

( owner: list[str] | str | None = Noneitem: list[str] | str | None = Nonesort: CollectionSort_T | None = Nonelimit: int | None = Nonetoken: bool | str | None = None ) → Iterable[Collection]

参数

  • owner (list[str] 或 str,可选) — 按所有者的用户名进行筛选。
  • item (list[str] 或 str,可选) — 筛选包含特定项目的集合。示例:"models/teknium/OpenHermes-2.5-Mistral-7B"、"datasets/squad" 或 "papers/2311.12983"。
  • sort (Literal["lastModified", "trending", "upvotes"], 可选) — 按最后修改时间、热门程度或点赞数对集合进行排序。
  • limit (int,可选) — 返回的集合的最大数量。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterable[Collection]

Collection 对象的可迭代对象。

根据某些筛选条件,列出 Huggingface Hub 上的集合。

在列出集合时,每个集合的项目列表最多截断为 4 项。若要获取集合中的所有项目,必须使用 get_collection()。

list_daily_papers

< >

( date: str | None = Nonetoken: bool | str | None = Noneweek: str | None = Nonemonth: str | None = Nonesubmitter: str | None = Nonesort: DailyPapersSort_T | None = Nonep: int | None = Nonelimit: int | None = None ) → Iterable[PaperInfo]

参数

  • date (str, 可选) — 用于获取每日论文的 ISO 格式日期(YYYY-MM-DD)。 默认获取最近日期的论文。
  • token (Union[bool, str, None], 可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌。若要禁用身份验证,请传入 False。
  • week (str, 可选) — 要获取每日论文的 ISO 格式(YYYY-Www)周。例如,2025-W09。
  • month (str, 可选) — 要获取每日论文的 ISO 格式月份(YYYY-MM)。例如,2025-02。
  • submitter (str, 可选) — 用于筛选每日论文的提交者用户名。
  • sort (Literal["publishedAt", "trending"], 可选) — 每日论文的排序方式。可以按 publishedAt 或按 trending 排序。 默认为 "publishedAt"
  • p (int, 可选) — 分页的页码。默认为 0。
  • limit (int, 可选) — 要获取的论文数量上限。默认值为 50。

返回值

Iterable[PaperInfo]

huggingface_hub.hf_api.PaperInfo 对象的可迭代对象。

列出在 Hugging Face Hub 上于指定日期发布的每日论文。

示例:

>>> from huggingface_hub import HfApi

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

list_dataset_parquet_files

< >

( repo_id: strconfig: str | None = Nonetoken: bool | str | None = None ) → list[DatasetParquetEntry]

参数

  • repo_id (str) — 数据集仓库 ID(例如 "username/dataset-name")。
  • config (str, 可选) — 按特定的 config/subset 名称进行筛选。提供该参数时,仅返回对应 config 的 parquet 文件。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

list[DatasetParquetEntry]

DatasetParquetEntry 对象的列表,包含每个 parquet 文件的 config、split、url 和 size。

列出 Hub 上某个数据集可用的 parquet 文件。

托管在 Hub 上的所有数据集都会由 Dataset Viewer 自动转换为 Parquet 格式。 此方法返回 Parquet 文件列表,包含其 URL、配置、分片和大小。

示例:

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

list_datasets

< >

( filter: str | Iterable[str] | None = Noneauthor: str | None = Nonebenchmark: Literal[True] | Literal['official'] | str | None = Nonedataset_name: str | None = Nonegated: bool | None = Nonelanguage_creators: str | list[str] | None = Nonelanguage: str | list[str] | None = Nonemultilinguality: str | list[str] | None = Nonesize_categories: str | list[str] | None = Nonetask_categories: str | list[str] | None = Nonetask_ids: str | list[str] | None = Nonesearch: str | None = Nonesort: DatasetSort_T | None = Nonelimit: int | None = Noneexpand: list[ExpandDatasetProperty_T] | None = Nonefull: bool | None = Nonetoken: bool | str | None = None ) → Iterable[DatasetInfo]

参数

  • filter (str 或 Iterable[str],可选) — 用于在 hub 上过滤数据集的字符串或字符串列表。
  • author (str, 可选) — 用于标识返回数据集作者的字符串。
  • benchmark (True, "official", str, 可选) — 按基准测试筛选数据集。可以设置为 True 或 "official" 以返回官方基准测试数据集。 为了未来的兼容性,也可以是一个表示基准测试名称的字符串(目前仅支持 “official”)。
  • dataset_name (str, 可选) — 一个字符串或字符串列表,用于通过名称在 Hub 上识别数据集,例如 SQAC 或 wikineural
  • gated (bool, 可选) — 一个布尔值,用于筛选 Hub 上受限制或未受限制的数据集。默认情况下,返回所有数据集。 如果传入 gated=True,则仅返回受限制的数据集。 如果传入 gated=False,则仅返回未受限制的数据集。
  • language_creators(str 或 List,可选)— 一个字符串或字符串列表,可用于在 Hub 上根据数据的整理方式(例如 crowdsourced 或 machine_generated)来识别数据集。
  • language (str 或 List,可选) — 一个字符串或字符串列表,表示用于在 Hub 上按语言筛选数据集的双字符语言代码。
  • multilinguality (str 或 List,可选) — 一个字符串或字符串列表,用于筛选包含多种语言的 dataset。
  • size_categories (str 或 List,可选) — 一个字符串或字符串列表,可用于根据数据集的大小来识别 Hub 上的数据集,例如 100K<n<1M 或 1M<n<10M。
  • task_categories (str 或 List,可选) — 一个字符串或字符串列表,可用于根据设计任务在 Hub 上识别数据集,例如 audio_classification 或 named_entity_recognition。
  • task_ids (str 或 List,可选) — 一个字符串或字符串列表,可用于根据特定任务(例如 speech_emotion_recognition 或 paraphrase)在 Hub 上识别数据集。
  • search (str, 可选) — 一个字符串,将包含在返回的数据集中。
  • sort (DatasetSort_T, 可选) — 用于对生成的数据集进行排序的键。可能的值为 “created_at”、“downloads”、“last_modified”、“likes” 和 “trending_score”。
  • limit (int, 可选) — 获取数据集数量的上限。将此选项保留为 None 将获取所有数据集。
  • expand (list[ExpandDatasetProperty_T], 可选) — 要在响应中返回的属性列表。使用此参数时,仅返回列表中的属性。 如果传递了 full,则不能使用此参数。 可能的值为 "author"、"cardData"、"citation"、"createdAt"、"disabled"、"description"、"downloads"、"downloadsAllTime"、"gated"、"lastModified"、"likes"、"mainSize"、"paperswithcode_id"、"private"、"siblings"、"sha"、"tags"、"trendingScore"、"usedStorage" 和 "resourceGroup"。
  • full (bool, 可选) — 是否获取所有数据集数据,包括 last_modified、card_data 以及文件。可能包含有用的信息,例如 PapersWithCode ID。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterable[DatasetInfo]

huggingface_hub.hf_api.DatasetInfo 对象的可迭代对象。

根据某些筛选条件,列出托管在 Huggingface Hub 上的数据集。

使用 filter 参数的示例用法:

>>> 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(filter="fiftyone")

使用 search 参数的示例用法:

>>> from huggingface_hub import HfApi

>>> api = HfApi()

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

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

list_inference_catalog

< >

( accelerator: Literal['cpu', 'gpu', 'neuron'] | str | None = Noneengine: Literal['llamacpp', 'sglang', 'tei', 'vllm'] | str | None = Nonelicense: str | None = Nonetask: str | None = Nonesearch: str | None = Nonelimit: int | None = Nonetoken: bool | str | None = None ) → list[InferenceCatalogModel]

参数

  • accelerator (str,可选) — 仅返回具有此加速器("cpu"、"gpu" 或 "neuron")配方的模型。
  • engine (str, 可选) — 仅返回具有此推理引擎配方(例如 "vllm"、"llamacpp"、"tei"、"sglang")的模型。
  • license (str, 可选) — 仅返回采用此许可证的模型(例如 "Apache 2.0")。
  • task (str, 可选) — 仅返回适用于此任务(例如 "text-generation")的模型。
  • search (str, 可选) — 仅返回与此搜索查询匹配的模型。
  • limit (int, 可选) — 返回的最大模型数量。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。

返回值

list[InferenceCatalogModel]

目录中可用的模型,每个模型都附有经过测试的配方。

列出 Hugging Face Inference Catalog 中可用的模型。

Inference Catalog 的目标是提供一份经过筛选的模型列表,这些模型针对推理进行了优化,并且其默认配置已经过测试。有关目录中可用模型的列表,请参阅 /static-proxy?url=https%3A%2F%2Fendpoints.huggingface.co%2Fcatalog%3C%2Fa%3E%E3%80%82%3C%2Fp%3E

使用 create_inference_endpoint_from_catalog() 从目录中部署模型或配方。

示例:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> catalog = api.list_inference_catalog(task="text-generation", accelerator="neuron")
>>> [(model.repo_id, [recipe.id for recipe in model.recipes]) for model in catalog]
[('meta-llama/Llama-3.1-8B-Instruct', ['sizzling-biryani-g4xsi1ac', 'artisanal-quinoa-yz9ynamx']), ...]

list_inference_catalog 目前处于实验阶段,其 API 未来可能会发生变化。如果您有任何建议或需求,请提供反馈。

list_inference_endpoints

< >

( namespace: str | None = Nonetoken: bool | str | None = None ) → listInferenceEndpoint

参数

  • namespace (str,可选) — 要列出端点的命名空间。默认值为当前用户。设置为 "*" 可列出所有命名空间(即个人命名空间以及用户所属的所有组织)中的所有端点。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

listInferenceEndpoint

给定命名空间下所有推理端点的列表。

列出给定命名空间中的所有推理端点。

示例:

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

list_inference_endpoints_hardware

< >

( namespace: str | None = Nonetoken: bool | str | None = None ) → list[InferenceEndpointHardware]

参数

返回值

list[InferenceEndpointHardware]

每个供应商和地区可用的硬件,包括当前不可用或已弃用的硬件。

列出可用于部署推理端点的硬件。

每个条目都包含 create_inference_endpoint() 所需的精确 vendor、region、accelerator、instance_type 和 instance_size 值,以及命名空间的价格和加速器配额。

示例:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> hardware = api.list_inference_endpoints_hardware()
>>> [hw.id for hw in hardware if hw.accelerator == "gpu" and hw.status == "available"]
['aws-us-east-1-nvidia-l4-x1', 'aws-us-east-1-nvidia-l4-x4', ...]

list_jobs

< >

( status: list[JobStage | str] | JobStage | str | None = Nonelabels: dict[str, str] | None = Nonetimeout: int | None = Nonenamespace: str | None = Nonetoken: bool | str | None = None ) → Iterable[JobInfo]

参数

  • status (JobStage、str 或 list,可选) — 仅返回具有指定状态的 Job,例如 "RUNNING" 或 [JobStage.RUNNING, JobStage.SCHEDULING]。 有关可能的值,请参阅 JobStage。
  • labels (dict[str, str],可选) — 仅返回具有所有指定 key=value 标签的 Jobs,例如 {"env": "prod", "team": "ml"}。
  • timeout (float, 可选) — 是否为向 Hub 发送的请求设置超时时间。
  • namespace (str,可选) — 列出作业所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

返回值

Iterable[JobInfo]

JobInfo 对象的可迭代对象。

列出 Hugging Face 基础设施上的计算任务。

list_jobs_hardware

< >

( token: bool | str | None = None ) → list[JobHardwareInfo]

返回值

list[JobHardwareInfo]

可用硬件配置列表。

列出 Hugging Face 基础设施上作业可用的硬件选项。

示例:

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

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

list_lfs_files

< >

( repo_id: strrepo_type: str | None = Nonetoken: bool | str | None = None ) → Iterable[LFSFileInfo]

参数

  • repo_id (str) — 要列出 LFS 文件的仓库。
  • repo_type (str, 可选) — 仓库类型。如果从数据集或空间列出,请设置为 "dataset" 或 "space";如果从模型列出,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterable[LFSFileInfo]

LFSFileInfo 对象的迭代器。

列出 Hub 上某个仓库中的所有 LFS 文件。

这主要用于统计仓库占用的存储空间,并最终使用 permanently_delete_lfs_files() 清理大文件。请注意,这将是一个永久操作,会影响所有引用这些已删除文件的提交,且无法撤销。

示例:

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

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

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

list_liked_repos

< >

( user: str | None = Nonetoken: bool | str | None = None ) → UserLikes

参数

返回值

UserLikes

包含用户名和 3 个仓库 ID 列表的对象(分别对应模型、数据集和 Spaces)。

引发

ValueError

  • ValueError — 如果未传递 user 且未找到令牌(无论是从参数还是从机器中获取)。

列出 huggingface.co 上某用户点赞的所有公共仓库。

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

另请参阅 unlike()。

示例:

>>> from huggingface_hub import list_liked_repos

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

>>> likes.user
"julien-c"

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

list_models

< >

( filter: str | Iterable[str] | None = Noneauthor: str | None = Noneapps: str | list[str] | None = Nonegated: bool | None = Noneinference: Literal['warm'] | None = Noneinference_provider: Literal['all'] | PROVIDER_T | list[PROVIDER_T] | None = Nonetrained_dataset: str | list[str] | None = Nonesearch: str | None = Nonepipeline_tag: str | None = Nonenum_parameters: str | None = Noneemissions_thresholds: tuple[float, float] | None = Nonesort: ModelSort_T | None = Nonelimit: int | None = Noneexpand: list[ExpandModelProperty_T] | None = Nonefull: bool | None = NonecardData: bool = Falsefetch_config: bool = Falsetoken: bool | str | None = None ) → Iterable[ModelInfo]

参数

  • filter (str 或 Iterable[str],可选) — 用于在 Hub 上筛选模型的字符串或字符串列表。 模型可以按库、语言、任务、标签等进行筛选。
  • author (str, 可选) — 用于标识返回的模型作者(用户或组织)的字符串。
  • apps (str 或 List,可选) — 一个字符串或字符串列表,用于筛选 Hub 上支持指定应用的模型。示例值包括 "ollama" 或 ["ollama", "vllm"]。
  • gated (bool, 可选) — 一个布尔值,用于筛选 Hub 上是否为受控(gated)模型。默认情况下,返回所有模型。 如果传入 gated=True,则仅返回受控模型。 如果传入 gated=False,则仅返回非受控模型。
  • inference (Literal["warm"], 可选) — 如果为“warm”,则筛选当前由至少一个提供商在 Hub 上提供服务的模型。
  • inference_provider (Literal["all"] 或 str,可选) — 用于筛选 Hub 上由特定提供商服务的模型的字符串。 传入 "all" 以获取由至少一个提供商服务的所有模型。
  • trained_dataset (str 或 List,可选) — Hub 上模型训练数据集的字符串标签或字符串标签列表。
  • search (str, 可选) — 一个字符串,将包含在返回的模型 ID 中。
  • pipeline_tag (str, 可选) — 用于在 Hub 上按字符串管道标签筛选模型的标签,例如 summarization。
  • num_parameters (str, 可选) — 按参数量筛选模型。接受与 Hub 界面和 API 相同的范围语法,例如 "min:6B,max:128B"、"min:6B" 或 "max:128B"。
  • emissions_thresholds (Tuple, 可选) — 一个由两个整数或浮点数组成的元组,表示用于筛选结果模型的最小和最大碳足迹(以克为单位)。
  • sort (ModelSort_T, 可选) — 用于对返回的模型进行排序的键。可能的值为 “created_at”、“downloads”、“last_modified”、“likes” 和 “trending_score”。
  • limit (int, 可选) — 获取模型数量的上限。将此选项保留为 None 将获取所有模型。
  • expand (list[ExpandModelProperty_T], 可选) — 要在响应中返回的属性列表。使用此参数时,仅返回列表中的属性。 如果传递了 full、cardData 或 fetch_config,则不能使用此参数。 可能的取值为 "author"、"cardData"、"config"、"createdAt"、"disabled"、"downloads"、"downloadsAllTime"、"evalResults"、"gated"、"gguf"、"inference"、"inferenceProviderMapping"、"lastModified"、"library_name"、"likes"、"mask_token"、"model-index"、"pipeline_tag"、"private"、"safetensors"、"sha"、"siblings"、"spaces"、"tags"、"transformersInfo"、"trendingScore"、"widgetData" 以及 "resourceGroup"。
  • full (bool, 可选) — 是否获取所有模型数据,包括 last_modified、sha、文件以及 tags。使用过滤器时,此参数默认设置为 True。
  • cardData (bool, 可选) — 是否同时获取模型的元数据。其中可能包含有用信息,例如碳排放量、指标以及用于训练的数据集。
  • fetch_config (bool, 可选) — 是否同时获取模型配置。由于体积较大,full 中不包含此项。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterable[ModelInfo]

huggingface_hub.hf_api.ModelInfo 对象的可迭代对象。

根据某些筛选条件,列出托管在 Huggingface Hub 上的模型。

示例:

>>> from huggingface_hub import HfApi

>>> api = HfApi()

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

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

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

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

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

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

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

list_organization_followers

< >

( organization: strtoken: bool | str | None = None ) → Iterable[User]

参数

返回值

Iterable[User]

一个包含该组织所有关注者的 User 对象列表。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果该组织在 Hub 上不存在,则返回 HTTP 404。

列出 Hub 上某个组织的关注者。

list_organization_members

< >

( organization: strtoken: bool | str | None = None ) → Iterable[User]

参数

返回值

Iterable[User]

一个包含该组织成员的 User 对象列表。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果该组织在 Hub 上不存在,则返回 HTTP 404。

Hub 上组织的成员列表。

list_papers

< >

( query: str | None = Nonelimit: int | None = Nonetoken: bool | str | None = None ) → Iterable[PaperInfo]

参数

  • query (str, 可选) — 用于查找论文的搜索查询字符串。 如果提供,则返回与查询匹配的论文。
  • limit (int, 可选) — 返回的最大论文数量。
  • token (Union[bool, str, None], 可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。 若要禁用认证,请传入 False。

返回值

Iterable[PaperInfo]

huggingface_hub.hf_api.PaperInfo 对象的可迭代对象。

根据搜索查询,在 Hugging Face Hub 上列出每日论文。

示例:

>>> from huggingface_hub import HfApi

>>> api = HfApi()

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

list_pending_access_requests

< >

( repo_id: strrepo_type: str | None = Nonetoken: bool | str | None = None ) → Iterable[AccessRequest]

参数

  • repo_id (str) — 要获取访问请求的仓库 ID。
  • repo_type (str, 可选) — 要获取访问请求的仓库类型。必须是 model、dataset 或 space 之一。 默认为 model。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterable[AccessRequest]

AccessRequest 对象的可迭代对象。每个条目包含 username、request_id、email、status 和 timestamp 属性。如果受控仓库具有自定义表单,则 fields 属性将填充用户的回答。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果仓库未开放访问,则返回 HTTP 400。
  • HfHubHTTPError — 如果您仅对仓库具有只读访问权限,则会返回 HTTP 403。如果您在仓库所属的组织中没有 write 或 admin 角色,或者您传递了 read 令牌,就可能出现这种情况。

获取指定受限仓库的待处理访问请求。

待处理请求表示用户已请求访问该仓库,但该请求尚未被处理。 如果审批模式为自动,则此列表应为空。可以使用 accept_access_request() 和 reject_access_request() 来接受或拒绝待处理请求。

有关受控仓库的更多信息,请参阅 https://huggingface.co/docs/hub/models-gated。

示例:

>>> from huggingface_hub import list_pending_access_requests, accept_access_request

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

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

list_rejected_access_requests

< >

( repo_id: strrepo_type: str | None = Nonetoken: bool | str | None = None ) → Iterable[AccessRequest]

参数

  • repo_id (str) — 要获取访问请求的仓库 ID。
  • repo_type (str, 可选) — 要获取访问请求的仓库类型。必须是 model、dataset 或 space 之一。 默认为 model。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterable[AccessRequest]

AccessRequest 对象的可迭代对象。每个条目包含 username、request_id、email、status 和 timestamp 属性。如果受控仓库具有自定义表单,则 fields 属性将填充用户的回答。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果仓库未开放访问,则返回 HTTP 400。
  • HfHubHTTPError — 如果您仅对仓库具有只读访问权限,则会返回 HTTP 403。如果您在仓库所属的组织中没有 write 或 admin 角色,或者您传递了 read 令牌,就可能出现这种情况。

获取指定受限仓库的已拒绝访问请求。

被拒绝的请求表示用户已申请访问该仓库,且该申请已被仓库所有者(您或您所在组织的其他用户)明确拒绝。该用户无法下载仓库中的任何文件。您可以随时使用 accept_access_request() 和 cancel_access_request() 来接受或取消被拒绝的请求。取消的请求将返回待处理列表,而接受的请求则会进入已接受列表。

有关受控仓库的更多信息,请参阅 https://huggingface.co/docs/hub/models-gated。

示例:

>>> from huggingface_hub import list_rejected_access_requests

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

list_repo_commits

< >

( repo_id: strrepo_type: str | None = Nonetoken: bool | str | None = Nonerevision: str | None = Noneformatted: bool = False ) → list[GitCommitInfo]

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • repo_type (str, 可选) — 如果列出的是数据集或 Space 的提交,请设置为 "dataset" 或 "space";如果列出的是模型的提交,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • revision (str, 可选) — 要从中提交内容的 git 修订版本。默认为 "main" 分支的头部。
  • formatted (bool) — 是否返回经过 HTML 格式化的提交标题和描述。默认为 False。

返回值

list[GitCommitInfo]

包含 Hub 上某个仓库提交信息的对象列表。

  • RepositoryNotFoundError — 如果未找到仓库(错误 404):repo_id/repo_type 错误、仓库为私有但未进行身份验证,或仓库不存在。
  • RevisionNotFoundError — 如果在仓库中未找到该 revision(错误 404)。

获取 Hub 上某个仓库指定修订版本的提交列表。

提交按日期排序(最近的提交排在最前)。

示例:

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

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

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

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

list_repo_files

< >

( repo_id: strrevision: str | None = Nonerepo_type: str | None = Nonetoken: str | bool | None = None ) → list[str]

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • revision (str, 可选) — 用于获取信息的仓库版本。
  • repo_type (str, 可选) — 如果上传到数据集或空间,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

list[str]

给定仓库中的文件列表。

获取指定仓库中的文件列表。

list_repo_likers

< >

( repo_id: strrepo_type: str | None = Nonetoken: bool | str | None = None ) → Iterable[User]

参数

  • repo_id (str) — 要获取的仓库。示例:"user/my-cool-model"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • repo_type (str, 可选) — 如果上传到数据集或 space,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。默认值为 None。

返回值

Iterable[User]

huggingface_hub.hf_api.User 对象的可迭代对象。

列出在 Hugging Face Hub 上点赞了指定仓库的所有用户。

另请参阅 list_liked_repos()。

list_repo_refs

< >

( repo_id: strrepo_type: str | None = Noneinclude_pull_requests: bool = Falsetoken: str | bool | None = None ) → GitRefs

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • repo_type (str, 可选) — 如果列出的是数据集、Space 或 Kernel 的 refs,请设置为 "dataset"、"space" 或 "kernel";如果列出的是模型的 refs,请设置为 None 或 "model"。默认值为 None。
  • include_pull_requests (bool, 可选) — 是否将来自拉取请求的引用包含在列表中。默认为 False。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

GitRefs

包含 Hub 上某个仓库所有分支和标签信息的对象。

获取指定仓库的 refs 列表(包括标签和分支)。

示例:

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

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

list_repo_tree

< >

( repo_id: strpath_in_repo: str | None = Nonerecursive: bool = Falseexpand: bool = Falserevision: str | None = Nonerepo_type: str | None = Nonetoken: str | bool | None = None ) → Iterable[Union[RepoFile, RepoFolder]]

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • path_in_repo (str, 可选) — 仓库中树(文件夹)的相对路径,例如: "checkpoints/1fec34a/results"。默认值为仓库的根树(文件夹)。
  • recursive (bool,可选,默认为 False) — 是否递归列出树中的文件和文件夹。
  • expand (bool,可选,默认为 False) — 是否获取有关树中文件和文件夹的更多信息(例如,最后一次提交以及文件的安全扫描结果)。此操作对服务器而言开销更大,因此每页仅返回 50 条结果(而非 1000 条)。 由于分页功能已在 huggingface_hub 中实现,除了获取结果所需的时间外,此过程对您而言是透明的。
  • revision (str, 可选) — 要获取树的仓库版本。默认为 "main" 分支。
  • repo_type (str, 可选) — 要获取树的仓库类型("model"、"dataset"、"space" 或 "kernel")。 默认为 "model"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterable[Union[RepoFile, RepoFolder]]

树中文件和文件夹的信息,作为 RepoFile 和 RepoFolder 对象的可迭代对象。文件和文件夹的顺序不保证。

引发

RepositoryNotFoundError 或 RevisionNotFoundError 或 ~utils.RemoteEntryNotFoundError

  • RepositoryNotFoundError — 如果未找到仓库(错误 404):repo_id/repo_type 错误、仓库为私有但未进行身份验证,或仓库不存在。
  • RevisionNotFoundError — 如果在仓库中未找到该 revision(错误 404)。
  • ~utils.RemoteEntryNotFoundError — 如果仓库中不存在该树(文件夹)(错误 404)。

列出仓库树中的文件和文件夹,并获取相关信息。

示例:

获取仓库树的信息。

>>> from huggingface_hub import list_repo_tree
>>> repo_tree = list_repo_tree("lysandre/arxiv-nlp")
>>> repo_tree
<generator object HfApi.list_repo_tree at 0x7fa4088e1ac0>
>>> list(repo_tree)
[
    RepoFile(path='.gitattributes', size=391, blob_id='ae8c63daedbd4206d7d40126955d4e6ab1c80f8f', lfs=None, last_commit=None, security=None),
    RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None),
    RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None),
    RepoFile(
        path='flax_model.msgpack', size=497764107, blob_id='8095a62ccb4d806da7666fcda07467e2d150218e',
        lfs={'size': 497764107, 'sha256': 'd88b0d6a6ff9c3f8151f9d3228f57092aaea997f09af009eefd7373a77b5abb9', 'pointer_size': 134}, last_commit=None, security=None
    ),
    RepoFile(path='merges.txt', size=456318, blob_id='226b0752cac7789c48f0cb3ec53eda48b7be36cc', lfs=None, last_commit=None, security=None),
    RepoFile(
        path='pytorch_model.bin', size=548123560, blob_id='64eaa9c526867e404b68f2c5d66fd78e27026523',
        lfs={'size': 548123560, 'sha256': '9be78edb5b928eba33aa88f431551348f7466ba9f5ef3daf1d552398722a5436', 'pointer_size': 134}, last_commit=None, security=None
    ),
    RepoFile(path='vocab.json', size=898669, blob_id='b00361fece0387ca34b4b8b8539ed830d644dbeb', lfs=None, last_commit=None, security=None)]
]

获取有关仓库树结构的更多信息(最后一次提交和文件的安全扫描结果)

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

list_scheduled_jobs

< >

( labels: dict[str, str] | None = Nonetimeout: int | None = Nonenamespace: str | None = Nonetoken: bool | str | None = None ) → list[ScheduledJobInfo]

参数

  • labels (dict[str, str],可选) — 仅返回具有所有指定 key=value 标签的已调度 Job,例如 {"env": "prod", "team": "ml"}。
  • timeout (float, 可选) — 是否为向 Hub 发送的请求设置超时时间。
  • namespace (str,可选) — 列出作业所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

返回值

list[ScheduledJobInfo]

ScheduledJobInfo 对象的列表。

列出 Hugging Face 基础设施上已调度的计算任务。

list_space_templates

< >

( token: str | bool | None = None ) → list[SpaceTemplate]

参数

返回值

list[SpaceTemplate]

可用的 Space 模板列表。

列出 Hub 上可用的官方 Space 模板。

返回的模板的 repo_id(或其简短的 name)可以作为 space_template 传递给 HfApi.create_repo(),以从该模板初始化一个新的 Space。

示例:

>>> from huggingface_hub import list_space_templates
>>> templates = list_space_templates()
>>> templates[0]
SpaceTemplate(name='Streamlit', repo_id='streamlit/streamlit-template-space', sdk='docker', preferred_private=False)

list_spaces

< >

( filter: str | Iterable[str] | None = Noneauthor: str | None = Nonesearch: str | None = Nonedatasets: str | Iterable[str] | None = Nonemodels: str | Iterable[str] | None = Nonelinked: bool = Falsesort: SpaceSort_T | None = Nonelimit: int | None = Noneexpand: list[ExpandSpaceProperty_T] | None = Nonefull: bool | None = Nonetoken: bool | str | None = None ) → Iterable[SpaceInfo]

参数

  • filter (str 或 Iterable,可选) — 用于在 Hub 上识别 Spaces 的字符串标签或标签列表。
  • author (str, 可选) — 用于标识返回的 Spaces 作者的字符串。
  • search (str, 可选) — 一个字符串,将包含在返回的 Spaces 中。
  • datasets (str 或 Iterable,可选) — 是否返回使用数据集的 Spaces。 可以将特定数据集的名称作为字符串传入。
  • models (str 或 Iterable,可选) — 是否返回使用模型的 Spaces。 可以传入特定模型的名称作为字符串。
  • linked (bool, 可选) — 是否返回使用模型或数据集的 Spaces。
  • sort (SpaceSort_T, 可选) — 用于对生成的空间进行排序的键。可能的值为 “created_at”、“last_modified”、“likes” 和 “trending_score”。
  • limit (int, 可选) — 获取的 Spaces 数量上限。将此选项保留为 None 将获取所有 Spaces。
  • expand (list[ExpandSpaceProperty_T], 可选) — 要在响应中返回的属性列表。使用此参数时,仅返回列表中的属性。 如果传递了 full,则不能使用此参数。 可能的值为 "author"、"cardData"、"datasets"、"disabled"、"lastModified"、"createdAt"、"likes"、"models"、"private"、"region"、"runtime"、"sdk"、"siblings"、"sha"、"subdomain"、"tags"、"trendingScore"、"usedStorage" 和 "resourceGroup"。
  • full (bool, 可选) — 是否获取所有 Spaces 数据,包括 last_modified、siblings 和 card_data 字段。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterable[SpaceInfo]

huggingface_hub.hf_api.SpaceInfo 对象的可迭代对象。

根据某些筛选条件,列出托管在 Huggingface Hub 上的空间。

list_spaces_hardware

< >

( token: bool | str | None = None ) → list[JobHardwareInfo]

返回值

list[JobHardwareInfo]

可用硬件配置列表。

列出 Spaces 可用的硬件选项。

示例:

>>> from huggingface_hub import list_spaces_hardware
>>> hardware_list = list_spaces_hardware()
>>> hardware_list[0]
JobHardwareInfo(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', ...)
>>> hardware_list[0].name
'cpu-basic'

list_user_followers

< >

( username: strtoken: bool | str | None = None ) → Iterable[User]

参数

返回值

Iterable[User]

包含该用户关注者的User对象列表。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果该用户在 Hub 上不存在,则返回 HTTP 404。

获取 Hub 上某用户的关注者列表。

list_user_following

< >

( username: strtoken: bool | str | None = None ) → Iterable[User]

参数

返回值

Iterable[User]

一个 User 对象列表,包含该用户所关注的用户。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果该用户在 Hub 上不存在,则返回 HTTP 404。

获取用户在 Hub 上关注的用户列表。

list_user_repos

< >

( namespace: str | None = Nonetoken: bool | str | None = None ) → Iterable[RepoStorageInfo]

参数

  • namespace (str,可选) — 组织名称。如果未提供,则列出已认证用户的仓库。
  • token (bool 或 str,可选) — 有效的用户访问令牌。默认使用本地保存的令牌。

返回值

Iterable[RepoStorageInfo]

RepoStorageInfo 对象的可迭代对象。

列出用户或组织的所有仓库(模型、数据集、空间、存储桶),并包含存储信息。

使用/api/settings/repositories端点获取已认证用户的设置,或使用/api/organizations/{namespace}/settings/repositories获取组织的设置。

示例:

>>> from huggingface_hub import list_user_repos

>>> repos = list(list_user_repos())
>>> repos[0]
RepoStorageInfo(id='username/my-model', type='model', ...)

>>> # List repos from an organization
>>> repos = list(list_user_repos(namespace="my-org"))

list_webhooks

< >

( token: bool | str | None = None ) → list[WebhookInfo]

参数

返回值

list[WebhookInfo]

Webhook 信息对象列表。

列出所有已配置的 webhook。

示例:

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

merge_pull_request

< >

( repo_id: strdiscussion_num: inttoken: bool | str | None = Nonecomment: str | None = Nonerepo_type: str | None = None ) → DiscussionStatusChange

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • discussion_num (int) — 讨论或拉取请求的编号。必须是一个严格大于零的整数。
  • comment (str, 可选) — 用于随状态变更一起发布的可选评论。
  • repo_type (str, 可选) — 如果上传到数据集或 space,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

状态变更事件

合并 Pull Request。

引发以下错误:

  • 如果 HuggingFace API 返回了错误,则抛出 HTTPError
  • 如果某些参数值无效,则抛出 ValueError
  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。

model_info

< >

( repo_id: strrevision: str | None = Nonetimeout: float | None = NonesecurityStatus: bool | None = Nonefiles_metadata: bool = Falseexpand: list[ExpandModelProperty_T] | None = Nonetoken: bool | str | None = None ) → huggingface_hub.hf_api.ModelInfo

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • revision (str, 可选) — 用于获取信息的模型仓库的版本。
  • timeout (float, 可选) — 是否为向 Hub 发送的请求设置超时时间。
  • securityStatus (bool,可选) — 是否同时从模型仓库获取安全状态。安全状态将在 security_repo_status 字段中返回。
  • files_metadata (bool, 可选) — 是否获取仓库中文件的元数据(大小、LFS 元数据等)。默认为 False。
  • expand (list[ExpandModelProperty_T], 可选) — 要在响应中返回的属性列表。使用此参数时,仅返回列表中的属性。 如果传递了 securityStatus 或 files_metadata,则不能使用此参数。 可能的值为 "author"、"baseModels"、"cardData"、"childrenModelCount"、"config"、"createdAt"、"disabled"、"downloads"、"downloadsAllTime"、"evalResults"、"gated"、"gguf"、"inference"、"inferenceProviderMapping"、"lastModified"、"library_name"、"likes"、"mask_token"、"model-index"、"pipeline_tag"、"private"、"safetensors"、"sha"、"siblings"、"spaces"、"tags"、"transformersInfo"、"trendingScore"、"widgetData"、"usedStorage" 和 "resourceGroup"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

模型仓库信息。

获取 huggingface.co 上某个特定模型的信息

如果传递了有效的令牌或已登录,模型可以设置为私有。

引发以下错误:

  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。
  • RevisionNotFoundError 如果找不到要下载的修订版本。

move_bucket

< >

( from_id: strto_id: strtoken: bool | str | None = None )

参数

  • from_id (str) — 由/分隔的命名空间(用户或组织)和存储桶名称。原始存储桶标识符(例如 "username/my-bucket")。
  • to_id (str) — 由/分隔的命名空间(用户或组织)和存储桶名称。最终的存储桶标识符(例如 "username/new-bucket-name" 或 "organization/my-bucket")。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

引发

BucketNotFoundError

  • BucketNotFoundError — 如果找不到源存储桶。这可能是因为它不存在, 或者它被设置为 private 且您没有访问权限。

将存储桶从“namespace1/repo_name1”移动到“namespace2/repo_name2”

请注意,某些操作存在限制。有关迁移仓库的更多信息,请参阅 https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo。

示例:

>>> from huggingface_hub import move_bucket

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

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

move_repo

< >

( from_id: strto_id: strrepo_type: str | None = Nonetoken: str | bool | None = None )

参数

  • from_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。原始仓库标识符。
  • to_id (str) — 由 / 分隔的命名空间(用户或组织)和仓库名称。最终的仓库标识符。
  • repo_type (str, 可选) — 如果上传到数据集或 space,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

将仓库从 namespace1/repo_name1 移动到 namespace2/repo_name2

请注意,某些操作存在限制。有关迁移仓库的更多信息,请参阅 https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo。

引发以下错误:

  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。

paper_info

< >

( id: str ) → PaperInfo

参数

  • id (str, 可选) — 论文的 ArXiv id。

返回值

PaperInfo

PaperInfo 对象。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果该论文在 Hub 上不存在,则返回 HTTP 404。

获取 Hub 上某篇论文的信息。

parse_safetensors_file_metadata

< >

( repo_id: strfilename: strrepo_type: str | None = Nonerevision: str | None = Nonetoken: bool | str | None = Nonetimeout: float | None = 10 ) → SafetensorsFileMetadata

参数

  • repo_id (str) — 由/分隔的用户或组织名称以及仓库名称。
  • filename (str) — 仓库中文件的名称。
  • repo_type (str, 可选) — 如果文件位于数据集或空间中,请设置为 "dataset" 或 "space";如果位于模型中,则设置为 None 或 "model"。默认值为 None。
  • revision (str, 可选) — 要从中获取文件的 git 修订版本。可以是分支名称、标签或提交哈希。默认为 "main" 分支的头部。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • timeout (float,可选,默认为 10) — 在放弃之前,等待服务器发送数据的秒数。设置为 None 可禁用超时(不推荐,因为停滞的连接可能会导致调用无限期挂起)。

返回值

SafetensorsFileMetadata

与 safetensors 文件相关的信息。

引发

NotASafetensorsRepoError 或 SafetensorsParsingError

  • NotASafetensorsRepoError — 如果该仓库不是 safetensors 仓库,即不包含 model.safetensors 或 model.safetensors.index.json 文件。
  • SafetensorsParsingError — 如果无法正确解析 safetensors 文件的文件头。

从 Hub 上的 safetensors 文件中解析元数据。

要一次性解析仓库中所有 safetensors 文件的元数据,请使用 get_safetensors_metadata()。

有关 safetensors 格式的更多详细信息,请参阅 https://huggingface.co/docs/safetensors/index#format。

pause_inference_endpoint

< >

( name: strnamespace: str | None = Nonetoken: bool | str | None = None ) → InferenceEndpoint

参数

  • name (str) — 要暂停的 Inference Endpoint 的名称。
  • namespace (str, 可选) — Inference Endpoint 所在的命名空间。默认值为当前用户。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

已暂停的推理端点的相关信息。

暂停推理端点。

已暂停的 Inference Endpoint 不会产生费用。您可以随时使用 resume_inference_endpoint() 将其恢复。 这与使用 scale_to_zero_inference_endpoint() 将 Inference Endpoint 缩容至零不同,后者会在收到请求时自动重启。

为了方便起见,您也可以使用 pause_inference_endpoint() 来暂停推理端点。

暂停空间

< >

( repo_id: strtoken: bool | str | None = None ) → SpaceRuntime

参数

返回值

SpaceRuntime

有关您的 Space 的运行时信息,包括 stage=PAUSED 和请求的硬件。

  • RepositoryNotFoundError — 如果未找到您的 Space(错误 404)。最可能的原因是 repo_id 错误,或者您的 Space 是私有的但您尚未进行身份验证。
  • HfHubHTTPError — 403 Forbidden:只有 Space 的所有者才能暂停它。如果您想管理一个您不拥有的 Space,请通过发起 Discussion 向所有者提出请求,或者复制该 Space。
  • BadRequestError — 如果您的 Space 是静态 Space。静态 Space 始终处于运行状态,且不会产生任何费用。如果您想隐藏 一个静态 Space,可以将其设置为私有。

暂停您的 Space。

已暂停的 Space 会停止执行,直到其所有者手动重启。这与免费 Space 在 48 小时无活动后进入的休眠状态不同。无论您选择了何种硬件,暂停期间均不会向您计费。要重启您的 Space,请使用 restart_space() 并前往您的 Space 设置页面。

有关更多详细信息,请访问文档。

permanently_delete_lfs_files

< >

( repo_id: strlfs_files: Iterable[LFSFileInfo]rewrite_history: bool = Truerepo_type: str | None = Nonetoken: bool | str | None = None )

参数

  • repo_id (str) — 要列出 LFS 文件的仓库。
  • lfs_files (Iterable[LFSFileInfo]) — 一个可迭代对象,包含要从仓库中永久删除的 LFSFileInfo 项。使用 list_lfs_files() 可以列出仓库中的所有 LFS 文件。
  • rewrite_history (bool,可选,默认为 True) — 是否重写仓库历史以移除指向已删除 LFS 文件的文件指针(推荐)。
  • repo_type (str, 可选) — 仓库类型。如果从数据集或空间列出,请设置为 "dataset" 或 "space";如果从模型列出,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

从 Hub 上的仓库中永久删除 LFS 文件。

这是一个永久操作,将影响所有引用已删除文件的提交,并可能损坏您的 仓库。此操作不可撤销。仅在您清楚了解后果的情况下使用。

示例:

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

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

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

preupload_lfs_files

< >

( repo_id: stradditions: Iterable[CommitOperationAdd]token: str | bool | None = Nonerepo_type: str | None = Nonerevision: str | None = Nonecreate_pr: bool | None = Nonenum_threads: int = 5free_memory: bool = Truegitignore_content: str | None = None )

参数

  • repo_id (str) — 用于提交文件的仓库,例如:"username/custom_transformers"。
  • additions(Iterable 类型的 CommitOperationAdd)— 要上传的文件列表。警告:此列表中的对象会被修改以包含与上传相关的信息。请勿在多次提交中重复使用相同的对象。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • repo_type (str, 可选) — 要上传到的仓库类型(例如 "model" -默认-、"dataset"、"space" 或 "kernel")。
  • revision (str, 可选) — 要从中提交内容的 git 修订版本。默认为 "main" 分支的头部。
  • create_pr (boolean,可选) — 是否计划使用该提交创建 Pull Request。默认为 False。
  • num_threads (int, 可选) — 用于上传文件的并发线程数。默认值为 5。 将其设置为 2 表示最多同时上传 2 个文件。
  • free_memory (bool,可选,默认为 True) — 如果为 True,上传后每个 CommitOperationAdd 的 path_or_fileobj 属性将被替换为一个空的 bytes 对象以节省内存。如果需要在后续的 create_commit() 调用之外重用这些操作对象,请将其设置为 False。
  • gitignore_content (str, 可选) — .gitignore 文件的内容,用于确定哪些文件应被忽略。优先级顺序为:首先检查是否传入了 gitignore_content,然后检查待提交的文件列表中是否存在 .gitignore 文件,最后默认使用 Hub 上已托管的 .gitignore 文件(如果存在)。

在提交前将 LFS 文件预上传到 S3,为未来的提交做准备。

如果您正在即时生成要上传的文件,并且不想在一次性上传之前将它们存储在内存中,那么此方法非常有用。

这是一种面向高级用户的方法。在进行常规提交时,您不应直接调用它。 请改为直接使用 create_commit()。

提交操作在过程中会被修改。具体来说,附加的 path_or_fileobj 在上传完成后会被移除以节省内存(并被一个空的 bytes 对象替换)。除了将其传递给 create_commit() 之外,请勿重复使用相同的对象。如果不想从提交操作对象中移除附加的内容,请传入 free_memory=False。

示例:

>>> from huggingface_hub import CommitOperationAdd, preupload_lfs_files, create_commit, create_repo

>>> repo_id = create_repo("test_preupload").repo_id

# Generate and preupload LFS files one by one
>>> operations = [] # List of all `CommitOperationAdd` objects that will be generated
>>> for i in range(5):
...     content = ... # generate binary content
...     addition = CommitOperationAdd(path_in_repo=f"shard_{i}_of_5.bin", path_or_fileobj=content)
...     preupload_lfs_files(repo_id, additions=[addition]) # upload + free memory
...     operations.append(addition)

# Create commit
>>> create_commit(repo_id, operations=operations, commit_message="Commit all shards")

read_paper

< >

( id: str ) → str

参数

  • id (str) — 论文的 ArXiv id。

返回值

str

论文页面的 Markdown 格式内容。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果该论文在 Hub 上不存在,则返回 HTTP 404。

获取 Hub 上论文页面的 Markdown 内容。

拒绝访问请求

< >

( repo_id: struser: str | None = Nonerequest_id: str | None = Nonerepo_type: str | None = Nonerejection_reason: str | Nonetoken: bool | str | None = None )

参数

  • repo_id (str) — 要拒绝访问请求的仓库的 id。
  • user (str, 可选) — 应拒绝其访问请求的用户名。必须且只能提供 user 或 request_id 中的一个。
  • request_id (str, 可选) — 要拒绝的访问请求的 id(参见 AccessRequest)。当仓库配置为不共享请求者用户名时,此项为必填。必须且只能提供 user 或 request_id 其中之一。
  • repo_type (str, 可选) — 要拒绝访问请求的仓库类型。必须是 model、dataset 或 space 之一。 默认为 model。
  • rejection_reason (str, 可选) — 可选的拒绝原因,将显示给用户(最多 200 个字符)。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

引发

HfHubHTTPError

  • HfHubHTTPError — 如果仓库未开放访问,则返回 HTTP 400。
  • HfHubHTTPError — 如果您仅对仓库具有只读访问权限,则会返回 HTTP 403。如果您在仓库所属的组织中没有 write 或 admin 角色,或者您传递了 read 令牌,就可能出现这种情况。
  • HfHubHTTPError — 如果该用户在 Hub 上不存在,则返回 HTTP 404。
  • HfHubHTTPError — 如果找不到用户的访问请求,则返回 HTTP 404。
  • HfHubHTTPError — 如果用户的访问请求已在拒绝列表中,则返回 HTTP 404。

拒绝用户对指定受限仓库的访问请求。

被拒绝的请求会进入已拒绝列表。用户无法下载该仓库中的任何文件。可以随时使用 accept_access_request() 和 cancel_access_request() 接受或取消被拒绝的请求。 被取消的请求会返回待处理列表,而被接受的请求则会进入已接受列表。

有关受控仓库的更多信息,请参阅 https://huggingface.co/docs/hub/models-gated。

rename_discussion

< >

( repo_id: strdiscussion_num: intnew_title: strtoken: bool | str | None = Nonerepo_type: str | None = None ) → DiscussionTitleChange

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • discussion_num (int) — 讨论或拉取请求的编号。必须是一个严格大于零的整数。
  • new_title (str) — 讨论的新标题
  • repo_type (str, 可选) — 如果上传到数据集或 space,请设置为 "dataset" 或 "space";如果上传到模型,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

标题更改事件

重命名讨论。

示例:

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

引发以下错误:

  • 如果 HuggingFace API 返回了错误,则抛出 HTTPError
  • 如果某些参数值无效,则抛出 ValueError
  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。

repo_exists

< >

( repo_id: strrepo_type: str | None = Nonetoken: str | bool | None = None )

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • repo_type (str, 可选) — 如果从数据集或 space 获取仓库信息,请设置为 "dataset" 或 "space"; 如果从模型获取仓库信息,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

检查 Hugging Face Hub 上是否存在某个仓库。

示例:

>>> from huggingface_hub import repo_exists
>>> repo_exists("google/gemma-7b")
True
>>> repo_exists("google/not-a-repo")
False

repo_info

< >

( repo_id: strrevision: str | None = Nonerepo_type: str | None = Nonetimeout: float | None = Nonefiles_metadata: bool = Falseexpand: ExpandModelProperty_T | ExpandDatasetProperty_T | ExpandSpaceProperty_T | None = Nonetoken: bool | str | None = None ) → Union[SpaceInfo, DatasetInfo, ModelInfo]

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • revision (str, 可选) — 用于获取信息的仓库版本。
  • repo_type (str, 可选) — 如果从数据集或 space 获取仓库信息,请设置为 "dataset" 或 "space"; 如果从模型获取仓库信息,请设置为 None 或 "model"。默认值为 None。
  • timeout (float, 可选) — 是否为向 Hub 发送的请求设置超时时间。
  • expand (ExpandModelProperty_T 或 ExpandDatasetProperty_T 或 ExpandSpaceProperty_T,可选) — 要在响应中返回的属性列表。使用此参数时,仅返回列表中的属性。 如果传递了 files_metadata,则不能使用此参数。 有关可用属性的完整列表,请参阅 model_info()、dataset_info() 或 space_info()。
  • files_metadata (bool, 可选) — 是否获取仓库中文件的元数据(大小、LFS 元数据等)。默认为 False。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Union[SpaceInfo, DatasetInfo, ModelInfo]

获取给定类型仓库的信息对象。

引发以下错误:

  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。
  • RevisionNotFoundError 如果找不到要下载的修订版本。

request_space_hardware

< >

( repo_id: strhardware: SpaceHardwaretoken: bool | str | None = Nonesleep_time: int | None = None ) → SpaceRuntime

参数

  • repo_id (str) — 要更新的仓库 ID。示例:"bigcode/in-the-stack"。
  • hardware (str 或 SpaceHardware) — 运行 Space 的硬件。示例:"t4-medium"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • sleep_time (int, 可选) — 在将 Space 置于休眠状态之前,等待的无活动秒数。如果不想让 Space 休眠,请设置为 -1(这是升级后硬件的默认行为)。对于免费硬件,无法配置休眠时间(该值固定为 48 小时无活动)。 有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。

返回值

SpaceRuntime

有关 Space 的运行时信息,包括 Space 阶段和硬件。

为 Space 申请新硬件。

在创建 Space 仓库时,也可以直接请求硬件!详情请参阅 create_repo()。

rerun_job

< >

( job_id: strnamespace: str | None = Nonetoken: bool | str | None = None ) → JobInfo

参数

  • job_id (str) — 要重新运行的 Job 的 ID。
  • namespace (str, 可选) — Job 的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 用户访问令牌。默认使用本地保存的令牌。

返回值

JobInfo

新启动的 Job。

使用现有 Job 的 spec(包括其重试和资源设置)运行一个新的 Job。

resolve_revision

< >

( repo_id: strrepo_type: str | None = Nonerevision: str | None = Nonecache_dir: str | Path | None = Nonelocal_files_only: bool = Falsetoken: bool | str | None = None ) → ResolvedRevision

参数

  • repo_id (str) — 由/分隔的用户或组织名称以及仓库名称。
  • repo_type (str, 可选) — 如果该仓库是数据集、空间或内核仓库,则设置为 "dataset"、"space" 或 "kernel";如果是模型,则设置为 None 或 "model"。默认值为 None。
  • revision (str, 可选) — 要解析的版本。可以是分支名称、标签、PR 引用或提交哈希。默认值为默认分支。如果传入的是 ResolvedRevision,则原样返回——除非它是针对另一个仓库解析的,在这种情况下,会重新解析其最初请求的版本。
  • cache_dir (str, Path, 可选) — 用于存储缓存文件的文件夹路径。默认值为 HF_HUB_CACHE 的值。
  • local_files_only (bool,可选,默认为 False) — 如果为 True,则仅从本地缓存解析修订版本,而不联系 Hub。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

ResolvedRevision

一个 str 子类,同时保存所请求的修订版本及其解析到的提交哈希值。

将修订版本(分支、标签、PR 引用)解析为提交哈希值。

此功能适用于需要分别下载和加载仓库中多个组件(如 config、weights、tokenizer 等)的库。一次性解析 revision 并传递返回的 ResolvedRevision,可确保后续每次调用都指向完全相同的 commit,即使仓库在此期间被更新也是如此。此外,这还能节省 HTTP 调用,因为使用 commit hash 进行的下载可以直接从本地缓存提供,而无需联系 Hub。

revision -> commit hash 的映射会以尽力而为的方式缓存在磁盘上(位于缓存的 refs/ 文件夹中)。如果之后无法连接到 Hub(离线模式、连接错误、超时、Hub 停机……),则会使用缓存的值作为回退方案。

如果只需要下载完整的仓库快照,只需调用一次 snapshot_download() 即可,它已经能正确处理。 resolve_revision 仅在单独下载文件时才有用。

示例:

>>> from huggingface_hub import hf_hub_download, resolve_revision
>>> revision = resolve_revision("openai-community/gpt2")
>>> revision
ResolvedRevision(initial=None, resolved='607a30d783dfa663caf39e06633721c8d4cfcd7e')

# Pass it around: every download is pinned to the same commit
>>> config = hf_hub_download("openai-community/gpt2", "config.json", revision=revision)
>>> weights = hf_hub_download("openai-community/gpt2", "model.safetensors", revision=revision)

restart_space

< >

( repo_id: strtoken: bool | str | None = Nonefactory_reboot: bool = False ) → SpaceRuntime

参数

  • repo_id (str) — 要重启的 Space 的 ID。示例:"Salesforce/BLIP2"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • factory_reboot (bool, 可选) — 如果为 True,Space 将从头重建,且不缓存任何依赖项。

返回值

SpaceRuntime

有关您的 Space 的运行时信息。

  • RepositoryNotFoundError — 如果未找到您的 Space(错误 404)。最可能的原因是 repo_id 错误,或者您的 Space 是私有的但您尚未进行身份验证。
  • HfHubHTTPError — 403 Forbidden: 只有 Space 的所有者才能重启它。如果您想重启一个您不拥有的 Space,请通过发起 Discussion 向所有者提出请求,或者复制该 Space。
  • BadRequestError — 如果您的 Space 是静态 Space。静态 Space 始终处于运行状态,且不会产生任何费用。如果您想隐藏 一个静态 Space,可以将其设置为私有。

重新启动您的 Space。

这是以编程方式重启已暂停的 Space 的唯一方法(参见 pause_space())。您必须是该 Space 的所有者才能重启它。如果您使用的是升级后的硬件,Space 重启后您的账户将立即被计费。无论 Space 当前处于何种状态,您都可以触发重启。

有关更多详细信息,请访问文档。

resume_inference_endpoint

< >

( name: strnamespace: str | None = Nonerunning_ok: bool = Truetoken: bool | str | None = None ) → InferenceEndpoint

参数

  • name (str) — 要恢复的 Inference Endpoint 的名称。
  • namespace (str, 可选) — Inference Endpoint 所在的命名空间。默认值为当前用户。
  • running_ok (bool, 可选) — 如果为 True,则即使 Inference Endpoint 已在运行,该方法也不会引发错误。默认值为 True。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

已恢复的推理端点的相关信息。

恢复推理端点。

为了方便起见,您也可以使用 InferenceEndpoint.resume() 来恢复推理端点。

resume_scheduled_job

< >

( scheduled_job_id: strnamespace: str | None = Nonetoken: bool | str | None = None )

参数

  • scheduled_job_id (str) — 计划任务的 ID。
  • namespace (str,可选) — 计划任务所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

在 Hugging Face 基础设施上恢复(取消暂停)已计划的计算 Job。

revision_exists

< >

( repo_id: strrevision: strrepo_type: str | None = Nonetoken: str | bool | None = None )

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • revision (str) — 要检查的仓库版本。
  • repo_type (str, 可选) — 如果从数据集或 space 获取仓库信息,请设置为 "dataset" 或 "space"; 如果从模型获取仓库信息,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

检查 Hugging Face Hub 上的某个仓库是否存在特定的修订版本。

示例:

>>> from huggingface_hub import revision_exists
>>> revision_exists("google/gemma-7b", "float16")
True
>>> revision_exists("google/gemma-7b", "not-a-revision")
False

run_as_future

< >

( fn: Callable[..., R]*args**kwargs ) → Future

参数

  • fn (Callable) — 要在后台运行的方法。
  • *args, **kwargs — 调用该方法时使用的参数。

返回值

Future

一个 Future 实例,用于获取任务的结果。

在后台运行一个方法并返回一个 Future 实例。

主要目标是在不阻塞主线程的情况下运行方法(例如在训练期间推送数据)。 后台任务会排队以保持顺序,但不会并行执行。如果您需要通过并行化大量 API 调用来加速脚本,必须自行设置并使用 ThreadPoolExecutor。

注意:最常用的方法,例如 upload_file()、upload_folder() 和 create_commit(),都有一个 run_as_future: bool 参数,用于直接在后台调用它们。这相当于对它们调用 api.run_as_future(...),但写法更简洁。

示例:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> future = api.run_as_future(api.whoami) # instant
>>> future.done()
False
>>> future.result() # wait until complete and return result
(...)
>>> future.done()
True

run_job

< >

( image: strcommand: list[str]env: dict[str, Any] | None = Nonesecrets: dict[str, Any] | None = Noneflavor: JobHardware | str | None = Nonetimeout: int | float | str | None = Noneattempts: int | None = Nonename: str | None = Nonelabels: dict[str, str] | None = Nonevolumes: list[Volume] | None = Noneexpose: list[int] | None = Noneexpose_public: list[int] | None = Nonessh: bool = Falsenetwork_group: str | None = Nonenetwork_aliases: list[str] | None = Noneresource_group_id: str | None = Nonenamespace: str | None = Nonetoken: bool | str | None = None )

参数

  • image (str) — 要使用的 Docker 镜像。 示例:"ubuntu"、"python:3.12"、"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"。 使用来自 Space 的镜像的示例:"hf.co/spaces/lhoestq/duckdb"。
  • command (list[str]) — 要运行的命令。示例:["echo", "hello"]。
  • env (dict[str, Any],可选) — 定义 Job 的环境变量。
  • secrets (dict[str, Any], 可选) — 定义 Job 的机密环境变量。
  • flavor (str, 可选) — 硬件的规格。有关可能的值,请参阅 JobHardware。 默认值为 "cpu-basic"。
  • timeout (Union[int, float, str], 可选) — Job 的最大持续时间:int 类型,单位为 s(秒,默认)、m(分钟)、h(小时)或 d(天)。 示例:300 或 "5m" 表示 5 分钟。
  • attempts (int, 可选) — 最大尝试次数,包括初始运行。默认为 1。例如,3 表示对失败的 Job 最多重试 2 次。
  • name (str, 可选) — Job 的名称。作为 name 标签存储。不能与 labels 中的 name 键同时传入。名称无需唯一。默认值是从镜像和命令派生的名称(带有短哈希后缀)。
  • labels (dict[str, str],可选) — 要附加到任务上的标签(键值对)。
  • volumes (list[Volume],可选) — 要挂载到作业容器中的 Hugging Face Buckets 或 Repos。 每个卷都是一个 Volume,包含 type("bucket"、"model"、"dataset" 或 "space")、 source(例如 "username/my-bucket")以及 mount_path(例如 "/data")。
  • expose (list[int], 可选) — 通过 jobs 代理暴露的容器端口。列表中指定的每个端口都可通过公共 jobs 域名访问(例如 https://<job_id>--8000.hf.jobs)。访问始终需要具有该 job 命名空间读取权限的 HF token。如需未认证访问,请使用 expose_public。
  • expose_public (list[int], 可选) — 通过 Jobs 代理公开且无需身份验证的端口。这些端口无需在 expose 中列出。
  • ssh (bool, 可选) — 如果为 True,则可以通过 job.status.ssh_url 指定的 URL 通过 SSH 访问该作业的容器 (例如 ssh <job_id>@ssh.hf.jobs,或从 CLI 执行 hf jobs ssh <job_id>)。连接需要 对作业命名空间具有写入权限,并在 Hub 上注册 SSH 公钥 (https://huggingface.co/settings/keys)。默认为 False。
  • network_group (str, 可选) — 要加入的网络组名称。位于同一命名空间和资源组中且共享同一组的作业会被放置在一起,并可在所有端口上相互访问。在每个成员内部, HF_NETWORK_GROUP_HOSTNAME 会解析为该组的所有成员。仅允许小写字母、数字和连字符, 最多 46 个字符。
  • network_aliases (list[str], 可选) — 此任务在其网络组中声明的别名。成员可通过 ${HF_NETWORK_GROUP_PREFIX}<alias> 访问声明了该别名的任务。多个任务可以声明相同的别名。仅允许小写字母、数字和连字符,最长 34 个字符,且在任务内唯一。需要 network_group。
  • resource_group_id (str, 可选) — 用于创建 Job 的资源组 ID。用于控制组织内资源的访问权限,以及成本归属/支出限制功能。如果未提供,则 Job 将在任何资源组之外创建。
  • namespace (str,可选) — Job 将创建所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

在 Hugging Face 基础设施上运行计算任务。

示例:

运行您的第一个 Job:

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

运行 GPU 任务:

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

使用卷运行任务:

>>> from huggingface_hub import Volume, run_job
>>> dataset_volume = Volume(type="dataset", source="HuggingFaceFW/fineweb", mount_path="/data")
>>> output_bucket_volume = Volume(type="bucket", source="username/my-bucket", mount_path="/output")
>>> image = "duckdb/duckdb"
>>> command = ["duckdb", "-c", "COPY (SELECT * FROM '/data/**/*.parquet' LIMIT 5) TO '/output/first-rows.parquet'"]
>>> run_job(image=image, command=command, volumes=[dataset_volume, output_bucket_volume])

run_uv_job

< >

( script: strscript_args: list[str] | None = Nonedependencies: list[str] | None = Nonepython: str | None = Noneimage: str | None = Noneenv: dict[str, Any] | None = Nonesecrets: dict[str, Any] | None = Noneflavor: JobHardware | str | None = Nonetimeout: int | float | str | None = Noneattempts: int | None = Nonename: str | None = Nonelabels: dict[str, str] | None = Nonevolumes: list[Volume] | None = Noneexpose: list[int] | None = Noneexpose_public: list[int] | None = Nonessh: bool = Falsenetwork_group: str | None = Nonenetwork_aliases: list[str] | None = Noneresource_group_id: str | None = Nonenamespace: str | None = Nonetoken: bool | str | None = None )

参数

  • script (str) — UV 脚本的路径或 URL,或一个命令。
  • script_args (list[str], 可选) — 传递给脚本或命令的参数。
  • dependencies (list[str], 可选) — 用于运行 UV 脚本的依赖项。
  • python (str,可选) — 使用特定的 Python 版本。默认为 3.12。
  • image (str,可选,默认为 “ghcr.io/astral-sh/uv —python3.12-bookworm”): 使用已安装 uv 的自定义 Docker 镜像。
  • env (dict[str, Any],可选) — 定义 Job 的环境变量。
  • secrets (dict[str, Any], 可选) — 定义 Job 的机密环境变量。
  • flavor (str, 可选) — 硬件的规格。有关可能的值,请参阅 JobHardware。 默认值为 "cpu-basic"。
  • timeout (Union[int, float, str], 可选) — Job 的最大持续时间:int 类型,单位为 s(秒,默认)、m(分钟)、h(小时)或 d(天)。 示例:300 或 "5m" 表示 5 分钟。
  • attempts (int, 可选) — 最大尝试次数,包括初始运行。默认为 1。
  • name (str, 可选) — Job 的名称。作为 name 标签存储。不能与 labels 中的 name 键同时传入。名称无需唯一。默认值由脚本及其参数派生(附带一个短哈希后缀)。
  • labels (dict[str, str],可选) — 要附加到任务上的标签(键值对)。
  • volumes (list[Volume],可选) — 要挂载到作业容器中的 Hugging Face Buckets 或 Repos。 每个卷都是一个 Volume,包含 type("bucket"、"model"、"dataset" 或 "space")、 source(例如 "username/my-bucket")以及 mount_path(例如 "/data")。
  • expose (list[int], 可选) — 通过 jobs 代理暴露的容器端口。列表中指定的每个端口都可通过公共 jobs 域名访问(例如 https://<job_id>--8000.hf.jobs)。访问始终需要具有该 job 命名空间读取权限的 HF token。如需未认证访问,请使用 expose_public。
  • expose_public (list[int], 可选) — 通过 Jobs 代理公开且无需身份验证的端口。这些端口无需在 expose 中列出。
  • ssh (bool, 可选) — 如果为 True,则可以通过 job.status.ssh_url 指定的 URL 通过 SSH 访问该作业的容器 (例如 ssh <job_id>@ssh.hf.jobs,或从 CLI 执行 hf jobs ssh <job_id>)。连接需要 对作业命名空间具有写入权限,并在 Hub 上注册 SSH 公钥 (https://huggingface.co/settings/keys)。默认为 False。
  • network_group (str, 可选) — 要加入的网络组名称。位于同一命名空间和资源组中且共享同一组的作业会被放置在一起,并可在所有端口上相互访问。在每个成员内部, HF_NETWORK_GROUP_HOSTNAME 会解析为该组的所有成员。仅允许小写字母、数字和连字符, 最多 46 个字符。
  • network_aliases (list[str], 可选) — 此任务在其网络组中声明的别名。成员可通过 ${HF_NETWORK_GROUP_PREFIX}<alias> 访问声明了该别名的任务。多个任务可以声明相同的别名。仅允许小写字母、数字和连字符,最长 34 个字符,且在任务内唯一。需要 network_group。
  • resource_group_id (str, 可选) — 用于创建 Job 的资源组 ID。用于控制组织内资源的访问权限,以及成本归属/支出限制功能。如果未提供,则 Job 将在任何资源组之外创建。
  • namespace (str,可选) — Job 将创建所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

在 Hugging Face 基础设施上运行 UV 脚本任务。

与 hf jobs uv run 不同,此方法会忽略 UV 脚本的 PEP 723 头部中可能携带的可选 [tool.hf-jobs] 表(参见 Jobs 指南):启动配置必须在此处显式传入。

示例:

从 URL 运行脚本:

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

运行本地脚本:

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

运行命令:

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

挂载卷,例如在训练期间保存模型检查点:

>>> from huggingface_hub import Volume, run_uv_job
>>> script = "my_sft.py"
>>> script_args = ["--output_dir", "/training-outputs/training-v3-final", ...]
>>> checkpoints_bucket = Volume(type="bucket", source="username/my-bucket", mount_path="/training-outputs")
>>> run_uv_job(script, script_args=script_args, volumes=[checkpoints_bucket])

scale_to_zero_inference_endpoint

< >

( name: strnamespace: str | None = Nonetoken: bool | str | None = None ) → InferenceEndpoint

参数

  • name (str) — 要缩容至零的 Inference Endpoint 的名称。
  • namespace (str, 可选) — Inference Endpoint 所在的命名空间。默认值为当前用户。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

有关缩容至零的推理端点的信息。

将推理端点缩放到零。

缩放为零的推理端点不会产生费用。在下次请求时,它将恢复运行,但会伴随冷启动延迟。这与使用 pause_inference_endpoint() 暂停推理端点不同,后者需要通过 resume_inference_endpoint() 手动恢复。

为了方便起见,您也可以通过 InferenceEndpoint.scale_to_zero() 将推理端点缩容至零。

search_spaces

< >

( query: strfilter: str | Iterable[str] | None = Nonesdk: str | list[str] | None = Noneinclude_non_running: bool = Falsetoken: bool | str | None = None ) → Iterable[SpaceSearchResult]

参数

  • query (str) — 搜索查询字符串。
  • filter (str 或 Iterable[str],可选) — 用于筛选的字符串标签或标签列表。
  • sdk (str 或 list[str],可选) — 按 SDK 进行筛选(例如 "gradio"、"docker"、"static")。
  • include_non_running (bool, 可选) — 是否在结果中包含未运行的 Spaces。默认为 False。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

Iterable[SpaceSearchResult]

SpaceSearchResult 对象的可迭代对象。

在 Hub 上使用语义搜索查找搜索空间。

此端点使用语义搜索(基于嵌入)处理多词查询,并使用全文搜索处理单词查询。

示例:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> results = list(api.search_spaces("generate image"))
>>> results[0].id
'mrfakename/Z-Image-Turbo'
>>> results[0].ai_category
'Image Generation'

set_space_sleep_time

< >

( repo_id: strsleep_time: inttoken: bool | str | None = None ) → SpaceRuntime

参数

  • repo_id (str) — 要更新的仓库 ID。示例:"bigcode/in-the-stack"。
  • sleep_time (int, 可选) — 在将 Space 置于休眠状态之前,等待的无活动秒数。如果不想让 Space 暂停,请设置为 -1(这是升级后硬件的默认行为)。对于免费硬件,无法配置休眠时间(该值固定为 48 小时无活动)。 有关更多详细信息,请参阅 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

SpaceRuntime

有关 Space 的运行时信息,包括 Space 阶段和硬件。

为运行在升级硬件上的 Space 设置自定义休眠时间。

您的 Space 将在 X 秒无活动后进入休眠状态。当您的 Space 处于“sleep”模式时,您无需付费。如果有新访客访问您的 Space,它将“唤醒”该 Space。只有升级后的硬件才能配置可自定义的休眠时间。如需了解有关休眠阶段的更多信息,请参阅 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。

在请求硬件时,也可以通过 request_space_hardware() 设置自定义的休眠时间。

set_space_volumes

< >

( repo_id: strvolumes: list[Volume]token: bool | str | None = None )

参数

  • repo_id (str) — 要更新的 Space 的 ID。示例:"username/my-space"。
  • volumes (list[Volume]) — 要挂载的 Volume 对象列表。每个卷都有一个 type("bucket"、"model"、"dataset" 或 "space")、一个 source(仓库或存储桶 ID)、一个 mount_path(容器内的路径),以及可选的 revision、read_only 和 path 字段。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

引发

BadRequestError

  • BadRequestError — 如果该 Space 是静态 Space(静态 Space 不支持卷)。

为 Space 设置卷。

设置(或替换)在 Space 中挂载的卷列表。每个卷都会使 Space 的容器能够访问一个 Hub 资源(模型、数据集或存储桶)。

示例:

>>> from huggingface_hub import HfApi, Volume
>>> api = HfApi()
>>> api.set_space_volumes(
...     "username/my-space",
...     volumes=[
...         Volume(type="model", source="username/my-model", mount_path="/models", read_only=True),
...         Volume(type="bucket", source="username/my-bucket", mount_path="/data"),
...     ],
... )

snapshot_download

< >

( repo_id: strrepo_type: str | None = Nonerevision: str | None = Nonecache_dir: str | Path | None = Nonelocal_dir: str | Path | None = Noneetag_timeout: float = 10force_download: bool = Falsetoken: bool | str | None = Nonelocal_files_only: bool = Falseallow_patterns: list[str] | str | None = Noneignore_patterns: list[str] | str | None = Nonemax_workers: int = 8tqdm_class: type[base_tqdm] | None = Nonedry_run: bool = False ) → str or list of DryRunFileInfo

参数

  • repo_id (str) — 由/分隔的用户或组织名称以及仓库名称。
  • repo_type (str, 可选) — 如果从数据集或 space 下载,请设置为 "dataset" 或 "space"; 如果从模型下载,请设置为 None 或 "model"。默认值为 None。
  • revision (str, 可选) — 可选的 Git 修订版本 ID,可以是分支名称、标签或提交哈希值。
  • cache_dir (str, Path, 可选) — 存储缓存文件的文件夹路径。
  • local_dir (str 或 Path,可选) — 如果提供,下载的文件将放置在此目录下。
  • etag_timeout (float,可选,默认为 10) — 在获取 ETag 时,等待服务器发送数据的时间(秒数),超时后放弃,该值会传递给 httpx2.request。
  • force_download (bool,可选,默认为 False) — 即使文件已存在于本地缓存中,是否仍应下载该文件。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • local_files_only (bool,可选,默认为 False) — 如果为 True,则避免下载文件,并在本地缓存文件存在时返回其路径。
  • allow_patterns (list[str] 或 str,可选) — 如果提供,则仅下载至少匹配其中一个模式的文件。
  • ignore_patterns (list[str] 或 str,可选) — 如果提供,则匹配任一模式的文件不会被下载。
  • max_workers (int, 可选) — 用于下载文件的并发线程数(1 个线程 = 1 个文件下载)。 默认值为 8。
  • tqdm_class (tqdm, 可选) — 如果提供,将覆盖进度条的默认行为。传入的参数必须继承自 tqdm.auto.tqdm 或至少模拟其行为。 请注意,tqdm_class 不会传递给每个单独的下载任务。 默认使用自定义的 HF 进度条,可通过设置环境变量 HF_HUB_DISABLE_PROGRESS_BARS 来禁用。
  • dry_run (bool,可选,默认为 False) — 如果为 True,则执行试运行,而不会实际下载文件。返回一个包含 DryRunFileInfo 对象的列表,其中包含有关将下载内容的信息。

返回值

str 或 DryRunFileInfo 列表

  • 如果 dry_run=False:仓库快照的文件夹路径。
  • 如果 dry_run=True:一个包含下载信息的 DryRunFileInfo 对象列表。

引发

RepositoryNotFoundError 或 RevisionNotFoundError 或 EnvironmentError 或 OSError 或 ValueError

下载仓库文件。

下载指定修订版本中仓库文件的完整快照。当您希望获取仓库中的所有文件,且事先无法确定具体需要哪些文件时,此功能非常有用。所有文件都会嵌套在一个文件夹内,以保持其相对于该文件夹的实际文件名。您还可以使用 allow_patterns 和 ignore_patterns 来筛选要下载的文件。

如果提供了 local_dir,仓库中的文件结构将在此位置进行复制。使用此选项时,cache_dir 将不会被使用,并且会在 local_dir 的根目录下创建一个 .cache/huggingface/ 文件夹,用于存储与下载文件相关的某些元数据。虽然此机制不如主缓存系统那样稳健,但它针对定期拉取仓库最新版本进行了优化。

另一种方法是克隆该仓库,但这要求安装并正确配置 git 和 git-lfs。此外,使用 git 克隆仓库时,无法筛选要下载的文件。

space_info

< >

( repo_id: strrevision: str | None = Nonetimeout: float | None = Nonefiles_metadata: bool = Falseexpand: list[ExpandSpaceProperty_T] | None = Nonetoken: bool | str | None = None ) → SpaceInfo

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • revision (str, 可选) — 用于获取信息的 Space 仓库的版本。
  • timeout (float, 可选) — 是否为向 Hub 发送的请求设置超时时间。
  • files_metadata (bool, 可选) — 是否获取仓库中文件的元数据(大小、LFS 元数据等)。默认为 False。
  • expand (list[ExpandSpaceProperty_T], 可选) — 要在响应中返回的属性列表。使用此参数时,仅返回列表中的属性。 如果传递了 full,则不能使用此参数。 可能的值为 "author"、"cardData"、"createdAt"、"datasets"、"disabled"、"lastModified"、"likes"、"models"、"private"、"region"、"runtime"、"sdk"、"siblings"、"sha"、"subdomain"、"tags"、"trendingScore"、"usedStorage" 和 "resourceGroup"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

SpaceInfo

空间仓库信息。

获取 huggingface.co 上某个特定 Space 的信息。

如果传递了有效的令牌,Space 可以是私有的。

引发以下错误:

  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。
  • RevisionNotFoundError 如果找不到要下载的修订版本。

super_squash_history

< >

( repo_id: strbranch: str | None = Nonecommit_message: str | None = Nonerepo_type: str | None = Nonetoken: str | bool | None = None )

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • branch (str, 可选) — 要压缩的分支。默认为 "main" 分支的头部。
  • commit_message (str, 可选) — 用于压缩后提交的提交信息。
  • repo_type (str, 可选) — 如果列出的是数据集或 Space 的提交,请设置为 "dataset" 或 "space";如果列出的是模型的提交,请设置为 None 或 "model"。默认值为 None。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • RepositoryNotFoundError — 如果未找到仓库(错误 404):repo_id/repo_type 错误、仓库为私有但未进行身份验证,或仓库不存在。
  • RevisionNotFoundError — 如果找不到要压缩的分支。
  • BadRequestError — 如果分支引用无效。您不能在标签上压缩历史记录。

压缩 Hub 上某个仓库分支的提交历史。

当你预见到会进行数百次提交且不希望历史记录变得杂乱时,压缩仓库历史会很有用。压缩提交只能从分支的头部执行。

压缩后,提交历史将无法恢复。这是一个不可逆的操作。

一旦某个分支的历史记录被压缩,就无法再将其合并回其他分支,因为两者的历史记录已经分叉。

示例:

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

# Create repo
>>> repo_id = api.create_repo("test-squash").repo_id

# Make a lot of commits.
>>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"content")
>>> api.upload_file(repo_id=repo_id, path_in_repo="lfs.bin", path_or_fileobj=b"content")
>>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"another_content")

# Squash history
>>> api.super_squash_history(repo_id=repo_id)

suspend_scheduled_job

< >

( scheduled_job_id: strnamespace: str | None = Nonetoken: bool | str | None = None )

参数

  • scheduled_job_id (str) — 计划任务的 ID。
  • namespace (str,可选) — 计划任务所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

在 Hugging Face 基础设施上暂停已计划的计算 Job。

sync_bucket

< >

( source: str | None = Nonedest: str | None = Nonedelete: bool = Falseignore_times: bool = Falseignore_sizes: bool = Falseexisting: bool = Falseignore_existing: bool = Falseinclude: list[str] | None = Noneexclude: list[str] | None = Nonefilter_from: str | None = Noneplan: str | None = Noneapply: str | None = Nonedry_run: bool = Falseverbose: bool = Falsequiet: bool = Falsetoken: bool | str | None = None ) → [SyncPlan]

参数

  • source (str, 可选) — 源路径:本地目录或 hf://buckets/namespace/bucket_name(/prefix)。 除非使用 apply,否则此项为必填。
  • dest (str, 可选) — 目标路径:本地目录或 hf://buckets/namespace/bucket_name(/prefix)。 除非使用 apply,否则此项为必填。
  • delete (bool,可选,默认为 False) — 删除源中不存在的目标文件。
  • ignore_times (bool,可选,默认为 False) — 仅根据大小跳过文件,忽略修改时间。
  • ignore_sizes (bool,可选,默认为 False) — 仅根据修改时间跳过文件,忽略文件大小。
  • existing (bool,可选,默认为 False) — 在接收端跳过创建新文件(仅更新现有文件)。
  • ignore_existing (bool,可选,默认为 False) — 跳过接收端已存在的文件(仅创建新文件)。
  • include (list[str], 可选) — 包含匹配模式(fnmatch 风格)的文件。
  • exclude (list[str], 可选) — 排除匹配模式(fnmatch 风格)的文件。
  • filter_from (str, 可选) — 包含/排除规则过滤文件的路径。
  • plan (str, optional) — 将同步计划保存到此 JSONL 文件中,而不是执行它。
  • apply (str, optional) — 应用之前保存的计划文件。设置后,source 和 dest 不再是必需的。
  • dry_run (bool,可选,默认为 False) — 将同步计划以 JSONL 格式打印到标准输出,而不执行。
  • verbose (bool,可选,默认为 False) — 显示每个文件的详细操作。
  • quiet (bool,可选,默认为 False) — 抑制所有输出和进度条。
  • token (Union[bool, str, None], optional) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌。

返回值

[SyncPlan]

计算(或加载)的同步计划。

在本地目录和存储桶之间同步文件。

这等效于 hf buckets sync CLI 命令。source 或 dest 之一必须是 bucket 路径(hf://buckets/...),另一个必须是本地目录路径。

示例:

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

# Upload local directory to bucket
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket")

# Download bucket to local directory
>>> api.sync_bucket("hf://buckets/username/my-bucket", "./data")

# Sync with delete and filtering
>>> api.sync_bucket(
...     "./data",
...     "hf://buckets/username/my-bucket",
...     delete=True,
...     include=["*.safetensors"],
... )

# Dry run: preview what would be synced
>>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True)
>>> plan.summary()
{'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}

# Save plan for review, then apply
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl")
>>> api.sync_bucket(apply="sync-plan.jsonl")

sync_job_volume

< >

( source: str | Pathmount_path: strremote_name: str | None = Noneread_only: bool = Truenamespace: str | None = Nonetoken: bool | str | None = None ) → Volume

参数

  • source (str 或 Path) — 要同步的本地目录路径。
  • mount_path (str) — Job 容器内的挂载路径,例如 "/inputs"。必须以 / 开头。
  • remote_name (str, 可选) — 要同步到的存储桶子文件夹名称。默认值是从源路径和机器的主机名派生出的 {dirname}-{hash} 名称。
  • read_only (bool,可选,默认为 True) — 在 Job 中以只读方式挂载该卷。传入 False 可让 Job 将数据写回 bucket 文件夹(例如,以便之后使用 sync_bucket() 获取输出)。
  • namespace (str, 可选) — 拥有 jobs-artifacts 存储桶的命名空间。默认值为当前用户的命名空间。请使用与将挂载该卷的 Job 相同的命名空间。
  • token (Union[bool, str, None], 可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

返回值

音量

一个作用域限定于同步子文件夹的 bucket 卷,用于传入 run_job()、run_uv_job()、create_scheduled_job() 或 create_scheduled_uv_job() 的 volumes 列表。

将本地目录同步到存储桶,并返回一个可在 Job 中挂载的 Volume。

文件会上传到 {namespace}/jobs-artifacts 存储桶的子文件夹中(该存储桶会自动创建为私有;如果它已存在且为公开,则会发出警告),并使用与 sync_bucket() 相同的同步逻辑:对同一目录重新同步时,仅上传新增或已修改的文件。默认情况下,子文件夹名称由目录路径和机器的主机名派生,因此从同一目录重复调用会复用同一个远程文件夹。传入 remote_name 可改用固定名称。

请注意,数据是复制到存储桶中的,而非实时挂载:同步后在本地所做的更改对 Job 不可见(重新运行 sync_job_volume 以更新),并且卷默认以只读方式挂载。若要获取 Job 写入到可读写卷中的数据,请使用 sync_bucket() 将存储桶文件夹同步回本地。如果源目录为空(例如输出目录),则会上传一个占位符文件 .keep,以便卷仍然可以被挂载。

示例:

>>> from huggingface_hub import run_uv_job, sync_job_volume

# Upload ./training-data once, then run multiple jobs against it
>>> volume = sync_job_volume("./training-data", "/data")
>>> run_uv_job("train.py", script_args=["--learning-rate", "0.01"], volumes=[volume])
>>> run_uv_job("train.py", script_args=["--learning-rate", "0.05"], volumes=[volume])

# Read-write volume to retrieve outputs after the job completes
>>> volume = sync_job_volume("./outputs", "/outputs", read_only=False)
>>> job = run_uv_job("process.py", volumes=[volume])

trigger_scheduled_job

< >

( scheduled_job_id: strnamespace: str | None = Nonetoken: bool | str | None = None ) → JobInfo

参数

  • scheduled_job_id (str) — 计划任务的 ID。
  • namespace (str,可选) — 计划任务所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

返回值

JobInfo

有关已触发运行的信息。

  • HfHubHTTPError — 如果另一个实例已在运行,且计划任务上禁用了 concurrency,则返回 HTTP 409。

触发计划任务立即运行。

这会立即触发一次计划任务规范的执行。它不会修改计划,也不会影响下一次计划执行。如果已有实例正在运行,且该计划任务不允许并发执行,则请求将被拒绝(HTTP 409)。

不同于

< >

( repo_id: strtoken: bool | str | None = Nonerepo_type: str | None = None )

参数

  • repo_id (str) — 要取消点赞的仓库。示例:"user/my-cool-model"。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • repo_type (str, 可选) — 如果取消点赞数据集或空间,请设置为 "dataset" 或 "space";如果取消点赞模型,请设置为 None 或 "model"。默认值为 None。
  • RepositoryNotFoundError — 如果未找到仓库(错误 404):repo_id/repo_type 错误、仓库为私有但未进行身份验证,或仓库不存在。

与 Hub 上的某个特定仓库(例如从收藏夹中移除)不同。

为防止滥用,无法通过脚本对仓库执行like操作。

另请参阅 list_liked_repos()。

示例:

>>> from huggingface_hub import list_liked_repos, unlike
>>> "gpt2" in list_liked_repos().models # we assume you have already liked gpt2
True
>>> unlike("gpt2")
>>> "gpt2" in list_liked_repos().models
False

update_bucket_settings

< >

( bucket_id: strprivate: booltoken: bool | str | None = None )

参数

  • bucket_id (str) — 存储桶的 ID(例如 "username/my-bucket")。
  • private (bool) — 是否将存储桶设为私有。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

引发

BucketNotFoundError 或 or

  • BucketNotFoundError — 如果找不到存储桶。这可能是因为它不存在,
  • or — 因为它被设置为 private,且您没有访问权限。

更新 Hub 上存储桶的设置。

目前,唯一支持的设置是存储桶的可见性。

示例:

>>> from huggingface_hub import update_bucket_settings

>>> # Make a bucket public
>>> update_bucket_settings(bucket_id="Wauplin/first-bucket", private=False)

>>> # Make it private again
>>> update_bucket_settings(bucket_id="Wauplin/first-bucket", private=True)

update_collection_item

< >

( collection_slug: stritem_object_id: strnote: str | None = Noneposition: int | None = Nonetoken: bool | str | None = None )

参数

  • collection_slug (str) — 要更新的集合的 Slug。示例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。
  • item_object_id (str) — 集合中该项目的 ID。这不是该项目在 Hub 上的 ID(repo_id 或 paper id)。 必须从 CollectionItem 对象中获取。示例:collection.items[0].item_object_id。
  • note (str, 可选) — 要附加到集合中该项目的备注。备注的最大长度为 500 个字符。
  • position (int, 可选) — 该元素在集合中的新位置。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

更新集合中的某个项目。

示例:

>>> from huggingface_hub import get_collection, update_collection_item

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

# Update item based on its ID (add note + update position)
>>> update_collection_item(
...     collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
...     item_object_id=collection.items[-1].item_object_id,
...     note="Newly updated model!",
...     position=0,
... )

update_collection_metadata

< >

( collection_slug: strtitle: str | None = Nonedescription: str | None = Noneposition: int | None = Noneprivate: bool | None = Nonetheme: str | None = Nonetoken: bool | str | None = None )

参数

  • collection_slug (str) — 要更新的集合的 Slug。示例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。
  • title (str) — 要更新的集合的标题。
  • description (str, 可选) — 要更新的集合的描述。描述的最大长度为 150 个字符。
  • position (int, 可选) — 该集合在用户集合列表中的新位置。
  • private (bool,可选) — 集合是否应为私有。
  • theme (str, 可选) — Hub 上该集合的主题。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

更新 Hub 上集合的元数据。

所有参数均为可选。仅会更新已提供的元数据。

返回:Collection

示例:

>>> from huggingface_hub import update_collection_metadata
>>> collection = update_collection_metadata(
...     collection_slug="username/iccv-2023-64f9a55bb3115b4f513ec026",
...     title="ICCV Oct. 2023",
...     description="Portfolio of models, datasets, papers and demos I presented at ICCV Oct. 2023",
...     private=False,
...     theme="pink",
... )
>>> collection.slug
"username/iccv-oct-2023-64f9a55bb3115b4f513ec026"
# ^collection slug got updated but not the trailing ID

update_collection_resource_group

< >

( collection_slug: strresource_group_id: str | Nonetoken: bool | str | None = None )

参数

  • collection_slug (str) — 要更新的集合的 Slug。示例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。
  • resource_group_id (str 或 None) — 要分配给该集合的资源组,表示为 24 位十六进制字符串。如果为 None, 则将该集合从任何资源组中移除。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

将集合分配给资源组,或将其从任何资源组中移除。

仅适用于组织拥有的集合。

示例:

>>> from huggingface_hub import update_collection_resource_group
>>> update_collection_resource_group(
...     collection_slug="my-org/iccv-2023-64f9a55bb3115b4f513ec026",
...     resource_group_id="66980ecfc1e12a49c8f0e42d",
... )

update_inference_endpoint

< >

( name: straccelerator: str | None = Noneinstance_size: str | None = Noneinstance_type: str | None = Nonemin_replica: int | None = Nonemax_replica: int | None = Nonescale_to_zero_timeout: int | None = Nonescaling_metric: InferenceEndpointScalingMetric | None = Nonescaling_threshold: float | None = Nonerepository: str | None = Noneframework: str | None = Nonerevision: str | None = Nonetask: str | None = Nonecustom_image: dict | None = Nonecontainer_command: list[str] | None = Nonecontainer_args: list[str] | None = Nonetensor_parallel_size: int | None = Nonedata_parallel_size: int | None = Noneenv: dict[str, str] | None = Nonesecrets: dict[str, str] | None = Nonedomain: str | None = Nonepath: str | None = Nonecache_http_responses: bool | None = Nonetags: list[str] | None = Nonenamespace: str | None = Nonetoken: bool | str | None = None ) → InferenceEndpoint

参数

  • name (str) — 要更新的 Inference Endpoint 的名称。
  • accelerator (str,可选) — 用于推理的硬件加速器(例如 "cpu")。
  • instance_size (str, 可选) — 用于托管模型的实例大小或类型(例如 "x4")。
  • instance_type (str, 可选) — Inference Endpoint 将部署到的云实例类型(例如 "intel-icl")。
  • min_replica (int, 可选) — Inference Endpoint 保持运行的最小副本(实例)数量。
  • max_replica (int, 可选) — Inference Endpoint 可扩容到的最大副本(实例)数量。
  • scale_to_zero_timeout (int, 可选) — 非活动端点缩容至零之前的时长(以分钟为单位)。
  • scaling_metric (str 或 InferenceEndpointScalingMetric ,可选) — 用于缩放的指标引用。提供时,可以是 “pendingRequests” 或 “hardwareUsage”。 默认为 None。
  • scaling_threshold (float, 可选) — 用于触发扩容的缩放指标阈值。在未提供缩放指标时将被忽略。 默认值为 None。
  • repository (str, 可选) — 与推理端点关联的模型仓库名称(例如 "gpt2")。
  • framework (str, 可选) — 用于该模型的机器学习框架(例如 "custom")。
  • revision (str, 可选) — 要在 Inference Endpoint 上部署的特定模型修订版本(例如 "6c0e6080953db56375760c0471a8c5f2929baf11")。
  • task (str,可选) — 用于部署模型的任务(例如 "text-classification")。
  • custom_image (dict, 可选) — 要运行的容器镜像。可以是按镜像变体(例如 {"vLLM": {"url": "vllm/vllm-openai:v0.23.0", "port": 8000}‌},也可以是 sGLang、tgi、tei、llamacpp、hfServe 等)为键的字典,该字典将原样转发;也可以是一个描述自定义容器的扁平字典(例如 {"url": ..., "port": ...}),该字典将作为 {"custom": ...} 发送。
  • container_command (list[str], 可选) — 覆盖容器的入口点命令(对应 API 负载中的 model.command)。适用于托管引擎镜像(例如 vLLM、SGLang)和自定义镜像。
  • container_args (list[str], 可选) — 附加到容器入口点的参数(对应 API 负载中的 model.args)。适用于托管引擎镜像(例如 vLLM、SGLang)和自定义镜像。
  • tensor_parallel_size (int, 可选) — 用于将单个模型副本分片到多少个加速器上(适用于 vLLM 和 SGLang 镜像)。该值会写入引擎镜像配置中。由于 API 要求提供完整的 model.image,因此当未指定 custom_image 时,系统会获取当前端点上配置的镜像并就地更新。
  • data_parallel_size (int, 可选) — 要运行的模型副本数量,每个加速器一个(vLLM 镜像)。处理方式与 tensor_parallel_size 相同。
  • env (dict[str, str],可选) — 要注入到容器环境中的非机密环境变量
  • secrets (dict[str, str], 可选) — 要注入到容器环境中的机密值。
  • domain (str, 可选) — Inference Endpoint 部署的自定义域名。如果已设置,推理端点将可通过该域名访问(例如 "my-new-domain.cool-website.woof")。
  • path (str, 可选) — 已部署模型的自定义路径,应以 / 开头(例如 "/models/google-bert/bert-base-uncased")。
  • cache_http_responses (bool, 可选) — 是否缓存来自 Inference Endpoint 的 HTTP 响应。
  • tags (list[str],可选) — 要关联到推理端点的标签列表。
  • namespace (str, 可选) — 将更新 Inference Endpoint 的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

有关更新后的 Inference Endpoint 的信息。

更新推理端点。

此方法允许更新计算配置、已部署的模型、路由或它们的任意组合。 所有参数均为可选,但必须至少提供一个。

为了方便起见,您也可以通过 InferenceEndpoint.update() 来更新推理端点。

update_job_expose

< >

( job_id: strexpose: list[int] | None = Noneexpose_public: list[int] | None = Nonenamespace: str | None = Nonetoken: bool | str | None = None ) → JobInfo

参数

  • job_id (str) — 正在运行的 Job 的 ID。
  • expose (list[int], 可选) — 要通过 Jobs 代理公开的端口。访问需要具有该 Job 命名空间读取权限的 HF token。
  • expose_public (list[int], 可选) — 通过 Jobs 代理公开且无需身份验证的端口。这些端口无需在 expose 中列出。
  • namespace (str, 可选) — Job 的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 用户访问令牌。默认使用本地保存的令牌。

返回值

JobInfo

更新后的 Job。

在不重新运行的情况下,替换正在运行的 Job 的暴露端口。

expose 和 expose_public 共同构成完整的端口配置:不在任一列表中的端口将被关闭。如果两者都不传入,则关闭所有已暴露的端口。

update_job_labels

< >

( job_id: strlabels: dict[str, str]namespace: str | None = Nonetoken: bool | str | None = None ) → JobInfo

参数

  • job_id (str) — Job 的 ID。
  • labels (dict[str, str]) — 要设置在任务上的新标签。将替换所有现有标签。 键和值的长度均不得超过 100 个字符,且只能包含字母、数字、连字符和下划线。
  • namespace (str,可选) — Job 运行的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

返回值

JobInfo

更新后的任务信息。

更新现有 Job 的标签。

用新标签替换所有现有的用户提供的标签。

update_repo_settings

< >

( repo_id: strgated: Literal['auto', 'manual', False] | None = Noneprivate: bool | None = Nonevisibility: RepoVisibility_T | None = Nonetoken: str | bool | None = Nonerepo_type: str | None = None )

参数

  • repo_id (str) — 由 / 分隔的命名空间(用户或组织)和仓库名称。
  • gated (Literal["auto", "manual", False], 可选) — 仓库的访问控制状态。如果设置为 None ((默认值),则不会更新仓库的 gated 设置。
    • “auto”:该仓库受访问控制,访问请求将根据预定义标准自动批准或拒绝。
    • “manual”:该仓库受访问限制,访问请求需要人工审批。
    • False:该仓库未设置访问限制,任何人都可以访问。
  • private (bool,可选) — 是否应将仓库设为私有。不能与 visibility 同时传入。
  • visibility (Literal["public", "private", "protected"],可选) — 仓库的可见性。可以是 "public" 或 "private",对于 Spaces 也可以是 "protected"。
  • token (Union[str, bool, None], 可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。 若要禁用认证,请传入 False。
  • repo_type (str, 可选) — 要从中更新设置的仓库类型("model"、"dataset" 或 "space")。 默认为 "model"。

引发

ValueError 或 HfHubHTTPError 或 RepositoryNotFoundError

  • ValueError — 如果 gated 不是 “auto”、“manual” 或 False 之一。
  • ValueError — 如果 repo_type 不是 constants.REPO_TYPES 中的值之一。
  • HfHubHTTPError — 如果向 Hugging Face Hub API 发出的请求失败。
  • RepositoryNotFoundError — 如果找不到要下载的仓库。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。

更新仓库的设置,包括受控访问和可见性。

为了更精细地控制仓库的使用方式,Hub 允许仓库作者为其仓库启用访问请求功能,并更改仓库的可见性。

update_scheduled_job_labels

< >

( scheduled_job_id: strlabels: dict[str, str]namespace: str | None = Nonetoken: bool | str | None = None ) → ScheduledJobInfo

参数

  • scheduled_job_id (str) — 计划任务的 ID。
  • labels (dict[str, str]) — 要设置在计划任务上的新标签。将替换所有现有标签。 键和值的长度均不得超过 100 个字符,且只能包含字母数字、连字符和下划线。
  • namespace (str,可选) — 计划任务所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

返回值

ScheduledJobInfo

更新后的计划任务信息。

更新现有计划任务(Job)的标签。

用新标签替换所有现有的用户提供的标签。

update_scheduled_job_schedule

< >

( scheduled_job_id: strschedule: strnamespace: str | None = Nonetoken: bool | str | None = None ) → ScheduledJobInfo

参数

  • scheduled_job_id (str) — 计划任务的 ID。
  • schedule (str) — “@annually”、“@yearly”、“@monthly”、“@weekly”、“@daily”、“@hourly” 之一,或 CRON 调度表达式(例如,‘0 9 * * 1’ 表示每周一上午 9 点)。
  • namespace (str,可选) — 计划任务所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

返回值

ScheduledJobInfo

更新后的计划任务信息。

更改现有计划任务 Job 的运行时间。

仅更新调度:Job 的 spec、标签和 suspended 状态保持不变。若要立即运行一次已调度的 Job 而不更改其调度,请改用 trigger_scheduled_job()。

示例:

>>> from huggingface_hub import update_scheduled_job_schedule
>>> scheduled_job = update_scheduled_job_schedule(scheduled_job_id="6abb8dc9c617607c354d45f4", schedule="@daily")
>>> scheduled_job.schedule
'@daily'

update_webhook

< >

( webhook_id: strurl: str | None = Nonejob_id: str | None = Nonewatched: list[dict | WebhookWatchedItem] | None = Nonedomains: list[constants.WEBHOOK_DOMAIN_T] | None = Nonesecret: str | None = Nonesecrets: dict[str, str] | None = Nonetoken: bool | str | None = None ) → WebhookInfo

参数

  • webhook_id (str) — 要更新的 webhook 的唯一标识符。
  • url (str, 可选) — 用于发送负载的 URL。
  • job_id (str, 可选) — 用于通过 webhook 负载触发的源 Job 的 ID。在设置 secrets 时必填。
  • watched (list[WebhookWatchedItem], optional) — 要监控的项目列表。可以是用户、组织、模型、数据集或空间。 有关详细信息,请参阅 WebhookWatchedItem。监控的项目也可以以普通字典的形式提供。
  • domains (list[Literal["repo", "discussion"]], optional) — 要监控的域。可以包括“repo”、“discussion”或两者。
  • secret (str, 可选) — 用于对负载进行签名的密钥,提供额外的安全层。
  • secrets (dict[str, str], optional) — 由 webhook 触发的 Job 的机密环境变量。列出的键将替换已存储的值,空字符串会删除该机密,省略的键则保留其已存储的值。需要 job_id。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。

返回值

WebhookInfo

有关更新后的 webhook 的信息。

更新现有的 webhook。

示例:

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

upload_attachment

< >

( path: str | Pathtoken: bool | str | None = None ) → str

参数

  • path (str 或 Path) — 要上传的文件路径。支持的格式为 PNG、JPEG、GIF、WebP、MP4、MOV、WebM、MP3 和 WAV。 文件大小必须小于 10MB(视频为 50MB)。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。该令牌需要具有 discussion.write 权限。若要匿名上传,请传入 False。

返回值

str

已上传文件的 URL。

引发

ValueError

  • ValueError — 如果文件格式不受支持。

将图像、视频或音频文件上传到 Hub 并返回其 URL。

这就是 Hub 网页编辑器在你将文件拖入讨论或 Pull Request 评论框时所做的操作。在描述或评论中嵌入返回的 URL:对于图像使用 ![alt text](url),对于视频使用纯 URL,对于音频文件使用 <audio controls src="url"></audio>。

示例:

>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> url = api.upload_attachment("screenshot.png")
>>> api.create_discussion("username/my-model", title="Rendering bug", description=f"![screenshot]({url})")

upload_file

< >

( path_or_fileobj: str | Path | bytes | BinaryIOpath_in_repo: strrepo_id: strtoken: str | bool | None = Nonerepo_type: str | None = Nonerevision: str | None = Nonecommit_message: str | None = Nonecommit_description: str | None = Nonecreate_pr: bool | None = Noneparent_commit: str | None = Nonerun_as_future: bool = False_hot_reload: bool | None = None ) → CommitInfo or Future

参数

  • path_or_fileobj (str、Path、bytes 或 IO) — 本地机器上文件的路径,或二进制数据流 / fileobj / 缓冲区。
  • path_in_repo (str) — 仓库中的相对文件路径,例如: "checkpoints/1fec34a/weights.bin"
  • repo_id (str) — 文件将上传到的仓库,例如: "username/custom_transformers"
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • repo_type (str, 可选) — 如果上传到数据集、空间或内核仓库,请设置为 "dataset"、"space" 或 "kernel";如果上传到模型,请设置为 None 或 "model"。默认值为 None。
  • revision (str, 可选) — 要从中提交内容的 git 修订版本。默认为 "main" 分支的头部。
  • commit_message (str, 可选) — 生成的提交的摘要 / 标题 / 第一行
  • commit_description (str, 可选) — 生成的提交的描述
  • create_pr (boolean, 可选) — 是否使用该提交创建 Pull Request。默认为 False。 如果未设置 revision,则针对 "main" 分支打开 PR。如果 设置了 revision 且它是一个分支,则针对该分支打开 PR。如果 设置了 revision 但它不是分支名称(例如:一个 commit oid),服务器将返回 RevisionNotFoundError。
  • parent_commit (str, 可选) — 父提交的 OID / SHA,以十六进制字符串表示。也支持简写形式(前 7 个字符)。 如果指定了该参数且 create_pr 为 False,当 revision 未指向 parent_commit 时,提交将失败。 如果指定了该参数且 create_pr 为 True,拉取请求将从 parent_commit 创建。 指定 parent_commit 可确保在提交更改之前仓库未发生变化,这在仓库被并发更新 / 提交时尤为有用。
  • run_as_future (bool, 可选) — 是否将此方法在后台运行。后台任务按顺序执行,不会阻塞主线程。传入 run_as_future=True 将返回一个 Future 对象。默认为 False。

返回值

CommitInfo 或 Future

包含新创建提交(提交哈希、提交 URL、PR URL、提交信息……)信息的 CommitInfo 实例。如果传入 run_as_future=True,则返回一个 Future 对象,该对象在执行后将包含结果。

将本地文件(最大 50 GB)上传到指定的仓库。上传通过 HTTP post 请求完成,无需安装 git 或 git-lfs。

引发以下错误:

  • 如果 HuggingFace API 返回了错误,则抛出 HTTPError
  • 如果某些参数值无效,则抛出 ValueError
  • RepositoryNotFoundError 当找不到要下载的仓库时抛出。这可能是因为它不存在,或者它被设置为 private 且您没有访问权限。
  • RevisionNotFoundError 如果找不到要下载的修订版本。

upload_file 假定该仓库已存在于 Hub 上。如果遇到 Client error 404,请确保您已完成身份验证,您的 token 具有所需的权限, 并且 repo_id 和 repo_type 设置正确。如果仓库不存在, 请先使用 create_repo() 创建它。

示例:

>>> from huggingface_hub import upload_file

>>> with open("./local/filepath", "rb") as fobj:
...     upload_file(
...         path_or_fileobj=fileobj,
...         path_in_repo="remote/file/path.h5",
...         repo_id="username/my-dataset",
...         repo_type="dataset",
...         token="my_token",
...     )

>>> upload_file(
...     path_or_fileobj=".\\local\\file\\path",
...     path_in_repo="remote/file/path.h5",
...     repo_id="username/my-model",
...     token="my_token",
... )

>>> upload_file(
...     path_or_fileobj=".\\local\\file\\path",
...     path_in_repo="remote/file/path.h5",
...     repo_id="username/my-model",
...     token="my_token",
...     create_pr=True,
... )

upload_folder

< >

( repo_id: strfolder_path: str | Pathpath_in_repo: str | None = Nonecommit_message: str | None = Nonecommit_description: str | None = Nonetoken: str | bool | None = Nonerepo_type: str | None = Nonerevision: str | None = Nonecreate_pr: bool | None = Noneparent_commit: str | None = Noneallow_patterns: list[str] | str | None = Noneignore_patterns: list[str] | str | None = Nonedelete_patterns: list[str] | str | None = Nonerun_as_future: bool = False ) → CommitInfo or Future

参数

  • repo_id (str) — 文件将上传到的仓库,例如: "username/custom_transformers"
  • folder_path (str 或 Path) — 本地文件系统中要上传的文件夹路径
  • path_in_repo (str, 可选) — 仓库中目录的相对路径,例如: "checkpoints/1fec34a/results"。默认值为仓库的根目录。
  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • repo_type (str, 可选) — 如果上传到数据集、空间或内核仓库,请设置为 "dataset"、"space" 或 "kernel";如果上传到模型,请设置为 None 或 "model"。默认值为 None。
  • revision (str, 可选) — 要从中提交内容的 git 修订版本。默认为 "main" 分支的头部。
  • commit_message (str, 可选) — 生成的提交的摘要 / 标题 / 第一行。默认值为: f"Upload {path_in_repo} with huggingface_hub"
  • commit_description (str 可选) — 生成的提交的描述
  • create_pr (boolean, 可选) — 是否使用该提交创建 Pull Request。默认为 False。PR 始终针对默认分支打开:同时设置 create_pr=True 和 revision 会引发 ValueError。请注意,每次使用 create_pr=True 调用都会打开一个新的 pull request:若要恢复中断的上传并将其合并到现有的 PR 中,请改用 revision="refs/pr/N" 重新运行。
  • parent_commit (str, 可选) — 父提交的 OID / SHA,以十六进制字符串表示。也支持简写形式(前 7 个字符)。 如果指定了该参数且 create_pr 为 False,当 revision 未指向 parent_commit 时,提交将失败。 指定 parent_commit 可确保在提交更改之前仓库未发生变化,这在仓库被并发更新 / 提交时尤为有用。如果上传被拆分为多个提交(例如大型文件夹),parent_commit 仅适用于第一个提交。
  • allow_patterns (list[str] 或 str,可选) — 如果提供,则仅上传至少匹配其中一个模式的文件。
  • ignore_patterns (list[str] 或 str,可选) — 如果提供,则匹配任一模式的文件不会被上传。
  • delete_patterns (list[str] 或 str,可选) — 如果提供,则在提交新文件时,仓库中匹配任一模式的远程文件将被删除。当您不确定哪些文件已经上传时,此功能非常有用。 注意:为避免出现差异,即使 .gitattributes 文件匹配该模式,也不会被删除。
  • run_as_future (bool, 可选) — 是否将此方法在后台运行。后台任务按顺序执行,不会阻塞主线程。传入 run_as_future=True 将返回一个 Future 对象。默认为 False。

返回值

CommitInfo 或 Future

包含新创建提交(提交哈希、提交 URL、PR URL、提交信息……)信息的 CommitInfo 实例。如果传入 run_as_future=True,则返回一个 Future 对象,该对象在执行后将包含结果。

将本地文件夹上传到指定的仓库。上传通过 HTTP 请求完成,无需安装 git 或 git-lfs。

文件夹的结构将保持不变。仓库中已存在的同名文件将被覆盖,其他文件则保持不变。

使用 allow_patterns 和 ignore_patterns 参数来指定要上传的文件。这些参数接受单个模式或模式列表。模式是标准通配符(globbing 模式),文档见 此处。如果同时提供了 allow_patterns 和 ignore_patterns,则两个约束条件同时生效。默认情况下,会上传文件夹中的所有文件。

使用 delete_patterns 参数来指定要删除的远程文件。输入类型与 allow_patterns 相同(见上文)。如果同时提供了 path_in_repo,则模式将针对相对于该文件夹的路径进行匹配。例如,upload_folder(..., path_in_repo="experiment", delete_patterns="logs/*") 将删除 ./experiment/logs/ 下的任何远程文件。请注意,即使 .gitattributes 文件匹配这些模式,它也不会被删除。

任何子目录中存在的 .git/ 文件夹都会被忽略。但请注意,.gitignore 文件不会被考虑在内。

当 hf_xet 已安装(默认情况)时,文件通过流式管道上传:在文件夹仍在与 Hub 进行比对时,上传即已开始;文件在分块上传的同时进行哈希计算(单次读取遍历);大型文件夹会自动分批提交,以确保不超过服务器限制(后续提交的提交信息会带有 (part N) 后缀)。如果上传被中断,重新运行相同的调用即可恢复:已提交的文件会被跳过,已上传的数据会进行去重。当 hf_xet 未安装时,将回退到使用 create_commit() 创建的单次提交。

引发以下错误:

  • 如果 HuggingFace API 返回了错误,则抛出 HTTPError
  • 如果某些参数值无效,则抛出 ValueError

upload_folder 假定该仓库已存在于 Hub 上。如果遇到 Client error 404,请确保您已完成身份验证,您的 token 具有所需的权限,并且 repo_id 和 repo_type 设置正确。如果仓库不存在,请先使用 create_repo() 创建它。

示例:

# Upload checkpoints folder except the log files
>>> upload_folder(
...     folder_path="local/checkpoints",
...     path_in_repo="remote/experiment/checkpoints",
...     repo_id="username/my-dataset",
...     repo_type="datasets",
...     token="my_token",
...     ignore_patterns="**/logs/*.txt",
... )

# Upload checkpoints folder including logs while deleting existing logs from the repo
# Useful if you don't know exactly which log files have already being pushed
>>> upload_folder(
...     folder_path="local/checkpoints",
...     path_in_repo="remote/experiment/checkpoints",
...     repo_id="username/my-dataset",
...     repo_type="datasets",
...     token="my_token",
...     delete_patterns="**/logs/*.txt",
... )

# Upload checkpoints folder while creating a PR
>>> upload_folder(
...     folder_path="local/checkpoints",
...     path_in_repo="remote/experiment/checkpoints",
...     repo_id="username/my-dataset",
...     repo_type="datasets",
...     token="my_token",
...     create_pr=True,
... )

verify_repo_checksums

< >

( repo_id: strrepo_type: str | None = Nonerevision: str | None = Nonelocal_dir: str | Path | None = Nonecache_dir: str | Path | None = Nonetoken: str | bool | None = None ) → FolderVerification

参数

  • repo_id (str) — 由/分隔的命名空间(用户或组织)和仓库名称。
  • repo_type (str, 可选) — 要从中获取树的仓库类型("model"、"dataset" 或 "space"。 默认为 "model"。
  • revision (str, 可选) — 要获取树的仓库版本。默认为 "main" 分支。
  • local_dir (str 或 Path,可选) — 要验证的本地目录。
  • cache_dir (str 或 Path,可选) — 要验证的缓存目录。
  • token (Union[bool, str, None], optional) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。 若要禁用认证,请传入 False。

返回值

FolderVerification

包含验证详情的结构化结果。

  • RepositoryNotFoundError — 如果未找到仓库(错误 404):repo_id/repo_type 错误、仓库为私有但未进行身份验证,或仓库不存在。
  • RevisionNotFoundError — 如果在仓库中未找到该 revision(错误 404)。

针对 Hub 校验和验证仓库的本地文件。

wait_for_job

< >

( job_id: str | list[str]timeout: float | None = Nonepoll_interval: float = 1.0stages: list[JobStage] | None = Nonenamespace: str | None = Nonetoken: bool | str | None = None ) → JobInfo or list[JobInfo]

参数

  • job_id (str 或 list[str]) — Job 的 ID,或要等待的 Job ID 列表。如果传入列表,则返回一个 JobInfo 列表(顺序相同)。
  • timeout (float, 可选) — 等待 Job 完成的最长时间,单位为秒。如果为 None,则会无限期等待。
  • poll_interval (float, 可选) — 每次状态检查之间的等待时间,以秒为单位。默认为 1 秒。
  • stages (list[JobStage],可选) — 要等待的阶段。默认为终止阶段("COMPLETED"、"CANCELED"、 "ERROR"、"DELETED")。例如,传入 [JobStage.RUNNING] 以等待 Job 开始运行。 无论此值如何,终止阶段始终会停止等待。
  • namespace (str,可选) — Job 所在的命名空间。默认值为当前用户的命名空间。
  • token (bool 或 str,可选) — 有效的用户访问令牌。如果未提供,将使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。 请参阅:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

返回值

JobInfo 或 list[JobInfo]

最终的 Job 信息。

引发

TimeoutError

  • TimeoutError — 如果在 timeout 秒后,至少有一个 Job 未达到目标阶段之一。

等待 Hugging Face 基础设施上的一个或多个计算 Job 达到指定阶段。

每个 Job 状态都会每隔 poll_interval 秒轮询一次(通过 inspect_job()),直到其 stage 变为 stages 之一(默认为终止阶段:"COMPLETED"、"CANCELED"、"ERROR" 或 "DELETED")。在所有情况下都会返回最终的 JobInfo:失败或已取消的 Job 不会抛出异常——请检查 job.status.stage 以根据结果采取相应操作。

终止阶段始终会停止等待,即使未列在 stages 中。这可以避免无限期地等待 Job 永远不会到达的阶段(例如,等待一个在调度期间失败的 Job 进入 "RUNNING" 状态)。

示例:

>>> from huggingface_hub import run_job, wait_for_job
>>> job = run_job(image="python:3.12", command=["python", "-c", "print('Hello from HF compute!')"])
>>> wait_for_job(job_id=job.id).status.stage
'COMPLETED'

wait_for_space

< >

( repo_id: strtimeout: float | None = Nonepoll_interval: float = 1.0token: bool | str | None = None ) → SpaceRuntime

参数

  • repo_id (str) — 要等待的 Space 的 ID。示例:"username/my-space"。
  • timeout (float, 可选) — 最大等待时间(秒)。如果为 None,则无限期等待。
  • poll_interval (float, 可选) — 状态检查之间的间隔秒数。默认为 1 秒。
  • token (bool 或 str,可选) — 有效的用户访问令牌。默认使用本地保存的令牌,这是推荐的认证方式。设置为 False 可禁用认证。参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication。

返回值

SpaceRuntime

当 Space 到达最终阶段时的最终运行时信息。

引发

TimeoutError

  • TimeoutError — 如果 Space 在 timeout 秒后仍未到达终止阶段。

等待 Space 到达终止阶段(非构建中/启动中)。

轮询操作每隔 poll_interval 秒调用一次 get_space_runtime(),直到 Space 的阶段不再是中间状态(BUILDING、RUNNING_BUILDING、APP_STARTING、RUNNING_APP_STARTING)。在所有情况下均返回最终的 SpaceRuntime——请检查 runtime.stage 以根据结果采取行动(例如 RUNNING 与 BUILD_ERROR)。

示例:

>>> from huggingface_hub import restart_space, wait_for_space
>>> restart_space("username/my-space")
>>> runtime = wait_for_space("username/my-space")
>>> runtime.stage
'RUNNING'

whoami

< >

( token: bool | str | None = Nonecache: bool = False )

参数

  • token (bool 或 str,可选) — 有效的用户访问令牌(字符串)。默认使用本地保存的令牌,这是推荐的认证方式(参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要禁用认证,请传入 False。
  • cache (bool, 可选) — 是否缓存 whoami 调用的结果以供后续调用使用。 如果首次调用期间发生错误,则不会进行缓存。 默认值为 False。

调用 HF API 以获取“whoami”信息。

如果传入 cache=True,结果将在 Python 进程存续期间被缓存,供后续调用使用。如果您计划多次调用 whoami,这将非常有用,因为出于安全考虑,该端点的速率限制非常严格。

API 数据类

AccessRequest

类 huggingface_hub.hf_api.AccessRequest

< >

( username: str | Nonerequest_id: strfullname: str | Noneemail: str | Nonetimestamp: datetimestatus: Literal['pending', 'accepted', 'rejected']fields: dict[str, Any] | None = None )

参数

  • username (str, 可选) — 请求访问的用户名。如果仓库配置为不共享请求者的用户名,则为 None。在这种情况下,请使用 request_id 来接受、拒绝或取消该请求。
  • request_id (str) — 访问请求的 ID。即使未共享用户名,也始终会设置。
  • fullname (str, 可选) — 请求访问的用户的全名。如果仓库配置为不共享请求者的用户名,则为 None。
  • email (str, 可选) — 请求访问的用户的电子邮件地址。如果用户被手动授予访问权限,或者仓库配置为不共享请求者的电子邮件地址,则为 None。
  • timestamp (datetime) — 请求的时间戳。
  • status (Literal["pending", "accepted", "rejected"]) — 请求的状态。可以是 ["pending", "accepted", "rejected"] 之一。
  • fields (dict[str, Any],可选) — 用户在门控表单中填写的附加字段。

包含用户访问请求信息的数据结构。

BucketFile

class huggingface_hub.BucketFile

< >

( **kwargs )

包含 Hub 上存储桶中某个文件的信息。此对象由 list_bucket_tree() 返回。

类似于 RepoFile,但用于存储桶中的文件。

BucketFileMetadata

class huggingface_hub.BucketFileMetadata

< >

( size: intxet_file_data: XetFileData )

参数

  • size (int) — 文件的字节大小。
  • xet_file_data (XetFileData) — 该文件的 Xet 信息(哈希值和刷新路由)。

包含存储桶中文件信息的数据结构。

由 get_bucket_file_metadata() 返回。

BucketInfo

class huggingface_hub.BucketInfo

< >

( **kwargs )

参数

  • id (str) — 桶的 ID。
  • private (bool) — 该存储桶是否为私有。
  • created_at (datetime) — 该 bucket 在 Hub 上的创建日期。
  • size (int) — 桶的字节大小。
  • total_files (int) — 存储桶中的文件总数。

包含 Hub 上某个存储桶的信息。此对象由 bucket_info() 和 list_buckets() 返回。

BucketUrl

类 huggingface_hub.BucketUrl

< >

( url: strendpoint: str = '' )

参数

  • url (str) — 存储桶 URL 的字符串值。
  • endpoint (str,可选) — Hub 的端点。默认为 https://huggingface.co。

描述 Hub 上的存储桶 URL。

BucketUrl 由 create_bucket() 返回。在初始化时,会解析该 URL 以填充属性:

  • endpoint(str)
  • 命名空间(str)
  • bucket_id (str)
  • url (str)
  • uri (HfUri)

DatasetLeaderboardEntry

类 huggingface_hub.DatasetLeaderboardEntry

< >

( **kwargs )

参数

  • rank (int) — 模型在排行榜上的排名(从 1 开始)。
  • model_id (str) — 模型的 ID(例如 "meta-llama/Llama-3-8b")。
  • value (float) — 评估分数值。
  • filename (str) — 包含评估数据的结果文件的名称。
  • verified (bool) — 结果是否已验证。
  • source (dict[str, Any],可选) — 评估结果来源的信息。包含诸如 "url"、"name" 和 "isExternal" 等键。并非所有条目都有来源。
  • author(User 或 Organization)— 模型作者,根据 API 响应中的 "type" 字段解析得出。
  • pull_request (int, 可选) — 与排行榜条目关联的拉取请求编号(如果有的话)。
  • notes (str, 可选) — 与排行榜条目相关的备注(如有)。

包含 Hub 上数据集排行榜中单个条目的信息。

排行榜根据模型在特定基准数据集上的评估分数对模型进行排名。 此对象由 get_dataset_leaderboard() 返回。若要获取特定模型在各基准上的评估结果,请参阅 ModelInfo.eval_results(通过 model_info() 并设置 expand=["evalResults"])以及 EvalResultEntry。

EvalResultEntry

类 huggingface_hub.EvalResultEntry

< >

( dataset_id: strtask_id: strvalue: typing.Anydataset_revision: str | None = Noneverify_token: str | None = Nonedate: str | None = Nonesource_url: str | None = Nonesource_name: str | None = Nonesource_user: str | None = Nonesource_org: str | None = Nonenotes: str | None = None )

参数

  • dataset_id (str) — 来自 Hub 的基准数据集 ID。示例:“cais/hle”、“Idavidrein/gpqa”。
  • task_id (str) — 基准测试中的任务标识符。示例:“gpqa_diamond”。
  • value (Any) — 指标值。示例:20.90。
  • dataset_revision (str, 可选) — 基准数据集的 Git SHA。
  • verify_token (str, 可选) — 一个签名,可用于证明评估过程是可审计且可复现的。
  • date (str,可选) — 评估运行的时间(ISO-8601 日期时间)。默认为 git 提交时间。
  • source_url (str, 可选) — 评估来源的链接(例如 https://huggingface.co/spaces/SaylorTwift/smollm3-mmlu-pro)。如果提供了 source_name、source_user 或 source_org,则此项为必填。
  • source_name (str, 可选) — 来源的显示名称。示例:“Eval Logs”。
  • source_user (str, 可选) — 用于署名归属的 HF 用户名。示例:“celinah”。
  • source_org (str, 可选) — 用于归属的 HF 组织名称。示例:“cais”。
  • notes (str, optional) — Details about the evaluation setup. Example: “tools”, “no-tools”, “chain-of-thought”.

.eval_results/*.yaml 格式的评估结果条目。

表示存储在模型仓库中的评估分数,这些分数会自动显示在模型页面和基准数据集的排行榜上。

对于 README.md 中的旧版 model-index 格式,请改用 EvalResult。

有关更多详细信息,请参阅 https://huggingface.co/docs/hub/eval-results。

示例:

>>> from huggingface_hub import EvalResultEntry
>>> # Minimal example with required fields only
>>> result = EvalResultEntry(
...     dataset_id="Idavidrein/gpqa",
...     task_id="gpqa_diamond",
...     value=0.412,
... )
>>> # Full example with all fields
>>> result = EvalResultEntry(
...     dataset_id="cais/hle",
...     task_id="default",
...     value=20.90,
...     dataset_revision="5503434ddd753f426f4b38109466949a1217c2bb",
...     verify_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
...     date="2025-01-15T10:30:00Z",
...     source_url="https://huggingface.co/datasets/cais/hle",
...     source_name="CAIS HLE",
...     source_org="cais",
...     notes="no-tools",
... )

SyncOperation

类 huggingface_hub.SyncOperation

< >

( action: typing.Literal['upload', 'download', 'delete', 'skip']path: strsize: int | None = Nonereason: str = ''local_mtime: str | None = Noneremote_mtime: str | None = Nonebucket_file: huggingface_hub._buckets.BucketFile | None = None )

表示要执行的同步操作。

SyncPlan

类 huggingface_hub.SyncPlan

< >

( source: strdest: strtimestamp: stroperations: list = <factory> )

表示一个完整的同步计划。

CommitInfo

类 huggingface_hub.CommitInfo

< >

( commit_url: str*args**kwargs )

参数

  • commit_url (str) — 查找该 commit 的 URL。
  • commit_message (str) — 已创建的提交的摘要(第一行)。
  • commit_description (str) — 已创建的提交的描述。可以为空。
  • oid (str) — 提交哈希 ID。示例:"91c54ad1727ee830252e457677f467be0bfd8a57"。
  • pr_url (str, 可选) — 已创建的 PR 的 URL(如果存在)。当传入 create_pr=True 时填充。
  • pr_revision (str, 可选) — 已创建的 PR 的版本(如果存在)。当传入 create_pr=True 时填充。示例:"refs/pr/1"。
  • pr_num (int, 可选) — 如果已创建,则为所创建的 PR 讨论的编号。当传入 create_pr=True 时填充。可以作为 discussion_num 传入 get_discussion_details()。示例:1。
  • repo_url (RepoUrl) — 包含 repo_id、repo_type 等信息的提交(commit)的仓库 URL。

包含新创建的提交信息的数据结构。

由 Hub 上创建提交的所有方法返回:create_commit()、upload_file()、upload_folder()、delete_file()、delete_folder()。为了向后兼容,它继承自 str,但使用 str 特有的方法已被弃用。

DatasetInfo

类 huggingface_hub.DatasetInfo

< >

( **kwargs )

参数

  • id (str) — 数据集的 ID。
  • author (str) — 数据集的作者。
  • card_data (DatasetCardData,可选) — 以 huggingface_hub.repocard_data.DatasetCardData 对象形式提供的数据集卡片元数据。
  • citation (str, 可选) — 数据集的引用信息。
  • created_at (datetime, 可选) — 该仓库在 Hub 上的创建日期。请注意,最低值为 2022-03-02T23:29:04.000Z,对应我们开始存储创建日期的日期。
  • description (str, 可选) — 数据集的描述。
  • disabled (bool,可选) — 仓库是否已禁用。
  • downloads (int) — 过去 30 天内该数据集的下载次数。
  • downloads_all_time (int) — 自数据集创建以来累计的下载次数。
  • gated (Literal["auto", "manual", False], 可选) — 该仓库是否受访问限制。 如果是,则指定审批方式为手动或自动。
  • last_modified (datetime, 可选) — 仓库最后一次提交的时间。
  • likes (int) — 数据集的点赞数。
  • main_size (int, 可选) — 数据集主分支的字节大小。
  • paperswithcode_id (str, 可选) — 数据集的 Papers with code ID。
  • private (bool) — 仓库是否为私有。
  • resource_group (dict, 可选) — 数据集的资源组信息。
  • sha (str) — 此特定修订版本的仓库 SHA。
  • siblings (list[RepoSibling]) — 构成该数据集的 huggingface_hub.hf_api.RepoSibling 对象列表。
  • tags (list[str]) — 数据集的标签列表。
  • trending_score (int,可选) — 数据集的热门分数。
  • used_storage (int,可选) — 数据集在 Hub 上的大小(以字节为单位)。

包含 Hub 上数据集的信息。此对象由 dataset_info() 和 list_datasets() 返回。

此类的大多数属性都是可选的。这是因为 Hub 返回的数据取决于所执行的查询。 通常,查询越具体,返回的信息就越多。相反,在使用 list_datasets() 列出数据集时,仅返回部分属性。

DryRunFileInfo

类 huggingface_hub.DryRunFileInfo

< >

( commit_hash: strfile_size: int | Nonefilename: strlocal_path: stris_cached: boolwill_download: bool )

参数

  • commit_hash (str) — 与该文件相关的 commit_hash。
  • file_size (int, 可选) — 文件大小(如果已知)。对于 LFS 文件,包含实际 LFS 文件的大小,而非指针的大小。
  • filename (str) — 仓库中文件的名称。
  • is_cached (bool) — 文件是否已在本地缓存。
  • will_download (bool) — 如果以 dry_run=False 调用 hf_hub_download,文件是否会被下载。 实际上,如果文件未缓存或 force_download=True,则 will_download 为 True。

执行文件下载试运行(dry run)时返回的信息。

当 dry_run=True 时,由 hf_hub_download() 返回。

DuplicatedRepoUrl

类 huggingface_hub.DuplicatedRepoUrl

< >

( url: Anyendpoint: str | None = None )

参数

  • files_copy_pending (bool) — 如果新仓库的 LFS/Xet 文件仍在后台复制中,则为 True。在复制完成之前,下载这些文件可能会失败。

duplicate_repo() 返回的 RepoUrl。

GitRefInfo

类 huggingface_hub.GitRefInfo

< >

( name: strref: strtarget_commit: str )

参数

  • name (str) — 引用的名称(例如标签名或分支名)。
  • ref (str) — Hub 上的完整 git ref(例如 "refs/heads/main" 或 "refs/tags/v1.0")。
  • target_commit (str) — 该 ref 的目标提交 OID(例如 "e7da7f221d5bf496a48136c0cd264e630fe9fcc8")

包含有关 Hub 上某个仓库的 git 引用的信息。

GitCommitInfo

类 huggingface_hub.GitCommitInfo

< >

( commit_id: strauthors: list[str]created_at: datetimetitle: strmessage: strformatted_title: str | Noneformatted_message: str | None )

参数

  • commit_id (str) — 提交的 OID(例如 "e7da7f221d5bf496a48136c0cd264e630fe9fcc8")
  • authors (list[str]) — 提交者的列表。
  • created_at (datetime) — 创建该提交时的日期和时间。
  • title (str) — 提交的标题。这是由作者输入的任意文本值。
  • message (str) — 提交的描述。这是由作者输入的任意文本值。
  • formatted_title (str) — 以 HTML 格式呈现的提交标题。仅在设置 formatted=True 时返回。
  • formatted_message (str) — 以 HTML 格式呈现的提交描述。仅在设置 formatted=True 时返回。

包含 Hub 上某个仓库的 git 提交信息。有关更多详细信息,请查看 list_repo_commits()。

GitRefs

类 huggingface_hub.GitRefs

< >

( branches: list[GitRefInfo]converts: list[GitRefInfo]tags: list[GitRefInfo]pull_requests: list[GitRefInfo] | None = None )

参数

  • branches (list[GitRefInfo]) — 一个包含 GitRefInfo 的列表,其中包含有关仓库分支的信息。
  • converts (list[GitRefInfo]) — 一个包含 GitRefInfo 的列表,其中包含有关仓库中“convert” refs 的信息。 Converts 是用于(在内部)向 Dataset 仓库推送预处理数据的 refs。
  • tags (list[GitRefInfo]) — 一个包含 GitRefInfo 的列表,其中包含有关仓库标签的信息。
  • pull_requests (list[GitRefInfo],可选) — 一个包含 GitRefInfo 的列表,其中包含有关该仓库上拉取请求的信息。 仅在设置 include_prs=True 时返回。

包含 Hub 上某个仓库的所有 git 引用信息。

对象由 list_repo_refs() 返回。

InferenceProviderMapping

类 huggingface_hub.hf_api.InferenceProviderMapping

< >

( **kwargs )

KernelInfo

类 huggingface_hub.KernelInfo

< >

( **kwargs )

参数

  • id (str) — 内核仓库的 ID。
  • author (str, 可选) — 内核仓库的作者。
  • downloads(int,可选)— 过去 30 天内该内核仓库的下载次数。
  • gated (Literal["auto", "manual", False], 可选) — 该仓库是否受访问限制。如果是,则指定审批方式为手动或自动。
  • last_modified (datetime, 可选) — 仓库最后一次提交的时间。
  • likes(int,可选)— 内核仓库的点赞数。
  • private (bool,可选) — 仓库是否为私有。
  • sha (str,可选) — 此特定修订版本的仓库 SHA。

包含 Hub 上内核仓库的信息。此对象由 kernel_info() 返回。

LFSFileInfo

类 huggingface_hub.hf_api.LFSFileInfo

< >

( **kwargs )

参数

  • file_oid (str) — 文件的 SHA-256 对象 ID。这是永久删除文件时需要传入的标识符。
  • filename (str) — LFS 对象的可能文件名。有关更多信息,请参阅上面的说明。
  • oid (str) — LFS 对象的 OID。
  • pushed_at (datetime) — LFS 对象推送到仓库的日期。
  • ref (str, 可选) — LFS 对象被推送到的引用(如果有的话)。
  • size (int) — LFS 对象的大小。

包含有关以 LFS 形式存储在 Hub 上某个仓库中的文件的信息。

用于在列出并永久删除仓库中的 LFS 文件以释放空间的上下文中。 有关更多详细信息,请参阅 list_lfs_files() 和 permanently_delete_lfs_files()。

Git LFS 文件使用 SHA-256 对象 ID 而非文件路径进行跟踪,以优化性能 由于单个对象可能在不同提交中被多个路径引用, 因此搜索和解析这些关联关系并不实际。请查阅我们的文档,了解如何确定每个 SHA 关联的文件名。

示例:

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

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

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

ModelInfo

类 huggingface_hub.ModelInfo

< >

( **kwargs )

参数

  • id (str) — 模型的 ID。
  • author (str, 可选) — 模型的作者。
  • base_models (list[str], 可选) — 该模型所基于的基础模型列表。
  • card_data (ModelCardData,可选) — 以 huggingface_hub.repocard_data.ModelCardData 对象形式提供的模型卡片元数据。
  • children_model_count (int, 可选) — 从此模型派生的子模型数量。
  • config (dict,可选) — 模型配置。
  • created_at (datetime, 可选) — 该仓库在 Hub 上的创建日期。请注意,最低值为 2022-03-02T23:29:04.000Z,对应我们开始存储创建日期的日期。
  • disabled (bool,可选) — 仓库是否已禁用。
  • downloads (int) — 过去 30 天内该模型的下载次数。
  • downloads_all_time (int) — 自模型创建以来累计的下载次数。
  • eval_results (list[EvalResultEntry], 可选) — 模型的评估结果。
  • gated (Literal["auto", "manual", False], 可选) — 该仓库是否受访问限制。 如果是,则指定审批方式为手动或自动。
  • gguf (dict, 可选) — 模型的 GGUF 信息。
  • inference (Literal["warm"], 可选) — 模型在 Inference Providers 上的状态。如果模型至少由一个提供商提供服务,则状态为 Warm。
  • inference_provider_mapping (list[InferenceProviderMapping],可选) — 一个 InferenceProviderMapping 列表,其顺序与用户的 provider 顺序一致。
  • last_modified (datetime, 可选) — 仓库最后一次提交的时间。
  • library_name (str, 可选) — 与该模型关联的库。
  • likes (int) — 该模型的点赞数。
  • mask_token (str, 可选) — 模型使用的掩码标记。
  • model_index (dict, 可选) — 用于评估的模型索引。
  • pipeline_tag (str, 可选) — 与模型关联的 Pipeline 标签。
  • private (bool) — 仓库是否为私有。
  • resource_group (dict, 可选) — 模型的资源组信息。
  • safetensors (SafeTensorsInfo,可选) — 模型的 safetensors 信息。
  • security_repo_status (dict, 可选) — 模型的安全扫描状态。
  • sha (str,可选) — 此特定修订版本的仓库 SHA。
  • siblings (list[RepoSibling]) — 构成该模型的 huggingface_hub.hf_api.RepoSibling 对象列表。
  • spaces (list[str],可选) — 使用该模型的 Spaces 列表。
  • tags (list[str]) — 模型的标签列表。与 card_data.tags 相比,它包含由 Hub 计算的额外标签(例如支持的库、模型的 arXiv)。
  • transformers_info (TransformersInfo,可选) — 与该模型关联的 Transformers 特定信息(自动类、处理器等)。
  • trending_score (int,可选) — 模型的热度分数。
  • used_storage (int,可选) — 模型在 Hub 上占用的字节数。
  • widget_data (Any, 可选) — 与模型关联的 Widget 数据。

包含 Hub 上模型的相关信息。此对象由 model_info() 和 list_models() 返回。

此类的大多数属性都是可选的。这是因为 Hub 返回的数据取决于所执行的查询。 通常,查询越具体,返回的信息就越多。相反,在使用 list_models() 列出模型时,只会返回部分属性。

RepoSibling

类 huggingface_hub.hf_api.RepoSibling

< >

( rfilename: strsize: int | None = Noneblob_id: str | None = Nonelfs: BlobLfsInfo | None = None )

参数

  • rfilename (str) — 相对于仓库根目录的文件名。
  • size (int, 可选) — 文件的大小,以字节为单位。当 repo_info() 的 files_metadata 参数设置为 True 时,会定义此属性。否则为 None。
  • blob_id (str, 可选) — 文件的 git OID。当 repo_info() 的 files_metadata 参数设置为 True 时,会定义此属性。否则为 None。
  • lfs (BlobLfsInfo,可选) — 文件的 LFS 元数据。当 repo_info() 的 files_metadata 参数设置为 True 且文件通过 Git LFS 存储时,会定义此属性。否则为 None。

包含 Hub 上仓库内某个仓库文件的基本信息。

此类的所有属性均为可选,rfilename 除外。这是因为在 Hub 上列出仓库时(使用 list_models()、list_datasets() 或 list_spaces()),仅返回文件名。如果您需要文件大小、blob id 或 lfs 详细信息等更多数据,必须针对单个仓库逐一请求(使用 model_info()、dataset_info() 或 space_info()),因为获取这些信息会对后端服务器施加更多约束。

RepoFile

类 huggingface_hub.RepoFile

< >

( **kwargs )

参数

  • path (str) — 相对于仓库根目录的文件路径。
  • size (int) — 文件大小,以字节为单位。
  • blob_id (str) — 该文件的 git OID。
  • lfs (BlobLfsInfo,可选) — 该文件的 LFS 元数据。
  • xet_hash (str, 可选) — 文件的 Xet 哈希值。
  • last_commit (LastCommitInfo,可选) — 该文件的最后一次提交元数据。仅在调用 list_repo_tree() 和 get_paths_info() 时传入 expand=True 才会定义。
  • security (BlobSecurityInfo,可选) — 文件的安全扫描元数据。仅在调用 list_repo_tree() 和 get_paths_info() 时传入 expand=True 才会定义。

包含有关 Hub 上文件的信息。

RepoUrl

类 huggingface_hub.RepoUrl

< >

( url: Anyendpoint: str | None = None )

参数

  • url (Any) — 仓库 URL 的字符串值。
  • endpoint (str,可选) — Hub 的端点。默认为 https://huggingface.co。

引发

HfUriError

  • HfUriError — 如果无法解析 URL(例如,规范化的单段仓库,或未知的 repo_type)。

str 的子类,用于描述 Hub 上的仓库 URL。

RepoUrl 由 HfApi.create_repo 返回。为了向后兼容,它继承自 str。在初始化时,URL 会被解析以填充属性:

  • endpoint(str)
  • 命名空间(str)
  • repo_name (str)
  • repo_id (str)
  • repo_type(Literal["model", "dataset", "space"])
  • url (str)

示例:

>>> RepoUrl('https://huggingface.co/openai-community/gpt2')
RepoUrl('https://huggingface.co/openai-community/gpt2', endpoint='https://huggingface.co', repo_type='model', repo_id='openai-community/gpt2')

>>> RepoUrl('/static-proxy?url=https%3A%2F%2Fhub-ci.huggingface.co%2Fdatasets%2Fdummy_user%2Fdummy_dataset%26%23x27%3B%3C%2Fspan%3E%2C endpoint='/static-proxy?url=https%3A%2F%2Fhub-ci.huggingface.co%26%23x27%3B%3C%2Fspan%3E)
RepoUrl('/static-proxy?url=https%3A%2F%2Fhub-ci.huggingface.co%2Fdatasets%2Fdummy_user%2Fdummy_dataset%26%23x27%3B%3C%2Fspan%3E%2C endpoint='/static-proxy?url=https%3A%2F%2Fhub-ci.huggingface.co%26%23x27%3B%3C%2Fspan%3E%2C repo_type='dataset', repo_id='dummy_user/dummy_dataset')

>>> RepoUrl('hf://datasets/my-user/my-dataset')
RepoUrl('hf://datasets/my-user/my-dataset', endpoint='https://huggingface.co', repo_type='dataset', repo_id='user/dataset')

>>> HfApi.create_repo("dummy_model")
RepoUrl('https://huggingface.co/Wauplin/dummy_model', endpoint='https://huggingface.co', repo_type='model', repo_id='Wauplin/dummy_model')

SafetensorsRepoMetadata

类 huggingface_hub.utils.SafetensorsRepoMetadata

< >

( metadata: dict | Nonesharded: boolweight_map: dictfiles_metadata: dict )

参数

  • metadata (dict, 可选) — 如果存在,则为 ‘model.safetensors.index.json’ 文件中包含的元数据。仅对分片模型进行填充。
  • sharded (bool) — 该仓库是否包含分片模型。
  • weight_map (dict[str, str]) — 所有权重的映射。键为张量名称,值为包含该张量的文件名。
  • files_metadata (dict[str, SafetensorsFileMetadata]) — 所有文件元数据的映射。键为文件名,值为对应文件的元数据,类型为 SafetensorsFileMetadata 对象。
  • parameter_count (dict[str, int]) — 按数据类型划分的参数量映射。键为数据类型,值为该数据类型的参数量。

Safetensors 仓库的元数据。

如果仓库根目录包含 ‘model.safetensors’ 权重文件(非共享模型)或 ‘model.safetensors.index.json’ 索引文件(分片模型),则该仓库被视为 Safetensors 仓库。

此类由 get_safetensors_metadata() 返回。

有关 safetensors 格式的更多详细信息,请参阅 https://huggingface.co/docs/safetensors/index#format。

SafetensorsFileMetadata

类 huggingface_hub.utils.SafetensorsFileMetadata

< >

( metadata: dicttensors: dict )

参数

  • metadata (dict) — 文件中包含的元数据。
  • tensors (dict[str, TensorInfo]) — 所有张量的映射。键为张量名称,值为对应张量的信息,以 TensorInfo 对象表示。
  • parameter_count (dict[str, int]) — 按数据类型划分的参数量映射。键为数据类型,值为该数据类型的参数量。

托管在 Hub 上的 Safetensors 文件的元数据。

此类由 parse_safetensors_file_metadata() 返回。

有关 safetensors 格式的更多详细信息,请参阅 https://huggingface.co/docs/safetensors/index#format。

SpaceInfo

类 huggingface_hub.SpaceInfo

< >

( **kwargs )

参数

  • id (str) — Space 的 ID。
  • author (str, 可选) — 该 Space 的作者。
  • card_data (SpaceCardData,可选) — 作为 huggingface_hub.repocard_data.SpaceCardData 对象的 Space Card 元数据。
  • created_at (datetime, 可选) — 该仓库在 Hub 上的创建日期。请注意,最低值为 2022-03-02T23:29:04.000Z,对应我们开始存储创建日期的日期。
  • datasets (list[str], 可选) — 该 Space 使用的数据集列表。
  • disabled (bool, 可选) — 该 Space 是否已禁用。
  • gated (Literal["auto", "manual", False], 可选) — 该仓库是否受访问限制。 如果是,则指定审批方式为手动或自动。
  • host (str, 可选) — Space 的主机 URL。
  • last_modified (datetime, 可选) — 仓库最后一次提交的时间。
  • likes (int) — 该 Space 的点赞数。
  • models (list[str], 可选) — 该 Space 使用的模型列表。
  • private (bool) — 仓库是否为私有。
  • region (Literal["us", "eu"], 可选) — Space 所在的云区域。
  • resource_group (dict, 可选) — 该 Space 的资源组信息。
  • runtime(SpaceRuntime,可选)— 以 huggingface_hub.hf_api.SpaceRuntime 对象形式表示的 Space 运行时信息。
  • sdk (str,可选) — Space 使用的 SDK。
  • sha (str,可选) — 此特定修订版本的仓库 SHA。
  • siblings (list[RepoSibling]) — 构成该 Space 的 huggingface_hub.hf_api.RepoSibling 对象列表。
  • subdomain (str, 可选) — Space 的子域名。
  • tags (list[str]) — 该 Space 的标签列表。
  • trending_score (int, 可选) — 该 Space 的热门分数。
  • used_storage (int, 可选) — Hub 上 Space 的字节大小。

包含 Hub 上某个 Space 的信息。此对象由 space_info() 和 list_spaces() 返回。

此类的大多数属性都是可选的。这是因为 Hub 返回的数据取决于所执行的查询。 通常,查询越具体,返回的信息就越多。相反,在使用 list_spaces() 列出空间时,仅返回部分属性。

SpaceSearchResult

类 huggingface_hub.SpaceSearchResult

< >

( data: dict )

参数

  • id (str) — Space 的 ID(例如 "username/repo-name")。
  • author (str) — 该 Space 的作者。
  • title (str) — Space 的显示标题。
  • emoji (str 或 None) — Space 的 Emoji 图标。
  • sdk (str 或 None) — Space 使用的 SDK(例如 "gradio"、"docker"、"static")。
  • likes (int) — 点赞数。
  • private (bool) — 该 Space 是否为私有。
  • tags(list[str] 或 None)— 标签列表。
  • runtime(SpaceRuntime 或 None)— 运行时信息(阶段、硬件等)。
  • ai_short_description (str 或 None) — AI 生成的简短描述。
  • ai_category (str 或 None) — AI 生成的类别(例如 "Image Generation")。
  • semantic_relevancy_score (float 或 None) — 相对于搜索查询的语义相关性得分(0-1)。
  • trending_score (int 或 None) — 趋势分数。

Spaces 语义搜索 API 的单条结果。

由 HfApi.search_spaces() 返回。

TensorInfo

类 huggingface_hub.utils.TensorInfo

< >

( dtype: typing.Literal['F64', 'F32', 'F16', 'BF16', 'I64', 'I32', 'I16', 'I8', 'U8', 'U3', 'BOOL']shape: listdata_offsets: tuple )

参数

  • dtype (str) — 张量的数据类型(“F64”、“F32”、“F16”、“BF16”、“I64”、“I32”、“I16”、“I8”、“U8”、“U3”、“BOOL”)。
  • shape (list[int]) — 张量的形状。
  • data_offsets (tuple[int, int]) — 文件中数据的偏移量,以元组 [BEGIN, END] 的形式表示。
  • parameter_count (int) — 张量中参数的数量。

张量的相关信息。

有关 safetensors 格式的更多详细信息,请参阅 https://huggingface.co/docs/safetensors/index#format。

用户

类 huggingface_hub.User

< >

( **kwargs )

参数

  • username (str) — Hub 上用户的名称(唯一)。
  • fullname (str) — 用户的姓名。
  • avatar_url (str) — 用户头像的 URL。
  • details (str, 可选) — 用户的详细信息。
  • is_following (bool, 可选) — 已认证用户是否关注了该用户。
  • is_pro (bool, 可选) — 用户是否为专业用户。
  • num_models (int, 可选) — 用户创建的模型数量。
  • num_datasets (int, 可选) — 用户创建的数据集数量。
  • num_spaces (int, 可选) — 用户创建的空间数量。
  • num_discussions (int, 可选) — 用户发起的讨论数量。
  • num_papers (int, 可选) — 用户撰写的论文数量。
  • num_upvotes (int, 可选) — 用户获得的点赞数。
  • num_likes (int, 可选) — 用户给出的点赞数。
  • num_following (int, 可选) — 该用户正在关注的用户数量。
  • num_followers (int, 可选) — 关注该用户的用户数量。
  • orgs(Organization 列表)— 用户所属的组织列表。

包含有关 Hub 上用户的信息。

UserLikes

类 huggingface_hub.UserLikes

< >

( user: strtotal: intdatasets: list[str]kernels: list[str]models: list[str]spaces: list[str] )

参数

  • user (str) — 我们获取点赞数据的用户名称。
  • total (int) — 点赞总数。
  • datasets (list[str]) — 用户点赞的数据集列表(以 repo_ids 形式表示)。
  • kernels (list[str]) — 用户喜欢的内核列表(以 repo_ids 形式表示)。
  • models (list[str]) — 用户喜欢的模型列表(以 repo_ids 形式表示)。
  • spaces (list[str]) — 用户喜欢的空间列表(以 repo_ids 形式表示)。

包含用户在 Hub 上的点赞信息。

WebhookInfo

类 huggingface_hub.WebhookInfo

< >

( id: strurl: str | Nonejob: JobSpec | Nonewatched: list[WebhookWatchedItem]domains: list[constants.WEBHOOK_DOMAIN_T]secret: str | Nonedisabled: bool )

参数

  • id (str) — Webhook 的 ID。
  • url (str, 可选) — Webhook 的 URL。
  • job (JobSpec,可选) — 要触发的 Job 的规格。
  • watched (list[WebhookWatchedItem]) — Webhook 监视的项目列表,参见 WebhookWatchedItem。
  • domains (list[WEBHOOK_DOMAIN_T]) — Webhook 正在监控的域名列表。可以是 ["repo", "discussion"] 之一。
  • secret (str, 可选) — Webhook 的密钥。
  • disabled (bool) — Webhook 是否已禁用。

包含 webhook 信息的数据结构。

指定了 url 或 job 之一,但并非两者都指定。

WebhookWatchedItem

类 huggingface_hub.WebhookWatchedItem

< >

( type: Literal['bucket', 'dataset', 'model', 'org', 'space', 'user']name: str )

参数

  • type (Literal["bucket", "dataset", "model", "org", "space", "user"]) — 要关注的项目类型。可以是 ["bucket", "dataset", "model", "org", "space", "user"] 之一。
  • name (str) — 要监控的项的名称。可以是用户名、组织名称、模型名称、数据集名称、空间名称或存储桶名称。

包含 Webhook 所监控项信息的数据结构。

CommitOperation

以下是 CommitOperation() 支持的取值:

类 huggingface_hub.CommitOperationAdd

< >

( path_in_repo: strpath_or_fileobj: str | pathlib.Path | bytes | typing.BinaryIO )

参数

  • path_in_repo (str) — 仓库中的相对文件路径,例如:"checkpoints/1fec34a/weights.bin"
  • path_or_fileobj (str, Path, bytes, 或 BinaryIO) — 可以是以下之一:
    • 要上传的本地文件路径(作为str或pathlib.Path)
    • 一个字节缓冲区(bytes),用于保存要上传的文件内容
    • 一个“文件对象”(io.BufferedIOBase 的子类),通常通过 open(path, "rb") 获取。它必须支持 seek() 和 tell() 方法。

引发

ValueError

  • ValueError — 如果 path_or_fileobj 不是 str、Path、bytes 或 io.BufferedIOBase 之一。
  • ValueError — 如果 path_or_fileobj 是 str 或 Path,但不是指向现有文件的路径。
  • ValueError — 如果 path_or_fileobj 是 io.BufferedIOBase,但不支持 seek() 和 tell()。

用于将文件上传到 Hub 上的仓库所需信息的数据结构。

as_file

< >

( with_tqdm: bool = False )

参数

  • with_tqdm (bool,可选,默认为 False) — 如果为 True,迭代文件对象时会显示进度条。仅当类文件对象是文件路径时有效。不支持纯字节和缓冲区。

一个上下文管理器,用于生成一个文件类对象,允许读取 path_or_fileobj 背后的底层数据。

示例:

>>> operation = CommitOperationAdd(
...        path_in_repo="remote/dir/weights.h5",
...        path_or_fileobj="./local/weights.h5",
... )
CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5')

>>> with operation.as_file() as file:
...     content = file.read()

>>> with operation.as_file(with_tqdm=True) as file:
...     while True:
...         data = file.read(1024)
...         if not data:
...              break
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]

>>> with operation.as_file(with_tqdm=True) as file:
...     httpx2.put(..., data=file)
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]

b64content

< >

( )

path_or_fileobj 的 base64 编码内容

返回:bytes

类 huggingface_hub.CommitOperationDelete

< >

( path_in_repo: stris_folder: typing.Union[bool, typing.Literal['auto']] = 'auto' )

参数

  • path_in_repo (str) — 仓库中的相对文件路径,例如:文件为 "checkpoints/1fec34a/weights.bin",文件夹为 "checkpoints/1fec34a/"。
  • is_folder (bool 或 Literal["auto"],可选) — 删除操作是否应用于文件夹。如果设置为 “auto”,则通过检查 path 是否以 ”/” 结尾(文件夹)或不以 ”/” 结尾(文件)来自动推断路径类型(文件或文件夹)。若要显式设置路径类型,可以设置 is_folder=True 或 is_folder=False。

用于从 Hub 上的存储库中删除文件或文件夹的数据结构,其中包含必要的信息。

类 huggingface_hub.CommitOperationCopy

< >

( src_path_in_repo: strpath_in_repo: strsrc_revision: str | None = Nonesrc_repo_id: str | None = Nonesrc_repo_type: str | None = None_src_oid: str | None = None_dest_oid: str | None = None_is_duplicated: bool = False )

参数

  • src_path_in_repo (str) — 要复制的文件在仓库中的相对文件路径,例如 "checkpoints/1fec34a/weights.bin"。
  • path_in_repo (str) — 仓库中用于复制文件的相对文件路径,例如 "checkpoints/1fec34a/weights_copy.bin"。
  • src_revision (str, 可选) — 要复制的文件的 git 修订版本。可以是任何有效的 git 修订版本。 默认为目标提交修订版本。
  • src_repo_id (str, 可选) — 要从中复制的源仓库(例如 "username/source-model")。 默认为目标仓库(仓库内复制)。
  • src_repo_type (str, 可选) — 源仓库的类型("model"、"dataset" 或 "space")。 当设置了 src_repo_id 时必填。

用于在 Hub 上的仓库中复制文件所需信息的数据结构。

LFS 文件和常规文件均受支持。LFS 文件会在服务器端进行复制,而常规文件则会作为提交的一部分被下载并重新上传。

通过设置 src_repo_id 和 src_repo_type 可以支持跨仓库复制。对于跨仓库的 LFS 复制,在创建提交之前,LFS 对象会先被复制到目标仓库。此过程由 create_commit() 自动处理。请注意,跨仓库复制仅支持在同一个 存储区域 内进行;不支持跨区域复制。

注意:您可以组合使用 CommitOperationCopy 和 CommitOperationDelete 来重命名 Hub 上的 LFS 文件。

CommitScheduler

类 huggingface_hub.CommitScheduler

< >

( repo_id: strfolder_path: str | pathlib.Pathevery: int | float = 5path_in_repo: str | None = Nonerepo_type: str | None = Nonerevision: str | None = Noneprivate: bool | None = Nonetoken: str | None = Noneallow_patterns: list[str] | str | None = Noneignore_patterns: list[str] | str | None = Nonesquash_history: bool = Falsehf_api: typing.Optional[ForwardRef('HfApi')] = None )

参数

  • repo_id (str) — 要提交到的仓库的 id。
  • folder_path (str 或 Path) — 要定期上传的本地文件夹的路径。
  • every(int 或 float,可选)— 每次提交之间的分钟数。默认值为 5 分钟。
  • path_in_repo (str, 可选) — 仓库中目录的相对路径,例如:"checkpoints/"。默认为仓库的根目录。
  • repo_type (str, 可选) — 要提交到的仓库类型。默认为 model。
  • revision (str, 可选) — 要提交到的仓库版本。默认为 main。
  • private (bool,可选) — 是否将仓库设为私有。如果为 None(默认值),除非组织的默认设置为私有,否则仓库将是公开的。如果仓库已存在,则忽略此值。
  • token (str, 可选) — 用于提交到仓库的 token。默认使用保存在机器上的 token。
  • allow_patterns (list[str] 或 str,可选) — 如果提供,则仅上传至少匹配其中一个模式的文件。
  • ignore_patterns (list[str] 或 str,可选) — 如果提供,则匹配任一模式的文件不会被上传。
  • squash_history (bool, 可选) — 是否在每次提交后压缩仓库的历史记录。默认为 False。压缩提交有助于避免仓库过大时性能下降。
  • hf_api (HfApi, 可选) — 用于向 Hub 提交内容的 HfApi 客户端。可以设置自定义配置(用户代理、令牌等)。

用于定期(例如每 5 分钟)将本地文件夹上传到 Hub 的调度器。

建议使用调度器的方式是将其作为上下文管理器使用。这可以确保在脚本结束时,调度器被正确停止并触发最后一次提交。也可以通过 stop 方法手动停止调度器。有关如何使用它的更多信息,请参阅 上传指南。

示例:

>>> from pathlib import Path
>>> from huggingface_hub import CommitScheduler

# Scheduler uploads every 10 minutes
>>> csv_path = Path("watched_folder/data.csv")
>>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)

>>> with csv_path.open("a") as f:
...     f.write("first line")

# Some time later (...)
>>> with csv_path.open("a") as f:
...     f.write("second line")

使用上下文管理器的示例:

>>> from pathlib import Path
>>> from huggingface_hub import CommitScheduler

>>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler:
...     csv_path = Path("watched_folder/data.csv")
...     with csv_path.open("a") as f:
...         f.write("first line")
...     (...)
...     with csv_path.open("a") as f:
...         f.write("second line")

# Scheduler is now stopped and last commit have been triggered

push_to_hub

< >

( )

将文件夹推送到 Hub 并返回提交信息。

此方法不打算被直接调用。它由调度器在后台运行,并遵循队列机制以避免并发提交。直接调用此方法可能会导致并发问题。

push_to_hub 的默认行为是将文件夹视为仅追加(append-only)模式。它会列出文件夹中的所有文件,并仅上传已更改的文件。如果未检测到任何更改,该方法将直接返回,不提交任何内容。若要更改此行为,您可以继承 CommitScheduler 并重写该方法。例如,这可用于在提交前将数据压缩到单个文件中。有关更多详细信息和示例,请参阅我们的 集成指南。

停止

< >

( )

停止调度器。

已停止的调度器无法重新启动。主要用于测试目的。

触发器

< >

( )

触发 push_to_hub 并返回一个 future。

此方法会自动每 every 分钟调用一次。您也可以手动调用它,以立即触发提交,而无需等待下一次计划中的提交。

Update on GitHub