Hub Python Library documentation

实用工具

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v2.4.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

实用工具

配置日志

huggingface_hub 包提供了一个 logging 实用工具,用于控制该包自身的日志级别。 您可以按以下方式导入它:

from huggingface_hub import logging

然后,您可以定义详细程度,以更新您将看到的日志数量:

from huggingface_hub import logging

logging.set_verbosity_error()
logging.set_verbosity_warning()
logging.set_verbosity_info()
logging.set_verbosity_debug()

logging.set_verbosity(...)

应这样理解这些级别:

  • error:仅显示可能导致错误或意外行为的关键使用日志。
  • warning:显示非关键但可能导致意外行为的日志。 此外,可能会显示重要的信息性日志。
  • info:显示大多数日志,包括一些关于内部发生情况的详细日志。 如果某些行为不符合预期,我们建议将详细程度级别切换为此级别,以获取更多信息。
  • debug:显示所有日志,包括一些可能用于追踪底层具体发生情况的内部日志。

huggingface_hub.utils.logging.get_verbosity

< >

( )

返回 HuggingFace Hub 根记录器(root logger)的当前日志级别。

HuggingFace Hub 具有以下日志级别:

  • huggingface_hub.logging.CRITICAL, huggingface_hub.logging.FATAL
  • huggingface_hub.logging.ERROR
  • huggingface_hub.logging.WARNING, huggingface_hub.logging.WARN
  • huggingface_hub.logging.INFO
  • huggingface_hub.logging.DEBUG

huggingface_hub.utils.logging.set_verbosity

< >

( verbosity: int )

参数

  • verbosity (int) — 日志级别,例如 huggingface_hub.logging.DEBUG 和 huggingface_hub.logging.INFO。

设置 HuggingFace Hub 根日志记录器的级别。

huggingface_hub.utils.logging.set_verbosity_info

< >

( )

将详细程度设置为 logging.INFO。

huggingface_hub.utils.logging.set_verbosity_debug

< >

( )

将详细程度设置为 logging.DEBUG。

huggingface_hub.utils.logging.set_verbosity_warning

< >

( )

将详细程度设置为 logging.WARNING。

huggingface_hub.utils.logging.set_verbosity_error

< >

( )

将详细程度设置为 logging.ERROR。

huggingface_hub.utils.logging.disable_propagation

< >

( )

禁用库日志输出的传播。请注意,日志传播默认处于禁用状态。

huggingface_hub.utils.logging.enable_propagation

< >

( )

启用库日志输出的传播。如果已配置根日志记录器,请禁用 HuggingFace Hub 的默认处理器,以防止重复记录日志。

特定于仓库的辅助方法

以下公开的方法在修改 huggingface_hub 库本身中的模块时相关。 如果您使用 huggingface_hub 且不对其进行修改,则不应需要使用这些方法。

huggingface_hub.utils.logging.get_logger

< >

( name: str | None = None )

参数

  • name (str, 可选) — 要获取的日志记录器名称,通常为文件名

返回一个具有指定名称的日志记录器。此函数不应由库用户直接访问。

示例:

>>> from huggingface_hub import logging

>>> logger = logging.get_logger(__name__)
>>> logging.set_verbosity_info()

配置进度条

进度条是一种有用的工具,可在长时间运行的任务执行期间(例如下载或上传文件时)向用户显示信息。huggingface_hub 提供了一个 tqdm 封装器,以便在整个库中以一致的方式显示进度条。

默认情况下,进度条是启用的。您可以通过设置 HF_HUB_DISABLE_PROGRESS_BARS 环境变量来全局禁用它们。您也可以使用 enable_progress_bars() 和 disable_progress_bars 来启用/禁用它们。如果设置了环境变量,则其优先级高于辅助函数。

>>> from huggingface_hub import snapshot_download
>>> from huggingface_hub.utils import are_progress_bars_disabled, disable_progress_bars, enable_progress_bars

>>> # Disable progress bars globally
>>> disable_progress_bars()

>>> # Progress bar will not be shown !
>>> snapshot_download("gpt2")

>>> are_progress_bars_disabled()
True

>>> # Re-enable progress bars globally
>>> enable_progress_bars()

按组控制进度条

您还可以为特定组启用或禁用进度条。这允许您在应用程序或库的不同部分中更精细地管理进度条的可见性。当某个组的进度条被禁用时,其下的所有子组也会受到影响,除非被显式覆盖。

# Disable progress bars for a specific group
>>> disable_progress_bars("peft.foo")
>>> assert not are_progress_bars_disabled("peft")
>>> assert not are_progress_bars_disabled("peft.something")
>>> assert are_progress_bars_disabled("peft.foo")
>>> assert are_progress_bars_disabled("peft.foo.bar")

# Re-enable progress bars for a subgroup
>>> enable_progress_bars("peft.foo.bar")
>>> assert are_progress_bars_disabled("peft.foo")
>>> assert not are_progress_bars_disabled("peft.foo.bar")

# Use groups with tqdm
# No progress bar for `name="peft.foo"`
>>> for _ in tqdm(range(5), name="peft.foo"):
...     pass

# Progress bar will be shown for `name="peft.foo.bar"`
>>> for _ in tqdm(range(5), name="peft.foo.bar"):
...     pass
100%|███████████████████████████████████████| 5/5 [00:00<00:00, 117817.53it/s]

are_progress_bars_disabled

huggingface_hub.utils.are_progress_bars_disabled

< >

( name: str | None = None ) → bool

参数

  • name (str, 可选) — 要检查的组名;如果为 None,则检查全局设置。

返回值

bool

如果进度条被禁用,则为 True,否则为 False。

检查进度条是否在全局或特定组中被禁用。

此函数返回给定组或全局是否禁用了进度条。 它会先检查 HF_HUB_DISABLE_PROGRESS_BARS 环境变量,然后检查编程设置。

disable_progress_bars

类 huggingface_hub.utils.disable_progress_bars

< >

( name: str | None = None )

参数

  • name (str, 可选) — 要禁用进度条的组名称。如果为 None,则全局禁用进度条。

引发

Warning

  • Warning — 如果环境变量禁止更改。

全局禁用进度条,或针对指定组禁用进度条。

此函数根据组名更新进度条的状态。 如果未提供组名,则禁用所有进度条。该操作 遵循 HF_HUB_DISABLE_PROGRESS_BARS 环境变量的设置。

既可用作常规调用,也可用作上下文管理器: disable_progress_bars() # 禁用,直到调用 enable_progress_bars() with disable_progress_bars(): # 在代码块内禁用,退出时重新启用 …

enable_progress_bars

huggingface_hub.utils.enable_progress_bars

< >

( name: str | None = None )

参数

  • name (str, 可选) — 要为其启用进度条的组名称。如果为 None,则全局启用进度条。

引发

Warning

  • Warning — 如果环境变量禁止更改。

在全局或指定组中启用进度条。

此函数为指定的组启用进度条;如果未指定组,则全局启用。该操作受 HF_HUB_DISABLE_PROGRESS_BARS 环境变量设置的影响。

配置 HTTP 后端

在 huggingface_hub v0.x 中,HTTP 请求由 requests 处理,配置通过 configure_http_backend 完成。由于我们现在使用 httpx2,配置方式有所不同:您必须提供一个工厂函数,该函数不接受任何参数并返回一个 httpx2.Client。您可以在此处查看 默认实现,以了解默认使用的参数。

在某些配置中,您可能需要控制 HTTP 请求的发送方式,例如在代理后面工作时。huggingface_hub 库允许您使用 set_client_factory() 进行全局配置。配置完成后,所有发往 Hub 的请求都将使用您的自定义设置。由于 huggingface_hub 底层依赖于 httpx2.Client,您可以查阅 httpx2 文档 了解可用参数的详细信息。

如果您正在构建第三方库并需要直接向 Hub 发起请求,请使用 get_session() 获取配置正确的 httpx2 客户端。将任何直接的 httpx2.get(...) 调用替换为 get_session().get(...),以确保行为正确。

huggingface_hub.set_client_factory

< >

( client_factory: Callable )

设置 huggingface_hub 使用的 HTTP 客户端工厂。

客户端工厂是一个返回 httpx2.Client 对象的方法。在首次调用 get_session() 时,客户端工厂将被用于创建一个新的 httpx2.Client 对象,该对象将在 huggingface_hub 发出的所有调用之间共享。

如果您在需要自定义配置(例如自定义代理或证书)的特定环境中运行脚本,这可能非常有用。

使用 get_session() 获取配置正确的 httpx2.Client。

huggingface_hub.get_session

< >

( )

使用用户提供的传输工厂,获取一个 httpx2.Client 对象。

此客户端由 huggingface_hub 发出的所有调用共享。因此,您不应手动关闭它。

使用 set_client_factory() 来自定义 httpx2.Client。

在极少数情况下,您可能需要手动关闭当前会话(例如,在出现短暂的 SSLError 之后)。您可以使用 close_session() 来执行此操作。在下一次调用 get_session() 时,将自动创建一个新的会话。

进程退出时,会话始终会自动关闭。

huggingface_hub.close_session

< >

( )

关闭 huggingface_hub 使用的全局 httpx2.Client。

如果 Client 已关闭,则在下次调用 get_session() 时会自动重新创建。

在例如 SSL 证书已更新的情况下可能有用。

对于异步代码,请使用 set_async_client_factory() 来配置一个 httpx2.AsyncClient,并使用 get_async_session() 来获取一个。

huggingface_hub.set_async_client_factory

< >

( async_client_factory: Callable )

设置 huggingface_hub 所使用的 HTTP 异步客户端工厂。

异步客户端工厂是一个返回 httpx2.AsyncClient 对象的方法。 如果您在需要自定义配置(例如自定义代理或证书)的特定环境中运行脚本,这将非常有用。 使用 get_async_session() 来获取配置正确的 httpx2.AsyncClient。

与在 huggingface_hub 发起的所有调用之间共享的 httpx2.Client 不同,httpx2.AsyncClient 并非共享的。 建议使用异步上下文管理器,以确保在退出上下文时正确关闭客户端。

huggingface_hub.get_async_session

< >

( )

返回一个 httpx2.AsyncClient 对象,使用用户提供的传输工厂。

使用 set_async_client_factory() 来自定义 httpx2.AsyncClient。

与在 huggingface_hub 发起的所有调用之间共享的 httpx2.Client 不同,httpx2.AsyncClient 并非共享的。 建议使用异步上下文管理器,以确保在退出上下文时正确关闭客户端。

与同步客户端不同,异步客户端的生命周期不会自动管理。请使用异步上下文管理器来正确处理它。

httpx 模块

huggingface_hub 将其底层使用的 HTTP 库重新导出为 huggingface_hub.utils.httpx:

from huggingface_hub.utils import httpx

try:
    ...
except httpx.HTTPError:
    ...

这主要适用于基于 huggingface_hub 构建的第三方库。huggingface_hub v1.x 基于 httpx 构建,而 v2.x 则基于 httpx2(其继任者,作为独立包分发)构建。从 huggingface_hub.utils 导入该模块,而不是直接导入 httpx,意味着你始终获取的是 huggingface_hub 实际使用的版本,从而确保你的库与两个主要版本保持兼容。有关迁移计划的更多详细信息,请参阅 此问题。

仅在需要 httpx 类型或异常(例如用于捕获错误)时使用此方法。要向 Hub 发起请求,请按照上述说明使用 get_session()。

处理 HTTP 错误

huggingface_hub 定义了自身的 HTTP 错误,以补充服务器返回的额外信息,从而细化由 httpx2 抛出的 HTTPError。

针对状态抛出异常

hf_raise_for_status() 旨在作为从 Hub 发出的任何请求中“根据状态抛出异常”的核心方法。它封装了基础的 httpx2.Response.raise_for_status 以提供更多信息。任何抛出的 HTTPError 都会被转换为 HfHubHTTPError。

from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError

response = get_session().post(...)
try:
    hf_raise_for_status(response)
except HfHubHTTPError as e:
    print(str(e)) # formatted message
    e.request_id, e.server_message # details returned by server

    # Complete the error message with additional information once it's raised
    e.append_to_message("\n`create_commit` expects the repository to exist.")
    raise

huggingface_hub.hf_raise_for_status

< >

( response: Responseendpoint_name: str | None = None )

参数

  • response (Response) — 来自服务器的响应。
  • endpoint_name (str, 可选) — 被调用的端点名称。如果提供,错误信息将更完整。

response.raise_for_status() 的内部版本,用于细化潜在的 HTTPError。 抛出的异常将是 HfHubHTTPError 的实例。

This helper is meant to be the unique method to raise_for_status when making a call to the Hugging Face Hub.

请求失败时引发:

  • RepositoryNotFoundError 如果找不到要下载的仓库。这可能是因为它不存在,因为 repo_type 未正确设置,或者因为该仓库是 private 且您没有访问权限。
  • GatedRepoError 如果仓库存在但受访问限制,且用户不在授权列表中。
  • RevisionNotFoundError 如果仓库存在但找不到该修订版本。
  • EntryNotFoundError 如果仓库存在但无法找到该条目(例如请求的文件)。
  • BadRequestError 如果请求因 HTTP 400 BadRequest 错误而失败。
  • HfHubHTTPError 如果请求因上述未列出的原因而失败。

检查离线模式

您可以使用 is_offline_mode 以编程方式检查是否已启用离线模式。通过设置环境变量 HF_HUB_OFFLINE=1 即可启用离线模式。

huggingface_hub.is_offline_mode

< >

( )

返回我们是否处于 Hub 的离线模式。

启用离线模式后,使用 get_session 发出的所有 HTTP 请求都会引发 OfflineModeIsEnabled 异常。

示例:

from huggingface_hub import is_offline_mode

def list_files(repo_id: str):
    if is_offline_mode():
        ... # list files from local cache (degraded experience but still functional)
    else:
        ... # list files from Hub (complete experience)

HTTP 错误

以下是 huggingface_hub 中抛出的 HTTP 错误列表。

HfHubHTTPError

HfHubHTTPError 是所有 HF Hub HTTP 错误的父类。它负责解析服务器响应并格式化错误消息,以尽可能向用户提供更多信息。

类 huggingface_hub.errors.HfHubHTTPError

< >

( message: strresponse: Responseserver_message: str | None = None )

在 HF Hub 中引发任何自定义 HTTP 错误时,需要继承的 HTTPError。

任何 HTTPError 至少会被转换为 HfHubHTTPError。如果服务器返回了某些信息,这些信息将被添加到错误消息中。

新增详情:

  • 请求 ID 按以下优先级顺序从请求头中获取:“X-Request-Id”、“X-Amzn-Trace-Id”、“X-Amz-Cf-Id”。
  • 来自请求头“X-Error-Message”的服务器错误消息。
  • 如果在响应体中找到了服务器错误消息,则显示该消息。

示例:

    import httpx2
    from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError

    response = get_session().post(...)
    try:
        hf_raise_for_status(response)
    except HfHubHTTPError as e:
        print(str(e)) # formatted message
        e.request_id, e.server_message # details returned by server

        # Complete the error message with additional information once it's raised
        e.append_to_message("
ate_commit` expects the repository to exist.")
        raise

append_to_message

< >

( additional_message: str )

将附加信息追加到 HfHubHTTPError 的初始消息中。

RepositoryNotFoundError

类 huggingface_hub.errors.RepositoryNotFoundError

< >

( message: strresponse: Responseserver_message: str | None = None )

参数

  • repo_id (str 或 None) — 如果可以从请求 URL 中确定,则为未找到的仓库 ID。
  • repo_type (str 或 None) — 如果可以从请求 URL 中确定,则为仓库类型(“model”、“dataset” 或 “space”)。

在尝试使用无效的仓库名称访问 hf.co URL,或使用用户无权访问的私有仓库名称时引发。

示例:

>>> from huggingface_hub import model_info
>>> model_info("<non_existent_repository>")
(...)
huggingface_hub.errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP)

Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E.
Please make sure you specified the correct `repo_id` and `repo_type`.
If the repo is private, make sure you are authenticated and your token has the required permissions.
Invalid username or password.

GatedRepoError

类 huggingface_hub.errors.GatedRepoError

< >

( message: strresponse: Responseserver_message: str | None = None )

当尝试访问用户不在授权列表中的受限仓库时引发。

注意:派生自 RepositoryNotFoundError,以确保向后兼容性。

示例:

>>> from huggingface_hub import model_info
>>> model_info("<gated_repository>")
(...)
huggingface_hub.errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa)

Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model.
Access to model ardent-figment/gated-model is restricted and you are not in the authorized list.
Visit https://huggingface.co/ardent-figment/gated-model to ask for access.

RevisionNotFoundError

类 huggingface_hub.errors.RevisionNotFoundError

< >

( message: strresponse: Responseserver_message: str | None = None )

参数

  • repo_id (str 或 None) — 如果可以从请求 URL 中确定,则为仓库 ID。
  • repo_type (str 或 None) — 如果可以从请求 URL 中确定,则为仓库类型(“model”、“dataset” 或 “space”)。

在尝试访问具有有效仓库但无效修订版本的 hf.co URL 时引发。

示例:

>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download('bert-base-cased', 'config.json', revision='<non-existent-revision>')
(...)
huggingface_hub.errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX)

Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json.

RevisionResolutionError

类 huggingface_hub.errors.RevisionResolutionError

< >

( )

当无法将修订版本解析为提交哈希时,由 HfApi.resolve_revision() 引发:无法连接到 Hub(离线模式、连接错误、超时、Hub 停机……),且在本地缓存中未找到匹配的条目。

BadRequestError

类 huggingface_hub.errors.BadRequestError

< >

( message: strresponse: Responseserver_message: str | None = None )

当服务器返回 HTTP 400 错误时,由 hf_raise_for_status 抛出。

示例:

>>> resp = httpx2.post("hf.co/api/check", ...)
>>> hf_raise_for_status(resp, endpoint_name="check")
huggingface_hub.errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX)

EntryNotFoundError

类 huggingface_hub.errors.EntryNotFoundError

< >

( )

当在本地或远程均未找到条目时引发。

示例:

>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download('bert-base-cased', '<non-existent-file>')
(...)
huggingface_hub.errors.RemoteEntryNotFoundError (...)
>>> hf_hub_download('bert-base-cased', '<non-existent-file>', local_files_only=True)
(...)
huggingface_hub.utils.errors.LocalEntryNotFoundError (...)

RemoteEntryNotFoundError

类 huggingface_hub.errors.RemoteEntryNotFoundError

< >

( message: strresponse: Responseserver_message: str | None = None )

参数

  • repo_id (str 或 None) — 如果可以从请求 URL 中确定,则为仓库 ID。
  • repo_type (str 或 None) — 如果可以从请求 URL 中确定,则为仓库类型(“model”、“dataset” 或 “space”)。

在尝试访问 hf.co URL 时,如果仓库和修订版本有效但文件名无效,则会引发此错误。

示例:

>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download('bert-base-cased', '<non-existent-file>')
(...)
huggingface_hub.errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x)

Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E.

LocalEntryNotFoundError

类 huggingface_hub.errors.LocalEntryNotFoundError

< >

( message: str )

当网络被禁用或不可用(连接问题)时,尝试访问磁盘上不存在的文件或快照会引发此错误。该条目可能存在于 Hub 上。

示例:

>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download('bert-base-cased', '<non-cached-file>',  local_files_only=True)
(...)
huggingface_hub.errors.LocalEntryNotFoundError: Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable hf.co look-ups and downloads online, set 'local_files_only' to False.

IncompleteSnapshotError

类 huggingface_hub.errors.IncompleteSnapshotError

< >

( message: strsnapshot_path: str )

当 Hub 无法访问(离线、连接问题或 local_files_only=True)且已知缓存快照不完整时,由 snapshot_download() 引发:仓库缓存的树列表中列出的某些文件在本地快照中缺失。

这是 LocalEntryNotFoundError 的子类,用于向后兼容。

snapshot_path 属性保存了不完整本地快照的路径,因此下游库可以定位到最新的缓存文件,即使已知这些文件并不完整。

CachedRepoTreeNotFoundError

类 huggingface_hub.errors.CachedRepoTreeNotFoundError

< >

( )

当请求的修订版本没有缓存的树列表时,由 get_cached_repo_tree() 引发。

树状列表是作为 snapshot_download() 的副作用而填充的。

OfflineModeIsEnabled

类 huggingface_hub.errors.OfflineModeIsEnabled

< >

( )

当发出请求但环境变量设置为 HF_HUB_OFFLINE=1 时引发。

遥测

huggingface_hub 包含一个用于发送遥测数据的辅助工具。这些信息有助于我们调试问题并确定新功能的优先级。 用户随时可以通过设置环境变量 HF_HUB_DISABLE_TELEMETRY=1 来禁用遥测数据收集。 在离线模式下(即设置 HF_HUB_OFFLINE=1 时),遥测功能同样会被禁用。

如果您是第三方库的维护者,发送遥测数据只需调用 send_telemetry 即可。 数据会在单独的线程中发送,以尽可能降低对用户的性能影响。

huggingface_hub.utils.send_telemetry

< >

( topic: strlibrary_name: str | None = Nonelibrary_version: str | None = Noneuser_agent: dict | str | None = None )

参数

  • topic (str) — 要监控的主题名称。该主题将直接用于构建 URL。如果要监控子主题,请使用“/”进行分隔。示例:“gradio”、“transformers/examples”等。
  • library_name (str, 可选) — 发起 HTTP 请求的库的名称。将被添加到 user-agent 请求头中。
  • library_version (str,可选) — 发起 HTTP 请求的库的版本。该值将被添加到 user-agent 请求头中。
  • user_agent (str, dict, 可选) — 以字典或单个字符串形式提供的用户代理信息。它将与已安装软件包的相关信息一起补全。

发送遥测数据,有助于跟踪不同 HF 库的使用情况。

这些使用数据有助于我们调试问题并确定新功能的优先级。不过,我们理解并非所有人都愿意分享额外信息,我们尊重您的隐私。您可以通过将 HF_HUB_DISABLE_TELEMETRY=1 设置为环境变量来禁用遥测数据收集。在离线模式下(即设置 HF_HUB_OFFLINE=1 时),遥测功能同样会被禁用。

遥测数据的收集在单独的线程中运行,以最大程度地降低对用户的干扰。

示例:

>>> from huggingface_hub.utils import send_telemetry

# Send telemetry without library information
>>> send_telemetry("ping")

# Send telemetry to subtopic with library information
>>> send_telemetry("gradio/local_link", library_name="gradio", library_version="3.22.1")

# Send telemetry with additional data
>>> send_telemetry(
...     topic="examples",
...     library_name="transformers",
...     library_version="4.26.0",
...     user_agent={"pipeline": "text_classification", "framework": "flax"},
... )

验证器

huggingface_hub 包含自定义验证器,用于自动验证方法参数。 其验证机制借鉴了 Pydantic 中用于验证类型提示的工作,但功能更为有限。

通用装饰器

validate_hf_hub_args() 是一个通用装饰器,用于封装那些参数遵循 huggingface_hub 命名规范的方法。默认情况下,所有已实现验证器的参数都会被验证。

如果输入无效,则会抛出 HFValidationError。只有第一个无效值会触发错误并停止验证过程。

用法:

>>> from huggingface_hub.utils import validate_hf_hub_args

>>> @validate_hf_hub_args
... def my_cool_method(repo_id: str):
...     print(repo_id)

>>> my_cool_method(repo_id="valid_repo_id")
valid_repo_id

>>> my_cool_method("other..repo..id")
huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.

>>> my_cool_method(repo_id="other..repo..id")
huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.

validate_hf_hub_args

huggingface_hub.utils.validate_hf_hub_args

< >

( fn: ~CallableT )

验证作为huggingface_hub任何公共方法参数接收的值。

该装饰器的目标是统一各处复用的参数验证。默认情况下,会测试所有已定义的验证器。

验证器:

  • validate_repo_id():repo_id 必须是 "repo_name" 或 "namespace/repo_name"。Namespace 是用户名或组织。
  • ~utils.smoothly_deprecate_legacy_arguments:下载文件时忽略 proxies(应全局设置)。

示例:

>>> from huggingface_hub.utils import validate_hf_hub_args

>>> @validate_hf_hub_args
... def my_cool_method(repo_id: str):
...     print(repo_id)

>>> my_cool_method(repo_id="valid_repo_id")
valid_repo_id

>>> my_cool_method("other..repo..id")
huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.

>>> my_cool_method(repo_id="other..repo..id")
huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.

HFValidationError

类 huggingface_hub.errors.HFValidationError

< >

( )

由 huggingface_hub 验证器抛出的通用异常。

继承自 ValueError。

参数验证器

验证器也可以单独使用。以下是所有可验证参数的列表。

repo_id

huggingface_hub.utils.validate_repo_id

< >

( repo_id: str | None )

验证 repo_id 是否有效。

这并非旨在取代 Hub 上进行的正式验证,而是为了尽可能避免本地不一致(例如:禁止在 repo_id 中传入 repo_type)。

规则:

  • 1 到 96 个字符之间。
  • “repo_name”或“namespace/repo_name”
  • [a-zA-Z0-9] 或 ”-”、”_”、”.”
  • “—”和“..”是被禁止的

有效:"foo"、"foo/bar"、"123"、"Foo-BAR_foo.bar123"

无效示例:"datasets/foo/bar"、".repo_id"、"foo--bar"、"foo.git"

示例:

>>> from huggingface_hub.utils import validate_repo_id
>>> validate_repo_id(repo_id="valid_repo_id")
>>> validate_repo_id(repo_id="other..repo..id")
huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.

在 https://github.com/huggingface/huggingface_hub/issues/1008 中讨论过。 在 moon-landing(内部仓库)中:

smoothly_deprecate_legacy_arguments

严格来说并不是验证器,但同样可以运行。

huggingface_hub.utils._validators.smoothly_deprecate_legacy_arguments

< >

( fn_name: strkwargs: dict )

在 huggingface_hub 代码库中平滑地弃用旧版参数。

此函数会忽略 kwargs 中的一些已弃用参数,并提醒用户这些参数已被忽略。 其目的是在避免破坏现有代码的同时,引导用户采用新的使用方式。

已弃用参数列表:

  • proxies: 要设置代理,用户必须使用 HTTP_PROXY 环境变量,或者使用 set_client_factory() 函数手动配置 httpx2.Client。

    在 huggingface_hub 0.x 中,proxies 是一个直接传递给 requests.request 的字典。 从 huggingface_hub 1.x 开始,不再支持按请求设置 proxies。 具体来说,无法按请求配置代理。解决方案是使用 set_client_factory() 函数或 HTTP_PROXY 环境变量进行全局配置。

    有关更多详细信息,请参阅:

  • resume_download:已弃用,无替代方案。huggingface_hub 在可能的情况下始终会恢复下载。

  • force_filename:已弃用,无替代方案。文件名始终与 Hub 上的相同。

  • local_dir_use_symlinks:已弃用,无替代方案。下载到本地目录时不再使用符号链接。

Update on GitHub