# 从 Hub 下载文件

`huggingface_hub` 库提供了从 Hub 上存储的仓库下载文件的函数。您可以独立使用这些函数，也可以将它们集成到您自己的库中，从而让用户与 Hub 的交互更加便捷。本指南将向您展示如何：

* 下载并缓存单个文件。
* 下载并缓存整个仓库。
* 将文件下载到本地文件夹。

## 下载单个文件

[hf_hub_download()](/docs/huggingface_hub/main/zh/package_reference/file_download#huggingface_hub.hf_hub_download) 函数是从 Hub 下载文件的主要函数。它会下载远程文件，以版本感知的方式将其缓存到磁盘上，并返回其本地文件路径。

> [!TIP]
> 返回的文件路径是指向 HF 本地缓存的指针。因此，请勿修改该文件，以免导致缓存损坏。如果您想了解文件缓存的更多细节，请参阅我们的[缓存指南](./manage-cache)。

### 从最新版本

使用 `repo_id`、`repo_type` 和 `filename` 参数选择要下载的文件。默认情况下，该文件被视为 `model` 仓库的一部分。

```python
>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download(repo_id="lysandre/arxiv-nlp", filename="config.json")
'/root/.cache/huggingface/hub/models--lysandre--arxiv-nlp/snapshots/894a9adde21d9a3e3843e6d5aeaaf01875c7fade/config.json'

# Download from a dataset
>>> hf_hub_download(repo_id="google/fleurs", filename="fleurs.py", repo_type="dataset")
'/root/.cache/huggingface/hub/datasets--google--fleurs/snapshots/199e4ae37915137c555b1765c01477c216287d34/fleurs.py'
```

### 从特定版本

默认情况下，会下载`main`分支的最新版本。但在某些情况下，您可能需要下载特定版本的文件（例如来自特定分支、PR、标签或提交哈希）。为此，请使用`revision`参数：

```python
# Download from the `v1.0` tag
>>> hf_hub_download(repo_id="lysandre/arxiv-nlp", filename="config.json", revision="v1.0")

# Download from the `test-branch` branch
>>> hf_hub_download(repo_id="lysandre/arxiv-nlp", filename="config.json", revision="test-branch")

# Download from Pull Request #3
>>> hf_hub_download(repo_id="lysandre/arxiv-nlp", filename="config.json", revision="refs/pr/3")

# Download from a specific commit hash
>>> hf_hub_download(repo_id="lysandre/arxiv-nlp", filename="config.json", revision="877b84a8f93f2d619faa2a6e514a32beef88ab0a")
```

**注意：**使用提交哈希时，必须使用完整长度的哈希，而不是 7 个字符的提交哈希。

### 构建下载 URL

如果您想构造用于从仓库下载文件的 URL，可以使用 [hf_hub_url()](/docs/huggingface_hub/main/zh/package_reference/file_download#huggingface_hub.hf_hub_url)，它会返回一个 URL。请注意，[hf_hub_download()](/docs/huggingface_hub/main/zh/package_reference/file_download#huggingface_hub.hf_hub_download) 内部使用了该函数。

## 下载整个仓库

[snapshot_download()](/docs/huggingface_hub/main/zh/package_reference/file_download#huggingface_hub.snapshot_download) 用于下载指定修订版本下的整个仓库。它内部使用 [hf_hub_download()](/docs/huggingface_hub/main/zh/package_reference/file_download#huggingface_hub.hf_hub_download)，这意味着所有下载的文件也会缓存在本地磁盘上。下载过程是并发执行的，以加快处理速度。

要下载整个仓库，只需传入 `repo_id` 和 `repo_type`：

```python
>>> from huggingface_hub import snapshot_download
>>> snapshot_download(repo_id="lysandre/arxiv-nlp")
'/home/lysandre/.cache/huggingface/hub/models--lysandre--arxiv-nlp/snapshots/894a9adde21d9a3e3843e6d5aeaaf01875c7fade'

# Or from a dataset
>>> snapshot_download(repo_id="google/fleurs", repo_type="dataset")
'/home/lysandre/.cache/huggingface/hub/datasets--google--fleurs/snapshots/199e4ae37915137c555b1765c01477c216287d34'
```

[snapshot_download()](/docs/huggingface_hub/main/zh/package_reference/file_download#huggingface_hub.snapshot_download) 默认下载最新修订版本。如果您需要特定的仓库修订版本，请使用 `revision` 参数：

```python
>>> from huggingface_hub import snapshot_download
>>> snapshot_download(repo_id="lysandre/arxiv-nlp", revision="refs/pr/1")
```

### 筛选要下载的文件

[snapshot_download()](/docs/huggingface_hub/main/zh/package_reference/file_download#huggingface_hub.snapshot_download) 提供了一种便捷的方式来下载仓库。但您并不总是需要下载仓库的全部内容。例如，如果您确定只会使用 `.safetensors` 权重，可能希望避免下载所有 `.bin` 文件。您可以使用 `allow_patterns` 和 `ignore_patterns` 参数来实现这一点。

这些参数接受单个模式或模式列表。模式是标准通配符（globbing 模式），文档见[此处](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm)。模式匹配基于[`fnmatch`](https://docs.python.org/3/library/fnmatch.html)。

例如，您可以使用 `allow_patterns` 来仅下载 JSON 配置文件：

```python
>>> from huggingface_hub import snapshot_download
>>> snapshot_download(repo_id="lysandre/arxiv-nlp", allow_patterns="*.json")
```

另一方面，`ignore_patterns` 可以排除某些文件不被下载。以下示例忽略了 `.msgpack` 和 `.h5` 文件扩展名：

```python
>>> from huggingface_hub import snapshot_download
>>> snapshot_download(repo_id="lysandre/arxiv-nlp", ignore_patterns=["*.msgpack", "*.h5"])
```

最后，您可以将两者结合使用，以精确筛选您的下载内容。以下是一个示例，用于下载除 `vocab.json` 之外的所有 json 和 markdown 文件。

```python
>>> from huggingface_hub import snapshot_download
>>> snapshot_download(repo_id="gpt2", allow_patterns=["*.md", "*.json"], ignore_patterns="vocab.json")
```

## 将文件下载到本地文件夹

默认情况下，我们建议使用[缓存系统](./manage-cache)从 Hub 下载文件。您可以在[hf_hub_download()](/docs/huggingface_hub/main/zh/package_reference/file_download#huggingface_hub.hf_hub_download)和[snapshot_download()](/docs/huggingface_hub/main/zh/package_reference/file_download#huggingface_hub.snapshot_download)中使用`cache_dir`参数指定自定义缓存位置，或者通过设置[`HF_HOME`](../package_reference/environment_variables#hf_home)环境变量来实现。

不过，如果您需要将文件下载到特定文件夹，可以向下载函数传递 `local_dir` 参数。这有助于使工作流更接近 `git` 命令所提供的功能。下载的文件将在指定文件夹内保留其原始文件结构。例如，如果 `filename="data/train.csv"` 且 `local_dir="path/to/folder"`，则生成的文件路径为 `"path/to/folder/data/train.csv"`。

在本地目录的根目录下会创建一个 `.cache/huggingface/` 文件夹，其中包含已下载文件的元数据。如果文件已是最新，这将避免重复下载。如果元数据已更改，则会下载新版本的文件。这使得 `local_dir` 能够优化为仅拉取最新的更改。

完成下载后，如果不再需要，您可以安全地删除 `.cache/huggingface/` 文件夹。但请注意，在没有该文件夹的情况下重新运行脚本可能会导致更长的恢复时间，因为元数据将会丢失。请放心，您的本地数据将保持完整且不受影响。

> [!TIP]
> 在将更改提交到 Hub 时，无需担心 `.cache/huggingface/` 文件夹！该文件夹会被 `git` 和 [upload_folder()](/docs/huggingface_hub/main/zh/package_reference/hf_api#huggingface_hub.HfApi.upload_folder) 自动忽略。

## 从 CLI 下载

您可以在终端中使用 `hf download` 命令直接从 Hub 下载文件。该命令内部使用了上文所述的 [hf_hub_download()](/docs/huggingface_hub/main/zh/package_reference/file_download#huggingface_hub.hf_hub_download) 和 [snapshot_download()](/docs/huggingface_hub/main/zh/package_reference/file_download#huggingface_hub.snapshot_download) 辅助函数，并将返回的路径打印到终端。

```bash
>>> hf download gpt2 config.json
/home/wauplin/.cache/huggingface/hub/models--gpt2/snapshots/11c5a3d5811f50298f278a704980280950aedb10/config.json
```

您可以一次下载多个文件，这将显示进度条并返回文件所在的快照路径：

```bash
>>> hf download gpt2 config.json model.safetensors
Fetching 2 files: 100%|████████████████████████████████████████████| 2/2 [00:00<00:00, 23831.27it/s]
/home/wauplin/.cache/huggingface/hub/models--gpt2/snapshots/11c5a3d5811f50298f278a704980280950aedb10
```

您也可以通过单个 `hf://` URI 指向仓库（以及可选的修订版本和文件）。该 URI 遵循语法 `hf://[<TYPE>/]<ID>[@<REVISION>][/<PATH>]`（完整语法请参阅 [HF URIs 参考](../package_reference/hf_uris)），并取代了 `--repo-type` 和 `--revision` 选项，这些选项不能与其同时设置：

```bash
# Download a single file from a dataset at a given revision
>>> hf download hf://datasets/google/fleurs@refs/pr/1/fleurs.py

# Download a subfolder (note the trailing slash)
>>> hf download hf://datasets/google/fleurs/data/

# Download an entire repo
>>> hf download hf://datasets/google/fleurs
```

有关 CLI 下载命令的更多详细信息，请参阅 [CLI 指南](./cli#hf-download)。

## 试运行模式

在某些情况下，您可能希望在真正下载之前先检查哪些文件将被下载。您可以使用 `--dry-run` 参数来执行此操作。它会列出仓库中所有待下载的文件，并检查它们是否已经下载。这有助于了解需要下载的文件数量及其大小。

下面是一个示例，用于检查单个文件：

```sh
>>> hf download openai-community/gpt2 onnx/decoder_model_merged.onnx --dry-run
[dry-run] Will download 1 files (out of 1) totalling 655.2M
File                           Bytes to download
------------------------------ -----------------
onnx/decoder_model_merged.onnx 655.2M
```

如果文件已经缓存：

```sh
>>> hf download openai-community/gpt2 onnx/decoder_model_merged.onnx --dry-run
[dry-run] Will download 0 files (out of 1) totalling 0.0.
File                           Bytes to download
------------------------------ -----------------
onnx/decoder_model_merged.onnx -
```

您也可以在完整仓库上执行试运行：

```sh
>>> hf download openai-community/gpt2 --dry-run
[dry-run] Fetching 26 files: 100%|█████████████| 26/26 [00:04<00:00,  6.26it/s]
[dry-run] Will download 11 files (out of 26) totalling 5.6G.
File                              Bytes to download
--------------------------------- -----------------
.gitattributes                    -
64-8bits.tflite                   125.2M
64-fp16.tflite                    248.3M
64.tflite                         495.8M
README.md                         -
config.json                       -
flax_model.msgpack                497.8M
generation_config.json            -
merges.txt                        -
model.safetensors                 548.1M
onnx/config.json                  -
onnx/decoder_model.onnx           653.7M
onnx/decoder_model_merged.onnx    655.2M
onnx/decoder_with_past_model.onnx 653.7M
onnx/generation_config.json       -
onnx/merges.txt                   -
onnx/special_tokens_map.json      -
onnx/tokenizer.json               -
onnx/tokenizer_config.json        -
onnx/vocab.json                   -
pytorch_model.bin                 548.1M
rust_model.ot                     702.5M
tf_model.h5                       497.9M
tokenizer.json                    -
tokenizer_config.json             -
vocab.json                        -
```

以及使用文件过滤：

```sh
>>> hf download openai-community/gpt2 --include "*.json"  --dry-run
[dry-run] Fetching 11 files: 100%|█████████████| 11/11 [00:00<00:00, 80518.92it/s]
[dry-run] Will download 0 files (out of 11) totalling 0.0.
File                         Bytes to download
---------------------------- -----------------
config.json                  -
generation_config.json       -
onnx/config.json             -
onnx/generation_config.json  -
onnx/special_tokens_map.json -
onnx/tokenizer.json          -
onnx/tokenizer_config.json   -
onnx/vocab.json              -
tokenizer.json               -
tokenizer_config.json        -
vocab.json                   -
```

最后，你还可以通过向 [hf_hub_download()](/docs/huggingface_hub/main/zh/package_reference/file_download#huggingface_hub.hf_hub_download) 和 [snapshot_download()](/docs/huggingface_hub/main/zh/package_reference/file_download#huggingface_hub.snapshot_download) 传递 `dry_run=True` 来以编程方式执行试运行。它将返回一个 [DryRunFileInfo](/docs/huggingface_hub/main/zh/package_reference/hf_api#huggingface_hub.DryRunFileInfo)（或一个 [DryRunFileInfo](/docs/huggingface_hub/main/zh/package_reference/hf_api#huggingface_hub.DryRunFileInfo) 列表），其中包含每个文件的提交哈希值、文件名和文件大小，以及该文件是否已缓存、是否会被下载。实际上，如果文件未缓存或传递了 `force_download=True`，该文件将会被下载。

## 更快的下载速度

借助 `hf_xet` 实现更快的下载速度，它是 [`xet-core`](https://github.com/huggingface/xet-core) 库的 Python 绑定，通过基于块的重复数据删除来加速下载和上传。`hf_xet` 可与 `huggingface_hub` 无缝集成，但它使用的是 Rust `xet-core` 库和 Xet 存储，而非 LFS。

`hf_xet` 使用 Xet 存储系统，该系统将文件拆分为不可变的块，并将这些块的集合（称为 block 或 xorb）存储在远程，在请求时检索它们以重新组装文件。下载时，在确认用户有权访问文件后，`hf_xet` 会使用此文件的 LFS SHA256 哈希值查询 Xet 内容寻址服务（CAS），以获取重建元数据（xorb 内的范围）来组装这些文件，以及用于直接下载 xorb 的预签名 URL。然后 `hf_xet` 会高效地下载所需的 xorb 范围，并将文件写入磁盘。

要启用此功能，只需安装最新版本的 `huggingface_hub`：

```bash
pip install -U "huggingface_hub"
```

从 `huggingface_hub` 0.32.0 版本开始，此操作还将安装 `hf_xet`。

所有其他 `huggingface_hub` API 将继续正常工作，无需任何修改。要了解 Xet 存储和 `hf_xet` 的优势，请参阅此 [部分](https://huggingface.co/docs/hub/xet/index)。

注意：`hf_transfer` 此前用于 LFS 存储后端，现已弃用；请改用 `hf_xet`。

