# 实用工具

## 配置日志[[huggingface_hub.utils.logging.get_verbosity]]

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

```py
from huggingface_hub import logging
```

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

```python
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.utils.logging.get_verbosity]]

```python
huggingface_hub.utils.logging.get_verbosity()
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/logging.py#L103)

**返回：**

日志级别，例如 `huggingface_hub.logging.DEBUG` 和 `huggingface_hub.logging.INFO`。

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

> [!TIP]
> 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[[huggingface_hub.utils.logging.set_verbosity]]

```python
huggingface_hub.utils.logging.set_verbosity(verbosity: int)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/logging.py#L122)

**参数：**

verbosity (`int`) : 日志级别，例如 `huggingface_hub.logging.DEBUG` 和 `huggingface_hub.logging.INFO`。

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

#### huggingface_hub.utils.logging.set_verbosity_info[[huggingface_hub.utils.logging.set_verbosity_info]]

```python
huggingface_hub.utils.logging.set_verbosity_info()
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/logging.py#L134)

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

#### huggingface_hub.utils.logging.set_verbosity_debug[[huggingface_hub.utils.logging.set_verbosity_debug]]

```python
huggingface_hub.utils.logging.set_verbosity_debug()
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/logging.py#L148)

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

#### huggingface_hub.utils.logging.set_verbosity_warning[[huggingface_hub.utils.logging.set_verbosity_warning]]

```python
huggingface_hub.utils.logging.set_verbosity_warning()
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/logging.py#L141)

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

#### huggingface_hub.utils.logging.set_verbosity_error[[huggingface_hub.utils.logging.set_verbosity_error]]

```python
huggingface_hub.utils.logging.set_verbosity_error()
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/logging.py#L155)

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

#### huggingface_hub.utils.logging.disable_propagation[[huggingface_hub.utils.logging.disable_propagation]]

```python
huggingface_hub.utils.logging.disable_propagation()
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/logging.py#L162)

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

#### huggingface_hub.utils.logging.enable_propagation[[huggingface_hub.utils.logging.enable_propagation]]

```python
huggingface_hub.utils.logging.enable_propagation()
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/logging.py#L170)

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

### 特定于仓库的辅助方法[[huggingface_hub.utils.logging.get_logger]]

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

#### huggingface_hub.utils.logging.get_logger[[huggingface_hub.utils.logging.get_logger]]

```python
huggingface_hub.utils.logging.get_logger(name: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/logging.py#L78)

**参数：**

name (`str`, *可选*) : 要获取的日志记录器名称，通常为文件名

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

示例：

```python
>>> 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()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.utils.enable_progress_bars) 和 [disable_progress_bars](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.utils.disable_progress_bars) 来启用/禁用它们。如果设置了环境变量，则其优先级高于辅助函数。

```py
>>> 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()
```

### 按组控制进度条

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

```py
# 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]]

#### huggingface_hub.utils.are_progress_bars_disabled[[huggingface_hub.utils.are_progress_bars_disabled]]

```python
huggingface_hub.utils.are_progress_bars_disabled(name: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/tqdm.py#L191)

**参数：**

name (`str`, *可选*) : 要检查的组名；如果为 None，则检查全局设置。

**返回：** `bool`

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

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

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

### disable_progress_bars[[huggingface_hub.utils.disable_progress_bars]]

#### huggingface_hub.utils.disable_progress_bars[[huggingface_hub.utils.disable_progress_bars]]

```python
huggingface_hub.utils.disable_progress_bars(name: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/tqdm.py#L109)

**参数：**

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

#### huggingface_hub.utils.enable_progress_bars[[huggingface_hub.utils.enable_progress_bars]]

```python
huggingface_hub.utils.enable_progress_bars(name: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/tqdm.py#L159)

**参数：**

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

**引发：** ``Warning``

- ``Warning`` -- 如果环境变量禁止更改。

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

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

## 配置 HTTP 后端[[huggingface_hub.set_client_factory]]

> [!TIP]
> 在 `huggingface_hub` v0.x 中，HTTP 请求由 `requests` 处理，配置通过 `configure_http_backend` 完成。由于我们现在使用 `httpx2`，配置方式有所不同：您必须提供一个工厂函数，该函数不接受任何参数并返回一个 `httpx2.Client`。您可以在此处查看 [默认实现](https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/utils/_http.py)，以了解默认使用的参数。

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

如果您正在构建第三方库并需要直接向 Hub 发起请求，请使用 [get_session()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.get_session) 获取配置正确的 `httpx2` 客户端。将任何直接的 `httpx2.get(...)` 调用替换为 `get_session().get(...)`，以确保行为正确。

#### huggingface_hub.set_client_factory[[huggingface_hub.set_client_factory]]

```python
huggingface_hub.set_client_factory(client_factory: Callable)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/_http.py#L373)

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

客户端工厂是一个返回 `httpx2.Client` 对象的方法。在首次调用 [get_session()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.get_session) 时，客户端工厂将被用于创建一个新的 `httpx2.Client` 对象，该对象将在 `huggingface_hub` 发出的所有调用之间共享。

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

使用 [get_session()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.get_session) 获取配置正确的 `httpx2.Client`。

#### huggingface_hub.get_session[[huggingface_hub.get_session]]

```python
huggingface_hub.get_session()
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/_http.py#L406)

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

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

使用 [set_client_factory()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.set_client_factory) 来自定义 `httpx2.Client`。

在极少数情况下，您可能需要手动关闭当前会话（例如，在出现短暂的 `SSLError` 之后）。您可以使用 [close_session()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.close_session) 来执行此操作。在下一次调用 [get_session()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.get_session) 时，将自动创建一个新的会话。

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

#### huggingface_hub.close_session[[huggingface_hub.close_session]]

```python
huggingface_hub.close_session()
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/_http.py#L435)

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

如果 Client 已关闭，则在下次调用 [get_session()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.get_session) 时会自动重新创建。

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

对于异步代码，请使用 [set_async_client_factory()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.set_async_client_factory) 来配置一个 `httpx2.AsyncClient`，并使用 [get_async_session()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.get_async_session) 来获取一个。

#### huggingface_hub.set_async_client_factory[[huggingface_hub.set_async_client_factory]]

```python
huggingface_hub.set_async_client_factory(async_client_factory: Callable)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/_http.py#L390)

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

异步客户端工厂是一个返回 `httpx2.AsyncClient` 对象的方法。如果您在需要自定义配置（例如自定义代理或证书）的特定环境中运行脚本，这将非常有用。请使用 [get_async_session()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.get_async_session) 来获取配置正确的 `httpx2.AsyncClient`。

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

#### huggingface_hub.get_async_session[[huggingface_hub.get_async_session]]

```python
huggingface_hub.get_async_session()
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/_http.py#L422)

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

使用 [set_async_client_factory()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.set_async_client_factory) 来自定义 `httpx2.AsyncClient`。

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

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

### `httpx` 模块

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

```py
from huggingface_hub.utils import httpx

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

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

> [!WARNING]
> 仅在需要 `httpx` 类型或异常（例如用于捕获错误）时使用此方法。要向 Hub 发起请求，请按照上述说明使用 [get_session()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.get_session)。

## 处理 HTTP 错误

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

### 针对状态抛出异常[[huggingface_hub.hf_raise_for_status]]

[hf_raise_for_status()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.hf_raise_for_status) 旨在作为针对向 Hub 发出的任何请求执行“状态检查并抛出异常”的核心方法。它封装了基础的 `httpx2.Response.raise_for_status` 以提供更多信息。任何抛出的 `HTTPError` 都会被转换为 `HfHubHTTPError`。

```py
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[[huggingface_hub.hf_raise_for_status]]

```python
huggingface_hub.hf_raise_for_status(response: Response, endpoint_name: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/_http.py#L827)

**参数：**

response (`Response`)：来自服务器的响应。

endpoint_name (`str`，*可选*)：所调用端点的名称。如果提供，错误信息将更完整。

`response.raise_for_status()` 的内部版本，用于细化潜在的 HTTPError。抛出的异常将是 [HfHubHTTPError](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.errors.HfHubHTTPError) 的实例。

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

> [!WARNING]
> 请求失败时引发：
>
> - [RepositoryNotFoundError](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.errors.RepositoryNotFoundError) 如果找不到要下载的仓库。这可能是因为它不存在、`repo_type` 未正确设置，或者该仓库是 `private` 且您没有访问权限。 - [GatedRepoError](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.errors.GatedRepoError) 如果仓库存在但受访问控制，且用户不在授权列表中。 - [RevisionNotFoundError](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.errors.RevisionNotFoundError) 如果仓库存在但找不到指定的修订版本。 - [EntryNotFoundError](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.errors.EntryNotFoundError) 如果仓库存在但找不到条目（例如请求的文件）。 - [EgressLimitError](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.errors.EgressLimitError) 如果账户已达到其出口流量（下载）配额。 - [BadRequestError](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.errors.BadRequestError) 如果请求因 HTTP 400 BadRequest 错误而失败。 - [HfHubHTTPError](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.errors.HfHubHTTPError) 如果请求因上述未列出的原因而失败。

### 检查离线模式[[huggingface_hub.is_offline_mode]]

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

#### huggingface_hub.is_offline_mode[[huggingface_hub.is_offline_mode]]

```python
huggingface_hub.is_offline_mode()
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/constants.py#L197)

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

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

示例：
```py
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[[huggingface_hub.errors.HfHubHTTPError]]

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

#### huggingface_hub.errors.HfHubHTTPError[[huggingface_hub.errors.HfHubHTTPError]]

```python
huggingface_hub.errors.HfHubHTTPError(message: str, response: Response, server_message: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L90)

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

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

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

示例：
```py
    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[[huggingface_hub.errors.HfHubHTTPError.append_to_message]]

```python
append_to_message(additional_message: str)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L137)

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

#### RepositoryNotFoundError[[huggingface_hub.errors.RepositoryNotFoundError]]

#### huggingface_hub.errors.RepositoryNotFoundError[[huggingface_hub.errors.RepositoryNotFoundError]]

```python
huggingface_hub.errors.RepositoryNotFoundError(message: str, response: Response, server_message: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L313)

**参数：**

repo_id (`str` 或 `None`) : 如果可以从请求 URL 中确定，则为未找到的仓库 ID。

repo_type (`str` 或 `None`)：如果可以从请求 URL 中确定，则为仓库类型（"model"、"dataset" 或 "space"）。

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

示例：

```py
>>> 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]]

#### huggingface_hub.errors.GatedRepoError[[huggingface_hub.errors.GatedRepoError]]

```python
huggingface_hub.errors.GatedRepoError(message: str, response: Response, server_message: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L343)

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

注意：派生自 `RepositoryNotFoundError`，以确保向后兼容性。

示例：

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

#### EgressLimitError[[huggingface_hub.errors.EgressLimitError]]

#### huggingface_hub.errors.EgressLimitError[[huggingface_hub.errors.EgressLimitError]]

```python
huggingface_hub.errors.EgressLimitError(message: str, response: Response, server_message: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L386)

当 Hub 因账户已达到其出口（下载）配额而拒绝请求时抛出。

服务器消息说明了当前的使用情况以及如何获取更高的配额。

示例：

```py
>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download("username/my-model", "model.safetensors")
(...)
huggingface_hub.errors.EgressLimitError: 402 Client Error. (Request ID: Root=1-...)

Egress limit reached for url: https://huggingface.co/username/my-model/resolve/main/model.safetensors.
You've downloaded (...) over the last 30 days, compared to your account's egress allowance of (...).
```

#### RevisionNotFoundError[[huggingface_hub.errors.RevisionNotFoundError]]

#### huggingface_hub.errors.RevisionNotFoundError[[huggingface_hub.errors.RevisionNotFoundError]]

```python
huggingface_hub.errors.RevisionNotFoundError(message: str, response: Response, server_message: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L409)

**参数：**

repo_id (`str` 或 `None`)：如果可以从请求 URL 中确定，则为仓库 ID。

repo_type (`str` 或 `None`)：如果可以从请求 URL 中确定，则为仓库类型（"model"、"dataset" 或 "space"）。

在尝试访问 hf.co 上的 URL 时，如果仓库有效但修订版本无效，则会引发此错误。

示例：

```py
>>> 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]]

#### huggingface_hub.errors.RevisionResolutionError[[huggingface_hub.errors.RevisionResolutionError]]

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L436)

当修订版本无法解析为提交哈希时，由 [HfApi.resolve_revision()](/docs/huggingface_hub/v2.5.0/zh/package_reference/hf_api#huggingface_hub.HfApi.resolve_revision) 抛出：无法连接到 Hub（离线模式、连接错误、超时、Hub 停机、……），且在本地缓存中未找到匹配的条目。

#### BadRequestError[[huggingface_hub.errors.BadRequestError]]

#### huggingface_hub.errors.BadRequestError[[huggingface_hub.errors.BadRequestError]]

```python
huggingface_hub.errors.BadRequestError(message: str, response: Response, server_message: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L527)

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

示例：

```py
>>> 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]]

#### huggingface_hub.errors.EntryNotFoundError[[huggingface_hub.errors.EntryNotFoundError]]

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L445)

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

示例：

```py
>>> 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]]

#### huggingface_hub.errors.RemoteEntryNotFoundError[[huggingface_hub.errors.RemoteEntryNotFoundError]]

```python
huggingface_hub.errors.RemoteEntryNotFoundError(message: str, response: Response, server_message: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L463)

**参数：**

repo_id (`str` 或 `None`)：如果可以从请求 URL 中确定，则为仓库 ID。

repo_type (`str` 或 `None`)：如果可以从请求 URL 中确定，则为仓库类型（"model"、"dataset" 或 "space"）。

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

示例：

```py
>>> 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]]

#### huggingface_hub.errors.LocalEntryNotFoundError[[huggingface_hub.errors.LocalEntryNotFoundError]]

```python
huggingface_hub.errors.LocalEntryNotFoundError(message: str)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L490)

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

示例：

```py
>>> 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]]

#### huggingface_hub.errors.IncompleteSnapshotError[[huggingface_hub.errors.IncompleteSnapshotError]]

```python
huggingface_hub.errors.IncompleteSnapshotError(message: str, snapshot_path: str)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L509)

当 Hub 无法访问（离线、连接问题或 `local_files_only=True`）且已知缓存快照不完整时，由 [snapshot_download()](/docs/huggingface_hub/v2.5.0/zh/package_reference/file_download#huggingface_hub.snapshot_download) 引发：仓库缓存树列表中列出的某些文件在本地快照中缺失。

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

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

#### CachedRepoTreeNotFoundError[[huggingface_hub.errors.CachedRepoTreeNotFoundError]]

#### huggingface_hub.errors.CachedRepoTreeNotFoundError[[huggingface_hub.errors.CachedRepoTreeNotFoundError]]

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L26)

当请求的修订版本没有缓存的树列表时，由 [get_cached_repo_tree()](/docs/huggingface_hub/v2.5.0/zh/package_reference/file_download#huggingface_hub.get_cached_repo_tree) 引发。

树状列表是作为 [snapshot_download()](/docs/huggingface_hub/v2.5.0/zh/package_reference/file_download#huggingface_hub.snapshot_download) 的副作用而填充的。

#### OfflineModeIsEnabled[[huggingface_hub.errors.OfflineModeIsEnabled]]

#### huggingface_hub.errors.OfflineModeIsEnabled[[huggingface_hub.errors.OfflineModeIsEnabled]]

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L86)

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

## 遥测[[huggingface_hub.utils.send_telemetry]]

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

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

#### huggingface_hub.utils.send_telemetry[[huggingface_hub.utils.send_telemetry]]

```python
huggingface_hub.utils.send_telemetry(topic: str, library_name: str | None = None, library_version: str | None = None, user_agent: dict | str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/_telemetry.py#L19)

**参数：**

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` 时），遥测功能同样会被禁用。

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

示例：
```py
>>> 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](https://pydantic-docs.helpmanual.io/) 中用于验证类型提示的工作，但功能更为有限。

### 通用装饰器

[validate_hf_hub_args()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.utils.validate_hf_hub_args) 是一个通用装饰器，用于封装那些参数遵循 `huggingface_hub` 命名规范的方法。默认情况下，所有已实现验证器的参数都会被验证。

如果输入无效，则会抛出 [HFValidationError](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.errors.HFValidationError)。只有第一个无效值会触发错误并停止验证过程。

用法：

```py
>>> 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]]

#### huggingface_hub.utils.validate_hf_hub_args[[huggingface_hub.utils.validate_hf_hub_args]]

```python
huggingface_hub.utils.validate_hf_hub_args(fn: ~CallableT)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/_validators.py#L42)

**引发：** [HFValidationError](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.errors.HFValidationError)

- [HFValidationError](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.errors.HFValidationError) -- 如果输入无效。

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

该装饰器的目标是统一各处复用的参数验证。默认情况下，所有已定义的验证器都会被执行。

验证器：
- [validate_repo_id()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.utils.validate_repo_id)：`repo_id` 必须是 `"repo_name"` 或 `"namespace/repo_name"`。Namespace 是用户名或组织。
- `~utils.smoothly_deprecate_legacy_arguments`：下载文件时忽略 `proxies`（应全局设置）。

示例：
```py
>>> 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.errors.HFValidationError[[huggingface_hub.errors.HFValidationError]]

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L217)

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

继承自 [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)。

### 参数验证器

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

#### repo_id[[huggingface_hub.utils.validate_repo_id]]

#### huggingface_hub.utils.validate_repo_id[[huggingface_hub.utils.validate_repo_id]]

```python
huggingface_hub.utils.validate_repo_id(repo_id: str | None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/_validators.py#L94)

验证 `repo_id` 是否有效。

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

规则：
- 1 到 96 个字符之间。
- “repo_name”或“namespace/repo_name”
- 或 “-”、“_”、“.”
- “--”和“..”是被禁止的

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

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

示例：
```py
>>> 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（内部仓库）中：
- https://github.com/huggingface/moon-landing/blob/main/server/lib/Names.ts#L27
- https://github.com/huggingface/moon-landing/blob/main/server/views/components/NewRepoForm/NewRepoForm.svelte#L138

#### smoothly_deprecate_legacy_arguments[[huggingface_hub.utils._validators.smoothly_deprecate_legacy_arguments]]

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

#### huggingface_hub.utils._validators.smoothly_deprecate_legacy_arguments[[huggingface_hub.utils._validators.smoothly_deprecate_legacy_arguments]]

```python
huggingface_hub.utils._validators.smoothly_deprecate_legacy_arguments(fn_name: str, kwargs: dict)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/utils/_validators.py#L152)

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

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

已弃用参数列表：
- `proxies`：要设置代理，用户必须使用 HTTP_PROXY 环境变量，或者使用 [set_client_factory()](/docs/huggingface_hub/v2.5.0/zh/package_reference/utilities#huggingface_hub.set_client_factory) 函数手动配置 `httpx2.Client`。

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

  有关更多详细信息，请参阅：
  - https://httpx2.pydantic.dev/advanced/proxies/

- `resume_download`：已弃用，无替代方案。`huggingface_hub` 在可能的情况下始终会恢复下载。
- `force_filename`：已弃用，无替代方案。文件名始终与 Hub 上的相同。
- `local_dir_use_symlinks`：已弃用，无替代方案。下载到本地目录时不再使用符号链接。

