# Huggingface_Hub

## Docs

- [🤗 Hub 客户端库](https://huggingface.co/docs/huggingface_hub/main/cn/index.md)
- [安装](https://huggingface.co/docs/huggingface_hub/main/cn/installation.md)
- [快速入门](https://huggingface.co/docs/huggingface_hub/main/cn/quick-start.md)
- [创建和管理存储库](https://huggingface.co/docs/huggingface_hub/main/cn/guides/repository.md)
- [集合（Collections）](https://huggingface.co/docs/huggingface_hub/main/cn/guides/collections.md)
- [操作指南](https://huggingface.co/docs/huggingface_hub/main/cn/guides/overview.md)
- [互动讨论与拉取请求（Pull Request）](https://huggingface.co/docs/huggingface_hub/main/cn/guides/community.md)
- [通过文件系统 API 与 Hub 交互](https://huggingface.co/docs/huggingface_hub/main/cn/guides/hf_file_system.md)
- [搜索 Hub](https://huggingface.co/docs/huggingface_hub/main/cn/guides/search.md)

### 🤗 Hub 客户端库
https://huggingface.co/docs/huggingface_hub/main/cn/index.md

# 🤗 Hub 客户端库

通过`huggingface_hub` 库，您可以与面向机器学习开发者和协作者的平台 [Hugging Face Hub](https://huggingface.co/)进行交互，找到适用于您所在项目的预训练模型和数据集，体验在平台托管的数百个机器学习应用，还可以创建或分享自己的模型和数据集并于社区共享。以上所有都可以用Python在`huggingface_hub` 库中轻松实现。

阅读[快速入门指南](快速入门指南)以开始使用huggingface_hub库。您将学习如何从Hub下载文件,创建存储库以及将文件上传到Hub。继续阅读以了解更多关于如何在🤗Hub上管理您的存储库,如何参与讨论或者甚至如何访问推理API的信息。

<div class="mt-10">
  <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./guides/overview">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">操作指南</div>
      <p class="text-gray-700">实用指南可帮助您实现特定目标。查看这些指南，了解如何使用 huggingface_hub 解决实际问题。</p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./package_reference/overview">
      <div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">参考</div>
      <p class="text-gray-700">huggingface_hub 类和方法的详尽技术描述。</p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./concepts/git_vs_http">
      <div class="w-full text-center bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">概念指南</div>
      <p class="text-gray-700">更好地理解 huggingface_hub 哲学的高级概念。</p>
    </a>

</div>
</div>

通过 `huggingface_hub`库，您可以与面向机器学习开发者和协作者的平台 [Hugging Face Hub](https://huggingface.co/)进行交互，找到适用于您所在项目的预训练模型和数据集，体验在平台托管的数百个机器学习应用，还可以创建或分享自己的模型和数据集并于社区共享。以上所有都可以用Python在 `huggingface_hub`库中轻松实现。

<!--
<a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./tutorials/overview"
  ><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Tutorials</div>
  <p class="text-gray-700">Learn the basics and become familiar with using huggingface_hub to programmatically interact with the 🤗 Hub!</p>
</a> -->

## 贡献

所有对 huggingface_hub 的贡献都受到欢迎和同等重视！🤗 除了在代码中添加或修复现有问题外，您还可以通过确保其准确且最新来帮助改进文档，在问题上帮助回答问题，并请求您认为可以改进库的新功能。请查看[贡献指南](https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md) 了解有关如何提交新问题或功能请求、如何提交拉取请求以及如何测试您的贡献以确保一切正常运行的更多信息。

当然，贡献者也应该尊重我们的[行为准则](https://github.com/huggingface/huggingface_hub/blob/main/CODE_OF_CONDUCT.md)，以便为每个人创建一个包容和欢迎的协作空间。


<EditOnGithub source="https://github.com/huggingface/huggingface_hub/blob/main/docs/source/cn/index.md" />

### 安装
https://huggingface.co/docs/huggingface_hub/main/cn/installation.md

# 安装

在开始之前，您需要通过安装适当的软件包来设置您的环境

huggingface_hub 在 Python 3.9 或更高版本上进行了测试，可以保证在这些版本上正常运行。如果您使用的是 Python 3.7 或更低版本，可能会出现兼容性问题

## 使用 pip 安装

我们建议将huggingface_hub安装在[虚拟环境](https://docs.python.org/3/library/venv.html)中.
如果你不熟悉 Python虚拟环境,可以看看这个[指南](https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/).

虚拟环境可以更容易地管理不同的项目,避免依赖项之间的兼容性问题

首先在你的项目目录中创建一个虚拟环境,请运行以下代码:

```bash
python -m venv .env
```

在Linux和macOS上,请运行以下代码激活虚拟环境:

```bash
source .env/bin/activate
```

在 Windows 上，请运行以下代码激活虚拟环境:

```bash
.env/Scripts/activate
```

现在您可以从[PyPi注册表](https://pypi.org/project/huggingface-hub/)安装 `huggingface_hub`：

```bash
pip install --upgrade huggingface_hub
```

完成后,[检查安装](#check-installation)是否正常工作

### 安装可选依赖项

`huggingface_hub`的某些依赖项是 [可选](https://setuptools.pypa.io/en/latest/userguide/dependency_management.html#optional-dependencies) 的，因为它们不是运行`huggingface_hub`的核心功能所必需的.但是，如果没有安装可选依赖项， `huggingface_hub` 的某些功能可能会无法使用

您可以通过`pip`安装可选依赖项,请运行以下代码：

```bash
# 安装 Torch 特定功能和 CLI 特定功能的依赖项
pip install 'huggingface_hub[cli,torch]'
```

这里列出了 `huggingface_hub` 的可选依赖项：

- `cli`：为 `huggingface_hub` 提供更方便的命令行界面

- `fastai`,` torch`: 运行框架特定功能所需的依赖项

- `dev`：用于为库做贡献的依赖项。包括 `testing`（用于运行测试）、`typing`（用于运行类型检查器）和 `quality`（用于运行 linter）

### 从源代码安装

在某些情况下，直接从源代码安装`huggingface_hub`会更有趣。因为您可以使用最新的主版本`main`而非最新的稳定版本

`main`版本更有利于跟进平台的最新开发进度，例如，在最近一次官方发布之后和最新的官方发布之前所修复的某个错误

但是，这意味着`main`版本可能不总是稳定的。我们会尽力让其正常运行，大多数问题通常会在几小时或一天内解决。如果您遇到问题，请创建一个 Issue ，以便我们可以更快地解决！

```bash
pip install git+https://github.com/huggingface/huggingface_hub  # 使用pip从GitHub仓库安装Hugging Face Hub库
```

从源代码安装时，您还可以指定特定的分支。如果您想测试尚未合并的新功能或新错误修复，这很有用

```bash
pip install git+https://github.com/huggingface/huggingface_hub@my-feature-branch  # 使用pip从指定的GitHub分支（my-feature-branch）安装Hugging Face Hub库
```

完成安装后，请[检查安装](#check-installation)是否正常工作

### 可编辑安装

从源代码安装允许您设置[可编辑安装](https://pip.pypa.io/en/stable/topics/local-project-installs/#editable-installs).如果您计划为`huggingface_hub`做出贡献并需要测试代码更改，这是一个更高级的安装方式。您需要在本机上克隆一个`huggingface_hub`的本地副本

```bash
# 第一，使用以下命令克隆代码库
git clone https://github.com/huggingface/huggingface_hub.git

# 然后，使用以下命令启动虚拟环境
cd huggingface_hub
pip install -e .
```

这些命令将你克隆存储库的文件夹与你的 Python 库路径链接起来。Python 现在将除了正常的库路径之外，还会在你克隆到的文件夹中查找。例如，如果你的 Python 包通常安装在`./.venv/lib/python3.13/site-packages/`中，Python 还会搜索你克隆的文件夹`./huggingface_hub/`

## 通过 conda 安装

如果你更熟悉它，你可以使用[conda-forge channel](https://anaconda.org/conda-forge/huggingface_hub)渠道来安装 `huggingface_hub`

请运行以下代码：

```bash
conda install -c conda-forge huggingface_hub
```
完成安装后，请[检查安装](#check-installation)是否正常工作

## 验证安装

安装完成后，通过运行以下命令检查`huggingface_hub`是否正常工作:

```bash
python -c "from huggingface_hub import model_info; print(model_info('gpt2'))"
```

这个命令将从 Hub 获取有关 [gpt2](https://huggingface.co/gpt2) 模型的信息。

输出应如下所示：

```text
Model Name: gpt2  模型名称
Tags: ['pytorch', 'tf', 'jax', 'tflite', 'rust', 'safetensors', 'gpt2', 'text-generation', 'en', 'doi:10.57967/hf/0039', 'transformers', 'exbert', 'license:mit', 'has_space']  标签
Task: text-generation  任务：文本生成
```

## Windows局限性

为了实现让每个人都能使用机器学习的目标，我们构建了 `huggingface_hub`库，使其成为一个跨平台的库，尤其可以在 Unix 和 Windows 系统上正常工作。但是，在某些情况下，`huggingface_hub`在Windows上运行时会有一些限制。以下是一些已知问题的完整列表。如果您遇到任何未记录的问题，请打开 [Github上的issue](https://github.com/huggingface/huggingface_hub/issues/new/choose).让我们知道

- `huggingface_hub`的缓存系统依赖于符号链接来高效地缓存从Hub下载的文件。在Windows上，您必须激活开发者模式或以管理员身份运行您的脚本才能启用符号链接。如果它们没有被激活，缓存系统仍然可以工作，但效率较低。有关更多详细信息，请阅读[缓存限制](./guides/manage-cache#limitations)部分。

- Hub上的文件路径可能包含特殊字符（例如:`path/to?/my/file`）。Windows对[特殊字符](https://learn.microsoft.com/en-us/windows/win32/intl/character-sets-used-in-file-names)更加严格，这使得在Windows上下载这些文件变得不可能。希望这是罕见的情况。如果您认为这是一个错误，请联系存储库所有者或我们，以找出解决方案。


## 后记

一旦您在机器上正确安装了`huggingface_hub`，您可能需要[配置环境变量](package_reference/environment_variables)或者[查看我们的指南之一](guides/overview)以开始使用。


<EditOnGithub source="https://github.com/huggingface/huggingface_hub/blob/main/docs/source/cn/installation.md" />

### 快速入门
https://huggingface.co/docs/huggingface_hub/main/cn/quick-start.md

# 快速入门

[Hugging Face Hub](https://huggingface.co/)是分享机器学习模型、演示、数据集和指标的首选平台`huggingface_hub`库帮助你在不离开开发环境的情况下与 Hub 进行交互。你可以轻松地创建和管理仓库,下载和上传文件,并从 Hub 获取有用的模型和数据集元数据

## 安装

要开始使用,请安装`huggingface_hub`库:

```bash
pip install --upgrade huggingface_hub
```

更多详细信息,请查看[安装指南](installation)

## 下载文件

Hugging Face 平台上的存储库是使用 git 版本控制的，用户可以下载单个文件或整个存储库。您可以使用 `hf_hub_download()` 函数下载文件。该函数将下载并将文件缓存在您的本地磁盘上。下次您需要该文件时，它将从您的缓存中加载，因此您无需重新下载它

您将需要填写存储库 ID 和您要下载的文件的文件名。例如，要下载[Pegasus](https://huggingface.co/google/pegasus-xsum)模型配置文件，请运行以下代码：

```py
>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download(repo_id="google/pegasus-xsum", filename="config.json")
repo_id: 仓库的 ID 或路径，这里使用了 "google/pegasus-xsum"
filename: 要下载的文件名，这里是 "config.json"
```

要下载文件的特定版本，请使用`revision`参数指定分支名称、标签或提交哈希。如果您选择使用提交哈希，它必须是完整长度的哈希，而不是较短的7个字符的提交哈希：

```py
>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download(
...     repo_id="google/pegasus-xsum",
...     filename="config.json",
...   revision="4d33b01d79672f27f001f6abade33f22d993b151"
... )
```

有关更多详细信息和选项，请参阅 `hf_hub_download()` 的 API 参考文档

## 登录

在许多情况下，您必须使用 Hugging Face 帐户进行登录后才能与 Hugging Face 模型库进行交互，例如下载私有存储库、上传文件、创建 PR 等。如果您还没有帐户，请[创建一个](https://huggingface.co/join),然后登录以获取您的 [用户访问令牌](https://huggingface.co/docs/hub/security-tokens),security-tokens从您的[设置页面](https://huggingface.co/settings/tokens)进入设置,用户访问令牌用于向模型库进行身份验证

运行以下代码，这将使用您的用户访问令牌登录到Hugging Face模型库

```bash
hf auth login

hf auth login --token $HUGGINGFACE_TOKEN
```

或者，你可以在笔记本电脑或脚本中使用 `login()` 来进行程序化登录,请运行以下代码:

```py
>>> from huggingface_hub import login
>>> login()
```

您还可以直接将令牌传递给 `login()`，如下所示：`login(token="hf_xxx")`。这将使用您的用户访问令牌登录到 Hugging Face 模型库，而无需您输入任何内容。但是，如果您这样做，请在共享源代码时要小心。最好从安全保管库中加载令牌，而不是在代码库/笔记本中显式保存它

您一次只能登录一个帐户。如果您使用另一个帐户登录您的机器，您将会从之前的帐户注销。请确保使用命令 `hf auth whoami`来检查您当前使用的是哪个帐户。如果您想在同一个脚本中处理多个帐户，您可以在调用每个方法时提供您的令牌。这对于您不想在您的机器上存储任何令牌也很有用

> [!WARNING]
> 一旦您登录了，所有对模型库的请求（即使是不需要认证的方法）都将默认使用您的访问令牌。如果您想禁用对令牌的隐式使用，您应该设置`HF_HUB_DISABLE_IMPLICIT_TOKEN`环境变量

## 创建存储库

一旦您注册并登录，请使用 `create_repo()` 函数创建存储库：

```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.create_repo(repo_id="super-cool-model")
```
如果您想将存储库设置为私有，请按照以下步骤操作：

```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.create_repo(repo_id="super-cool-model", private=True)
```
私有存储库将不会对任何人可见，除了您自己

> [!TIP]
> 创建存储库或将内容推送到 Hub 时，必须提供具有`写入`权限的用户访问令牌。您可以在创建令牌时在您的[设置页面](https://huggingface.co/settings/tokens)中选择权限

## 上传文件

您可以使用 `upload_file()` 函数将文件添加到您新创建的存储库。您需要指定：

1. 要上传的文件的路径

2. 文件在存储库中的位置

3. 您要将文件添加到的存储库的 ID

```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.upload_file(
...     path_or_fileobj="/home/lysandre/dummy-test/README.md"
...     path_in_repo="README.md"
...     repo_id="lysandre/test-model"
... )
```

要一次上传多个文件，请查看[上传指南](./guides/upload) ,该指南将向您介绍几种上传文件的方法（有或没有 git）。

## 下一步

`huggingface_hub`库为用户提供了一种使用Python与Hub 进行交互的简单方法。要了解有关如何在Hub上管理文件和存储库的更多信息，我们建议您阅读我们的[操作方法指南](./guides/overview)：

- [管理您的存储库](./guides/repository)
- [从Hub下载文件](./guides/download)
- [将文件上传到Hub](./guides/upload)
- [在Hub中搜索您的所需模型或数据集](./guides/search)
- [了解如何使用 Inference API 进行快速推理](./guides/inference)


<EditOnGithub source="https://github.com/huggingface/huggingface_hub/blob/main/docs/source/cn/quick-start.md" />

### 创建和管理存储库
https://huggingface.co/docs/huggingface_hub/main/cn/guides/repository.md

# 创建和管理存储库

Hugging Face Hub是一组 Git 存储库。[Git](https://git-scm.com/)是软件开发中广泛使用的工具，可以在协作工作时轻松对项目进行版本控制。本指南将向您展示如何与 Hub 上的存储库进行交互，特别关注以下内容：

- 创建和删除存储库
- 管理分支和标签
- 重命名您的存储库
- 更新您的存储库可见性
- 管理存储库的本地副本

> [!WARNING]
> 如果您习惯于使用类似于GitLab/GitHub/Bitbucket等平台，您可能首先想到使用 `git`命令行工具来克隆存储库（`git clone`）、提交更改（`git add` , ` git commit`）并推送它们（`git push`）。在使用 Hugging Face Hub 时，这是有效的。然而，软件工程和机器学习并不具有相同的要求和工作流程。模型存储库可能会维护大量模型权重文件以适应不同的框架和工具，因此克隆存储库会导致您维护大量占用空间的本地文件夹。因此，使用我们的自定义HTTP方法可能更有效。您可以阅读我们的[git与HTTP相比较](../concepts/git_vs_http)解释页面以获取更多详细信息

如果你想在Hub上创建和管理一个仓库，你的计算机必须处于登录状态。如果尚未登录，请参考[此部分](../quick-start#login)。在本指南的其余部分，我们将假设你的计算机已登录

## 仓库创建和删除

第一步是了解如何创建和删除仓库。你只能管理你拥有的仓库（在你的用户名命名空间下）或者你具有写入权限的组织中的仓库

### 创建一个仓库

使用 `create_repo()` 创建一个空仓库，并通过 `repo_id`参数为其命名 `repo_id`是你的命名空间，后面跟着仓库名称：`username_or_org/repo_name`

运行以下代码，以创建仓库：

```py
>>> from huggingface_hub import create_repo
>>> create_repo("lysandre/test-model")
'https://huggingface.co/lysandre/test-model'
```

默认情况下，`create_repo()` 会创建一个模型仓库。但是你可以使用 `repo_type`参数来指定其他仓库类型。例如，如果你想创建一个数据集仓库

请运行以下代码：

```py
>>> from huggingface_hub import create_repo
>>> create_repo("lysandre/test-dataset", repo_type="dataset")
'https://huggingface.co/datasets/lysandre/test-dataset'
```

创建仓库时，你可以使用 `private`参数设置仓库的可见性

请运行以下代码

```py
>>> from huggingface_hub import create_repo
>>> create_repo("lysandre/test-private", private=True)
```

如果你想在以后更改仓库的可见性，你可以使用`update_repo_settings()` 函数

### 删除一个仓库

使用 `delete_repo()` 删除一个仓库。确保你确实想要删除仓库，因为这是一个不可逆转的过程！做完上述过程后，指定你想要删除的仓库的 `repo_id`

请运行以下代码：

```py
>>> delete_repo(repo_id="lysandre/my-corrupted-dataset", repo_type="dataset")
```

### 克隆一个仓库（仅适用于 Spaces）

在某些情况下，你可能想要复制别人的仓库并根据自己的用例进行调整。对于 Spaces，你可以使用 `duplicate_space()` 方法来实现。它将复制整个仓库。

你仍然需要配置自己的设置（硬件和密钥）。查看我们的[管理你的Space指南](./manage-spaces)以获取更多详细信息。

请运行以下代码：

```py
>>> from huggingface_hub import duplicate_space
>>> duplicate_space("multimodalart/dreambooth-training", private=False)
RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)
```

## 上传和下载文件

既然您已经创建了您的存储库，您现在也可以推送更改至其中并从中下载文件

这两个主题有它们自己的指南。请[上传指南](./upload) 和[下载指南](./download)来学习如何使用您的存储库。

## 分支和标签

Git存储库通常使用分支来存储同一存储库的不同版本。标签也可以用于标记存储库的特定状态，例如，在发布版本这个情况下。更一般地说，分支和标签被称为[git引用](https://git-scm.com/book/en/v2/Git-Internals-Git-References).

### 创建分支和标签

你可以使用`create_branch()`和`create_tag()`来创建新的分支和标签:

请运行以下代码：

```py
>>> from huggingface_hub import create_branch, create_tag

# Create a branch on a Space repo from `main` branch
>>> create_branch("Matthijs/speecht5-tts-demo", repo_type="space", branch="handle-dog-speaker")

# Create a tag on a Dataset repo from `v0.1-release` branch
>>> create_branch("bigcode/the-stack", repo_type="dataset", revision="v0.1-release", tag="v0.1.1", tag_message="Bump release version.")
```

同时,你可以以相同的方式使用 `delete_branch()` 和 `delete_tag()` 函数来删除分支或标签

### 列出所有的分支和标签

你还可以使用 `list_repo_refs()` 列出存储库中的现有 Git 引用
请运行以下代码：

```py
>>> from huggingface_hub import list_repo_refs
>>> 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')
   ]
)
```

## 修改存储库设置

存储库具有一些可配置的设置。大多数情况下，您通常会在浏览器中的存储库设置页面上手动配置这些设置。要配置存储库，您必须具有对其的写访问权限（拥有它或属于组织）。在本节中，我们将看到您还可以使用 `huggingface_hub` 在编程方式上配置的设置。

一些设置是特定于 Spaces（硬件、环境变量等）的。要配置这些设置，请参考我们的[管理Spaces](../guides/manage-spaces)指南。

### 更新可见性

一个存储库可以是公共的或私有的。私有存储库仅对您或存储库所在组织的成员可见。

请运行以下代码将存储库更改为私有：

```py
>>> from huggingface_hub import update_repo_settings
>>> update_repo_settings(repo_id=repo_id, private=True)
```

### 重命名您的存储库

您可以使用 `move_repo()` 在 Hub 上重命名您的存储库。使用这种方法，您还可以将存储库从一个用户移动到一个组织。在这样做时，有一些[限制](https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo)需要注意。例如，您不能将存储库转移到另一个用户。

请运行以下代码：

```py
>>> from huggingface_hub import move_repo
>>> move_repo(from_id="Wauplin/cool-model", to_id="huggingface/cool-model")
```


<EditOnGithub source="https://github.com/huggingface/huggingface_hub/blob/main/docs/source/cn/guides/repository.md" />

### 集合（Collections）
https://huggingface.co/docs/huggingface_hub/main/cn/guides/collections.md

# 集合（Collections）

集合（collection）是 Hub 上将一组相关项目（模型、数据集、Spaces、论文）组织在同一页面上的一种方式。利用集合，你可以创建自己的作品集、为特定类别的内容添加书签，或呈现你想要分享的精选条目。要了解更多关于集合的概念及其在 Hub 上的呈现方式，请查看这篇 [指南](https://huggingface.co/docs/hub/collections) 

你可以直接在浏览器中管理集合，但本指南将重点介绍如何以编程方式进行管理。

## 获取集合

使用 `get_collection()` 来获取你的集合或任意公共集合。 你需要提供集合的 *slug* 才能检索到该集合。 slug 是基于集合标题和唯一 ID 的标识符。你可以在集合页面的 URL 中找到它。

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hfh_collection_slug.png"/>
</div>

让我们获取`"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`这个集合:

```py
>>> from huggingface_hub import get_collection
>>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
>>> collection
Collection(
  slug='TheBloke/recent-models-64f9a55bb3115b4f513ec026',
  title='Recent models',
  owner='TheBloke',
  items=[...],
  last_updated=datetime.datetime(2023, 10, 2, 22, 56, 48, 632000, tzinfo=datetime.timezone.utc),
  position=1,
  private=False,
  theme='green',
  upvotes=90,
  description="Models I've recently quantized. Please note that currently this list has to be updated manually, and therefore is not guaranteed to be up-to-date."
)
>>> collection.items[0]
CollectionItem(
  item_object_id='651446103cd773a050bf64c2',
  item_id='TheBloke/U-Amethyst-20B-AWQ',
  item_type='model',
  position=88,
  note=None
)
```

`get_collection()` 返回的 `Collection` 对象包含以下信息:
- 高级元数据: `slug`, `owner`, `title`, `description`等。
- 一个 `CollectionItem` 对象列表; 每个条目代表一个模型、数据集、Space 或论文。

所有集合条目（items）都保证具有：
- 唯一的 `item_object_id`: 这是集合条目在数据库中的唯一 ID
- 一个 `item_id`: Hub 上底层条目的 ID（模型、数据集、Space、论文）；此 ID 不一定是唯一的，仅当 `item_id` 与 `item_type` 成对出现时才唯一
- 一个 `item_type`: 如`model`, `dataset`, `Space`, `paper`
- 该条目在集合中的 `position`, 可通过后续操作 (参加下文的 `update_collection_item()`)来重新排序集合条目

此外，`note` 可选地附加在条目上。这对为某个条目添加额外信息（评论、博客文章链接等）很有帮助。如果条目没有备注，`note` 的值为 `None`。

除了这些基本属性之外，不同类型的条目可能会返回额外属性，如：`author`、`private`、`lastModified`、`gated`、`title`、`likes`、`upvotes` 等。这些属性不保证一定存在。

## 列出集合

我们也可以使用 `list_collections()`来检索集合，并通过一些参数进行过滤。让我们列出用户[`teknium`](https://huggingface.co/teknium)的所有集合：
```py
>>> from huggingface_hub import list_collections

>>> collections = list_collections(owner="teknium")
```

这将返回一个 Collection 对象的可迭代序列。我们可以遍历它们，比如打印每个集合的点赞数（upvotes）：

```py
>>> for collection in collections:
...   print("Number of upvotes:", collection.upvotes)
Number of upvotes: 1
Number of upvotes: 5
```

> [!WARNING]
> 当列出集合时，每个集合中返回的条目列表最多会被截断为 4 个。若要检索集合中的所有条目，你必须使用 `get_collection()`.

我们可以进行更高级的过滤。例如，让我们获取所有包含模型 [TheBloke/OpenHermes-2.5-Mistral-7B-GGUF](https://huggingface.co/TheBloke/OpenHermes-2.5-Mistral-7B-GGUF) 的集合，并按照趋势（trending）进行排序，同时将结果限制为 5 个。
```py
>>> collections = list_collections(item="models/TheBloke/OpenHermes-2.5-Mistral-7B-GGUF", sort="trending", limit=5):
>>> for collection in collections:
...   print(collection.slug)
teknium/quantized-models-6544690bb978e0b0f7328748
AmeerH/function-calling-65560a2565d7a6ef568527af
PostArchitekt/7bz-65479bb8c194936469697d8c
gnomealone/need-to-test-652007226c6ce4cdacf9c233
Crataco/favorite-7b-models-651944072b4fffcb41f8b568
```

`sort` 参数必须是 `"last_modified"`、`"trending"` 或 `"upvotes"` 之一。`item` 参数接受任意特定条目，例如：
* `"models/teknium/OpenHermes-2.5-Mistral-7B"`
* `"spaces/julien-c/open-gpt-rhyming-robot"`
* `"datasets/squad"`
* `"papers/2311.12983"`

详情请查看 `list_collections()` 的参考文档。

## 创建新集合

现在我们已经知道如何获取一个 `Collection`, 让我们自己创建一个吧！ 使用 `create_collection()`，传入一个标题和描述即可。 若要在组织（organization）名下创建集合，可以通过 `namespace="my-cool-org"` 参数指定。同样，你也可以通过传入 `private=True` 创建私有集合。

```py
>>> 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` 来引用该集合。

```py
>>> collection.slug
'owner/iccv-2023-15e23b46cb98efca45'
>>> collection.title
"ICCV 2023"
>>> collection.owner
"username"
>>> collection.url
'https://huggingface.co/collections/owner/iccv-2023-15e23b46cb98efca45'
```

## 管理集合中的条目

现在我们有了一个 `Collection`，接下来要添加条目并进行管理。

### 添加条目

使用 `add_collection_item()` 来向集合中添加条目（一次添加一个）。你只需要提供 `collection_slug`、`item_id` 和 `item_type`。可选参数 `note` 用于为该条目添加附加说明（最多 500 个字符）。

```py
>>> from huggingface_hub import create_collection, add_collection_item

>>> collection = create_collection(title="OS Week Highlights - Sept 18 - 24", namespace="osanseviero")
>>> collection.slug
"osanseviero/os-week-highlights-sept-18-24-650bfed7f795a59f491afb80"

>>> add_collection_item(collection.slug, item_id="coqui/xtts", item_type="space")
>>> add_collection_item(
...     collection.slug,
...     item_id="warp-ai/wuerstchen",
...     item_type="model",
...     note="Würstchen is a new fast and efficient high resolution text-to-image architecture and model"
... )
>>> add_collection_item(collection.slug, item_id="lmsys/lmsys-chat-1m", item_type="dataset")
>>> add_collection_item(collection.slug, item_id="warp-ai/wuerstchen", item_type="space") # same item_id, different item_type
```

如果一个条目已存在于集合中（相同的 `item_id` 和 `item_type`），将会引发 HTTP 409 错误。你可以通过设置 `exists_ok=True` 来忽略此错误。

### 为已存在条目添加备注

你可以使用 `update_collection_item()` 来为已存在条目添加或修改备注。让我们重用上面的示例：

```py
>>> from huggingface_hub import get_collection, update_collection_item

# Fetch collection with newly added items
>>> collection_slug = "osanseviero/os-week-highlights-sept-18-24-650bfed7f795a59f491afb80"
>>> collection = get_collection(collection_slug)

# Add note the `lmsys-chat-1m` dataset
>>> update_collection_item(
...     collection_slug=collection_slug,
...     item_object_id=collection.items[2].item_object_id,
...     note="This dataset contains one million real-world conversations with 25 state-of-the-art LLMs.",
... )
```

### 重新排序条目

集合中的条目是有序的。该顺序由每个条目的 `position` 属性决定。默认情况下，新添加的条目会被追加到集合末尾。你可以通过 `update_collection_item()` 来更新顺序。

再次使用之前的示例：

```py
>>> from huggingface_hub import get_collection, update_collection_item

# Fetch collection
>>> collection_slug = "osanseviero/os-week-highlights-sept-18-24-650bfed7f795a59f491afb80"
>>> collection = get_collection(collection_slug)

# Reorder to place the two `Wuerstchen` items together
>>> update_collection_item(
...     collection_slug=collection_slug,
...     item_object_id=collection.items[3].item_object_id,
...     position=2,
... )
```

### 删除条目

最后，你也可以使用 `delete_collection_item()` 来删除集合中的条目。

```py
>>> from huggingface_hub import get_collection, update_collection_item

# Fetch collection
>>> collection_slug = "osanseviero/os-week-highlights-sept-18-24-650bfed7f795a59f491afb80"
>>> collection = get_collection(collection_slug)

# Remove `coqui/xtts` Space from the list
>>> delete_collection_item(collection_slug=collection_slug, item_object_id=collection.items[0].item_object_id)
```

## 删除集合

可以使用 `delete_collection()` 来删除集合。

> [!WARNING]
> 此操作不可逆。删除的集合无法恢复。

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


<EditOnGithub source="https://github.com/huggingface/huggingface_hub/blob/main/docs/source/cn/guides/collections.md" />

### 操作指南
https://huggingface.co/docs/huggingface_hub/main/cn/guides/overview.md

# 操作指南

在本节中，您将找到帮助您实现特定目标的实用指南。
查看这些指南，了解如何使用 huggingface_hub 解决实际问题：

<div class="mt-10">
  <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-3 md:gap-y-4 md:gap-x-5">

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg"
       href="./repository">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">
        仓库
      </div><p class="text-gray-700">
        如何在 Hub 上创建仓库？如何配置它？如何与之交互？
      </p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg"
       href="./download">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">
        下载文件
      </div><p class="text-gray-700">
        如何从 Hub 下载文件？如何下载仓库？
      </p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg"
       href="./upload">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">
        上传文件
      </div><p class="text-gray-700">
        如何上传文件或文件夹？如何对 Hub 上的现有仓库进行更改？
      </p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg"
       href="./search">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">
        搜索
      </div><p class="text-gray-700">
        如何高效地搜索超过 200k+ 个公共模型、数据集和Space？
      </p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg"
       href="./hf_file_system">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">
        HfFileSystem
      </div><p class="text-gray-700">
        如何通过一个模仿 Python 文件接口的便捷接口与 Hub 交互？
      </p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg"
       href="./inference">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">
        推理
      </div><p class="text-gray-700">
        如何使用加速推理 API 进行预测？
      </p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg"
       href="./community">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">
        社区
      </div><p class="text-gray-700">
        如何与社区（讨论和拉取请求）互动？
      </p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg"
       href="./collections">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">
        集合
      </div><p class="text-gray-700">
        如何以编程方式构建集合？
      </p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg"
       href="./manage-cache">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">
        缓存
      </div><p class="text-gray-700">
        缓存系统如何工作？如何从中受益？
      </p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg"
       href="./model-cards">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">
        模型卡片
      </div><p class="text-gray-700">
        如何创建和分享模型卡片？
      </p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg"
       href="./manage-spaces">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">
        管理您的Space
      </div><p class="text-gray-700">
        如何管理您的Space的硬件和配置？
      </p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg"
       href="./integrations">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">
        集成库
      </div><p class="text-gray-700">
        将库集成到 Hub 中意味着什么？如何实现？
      </p>
    </a>

    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg"
       href="./webhooks_server">
      <div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">
        Webhooks 服务器
      </div><p class="text-gray-700">
        如何创建一个接收 Webhooks 的服务器并将其部署为一个Space？
      </p>
    </a>

  </div>
</div>


<EditOnGithub source="https://github.com/huggingface/huggingface_hub/blob/main/docs/source/cn/guides/overview.md" />

### 互动讨论与拉取请求（Pull Request）
https://huggingface.co/docs/huggingface_hub/main/cn/guides/community.md

# 互动讨论与拉取请求（Pull Request）

huggingface_hub 库提供了一个 Python 接口，用于与 Hub 上的拉取请求（Pull Request）和讨论互动。
访问 [相关的文档页面](https://huggingface.co/docs/hub/repositories-pull-requests-discussions)
，了解有关 Hub 上讨论和拉取请求（Pull Request）的更深入的介绍及其工作原理。

## 从 Hub 获取讨论和拉取请求（Pull Request）

`HfApi` 类允许您获取给定仓库中的讨论和拉取请求（Pull Request）：

```python
>>> from huggingface_hub import get_repo_discussions
>>> for discussion in get_repo_discussions(repo_id="bigscience/bloom"):
...     print(f"{discussion.num} - {discussion.title}, pr: {discussion.is_pull_request}")

# 11 - Add Flax weights, pr: True
# 10 - Update README.md, pr: True
# 9 - Training languages in the model card, pr: True
# 8 - Update tokenizer_config.json, pr: True
# 7 - Slurm training script, pr: False
[...]
```

`HfApi.get_repo_discussions` 支持按作者、类型（拉取请求或讨论）和状态（`open` 或 `closed`）进行过滤：

```python
>>> from huggingface_hub import get_repo_discussions
>>> for discussion in get_repo_discussions(
...    repo_id="bigscience/bloom",
...    author="ArthurZ",
...    discussion_type="pull_request",
...    discussion_status="open",
... ):
...     print(f"{discussion.num} - {discussion.title} by {discussion.author}, pr: {discussion.is_pull_request}")

# 19 - Add Flax weights by ArthurZ, pr: True
```

`HfApi.get_repo_discussions` 返回一个 [生成器](https://docs.python.org/3.7/howto/functional.html#generators) 生成
`Discussion` 对象。 要获取所有讨论并存储为列表，可以运行：

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

`HfApi.get_repo_discussions()` 返回的 `Discussion` 对象提供讨论或拉取请求（Pull Request）的高级概览。您还可以使用 `HfApi.get_discussion_details()` 获取更详细的信息：

```python
>>> from huggingface_hub import get_discussion_details

>>> get_discussion_details(
...     repo_id="bigscience/bloom-1b3",
...     discussion_num=2
... )
DiscussionWithDetails(
    num=2,
    author='cakiki',
    title='Update VRAM memory for the V100s',
    status='open',
    is_pull_request=True,
    events=[
        DiscussionComment(type='comment', author='cakiki', ...),
        DiscussionCommit(type='commit', author='cakiki', summary='Update VRAM memory for the V100s', oid='1256f9d9a33fa8887e1c1bf0e09b4713da96773a', ...),
    ],
    conflicting_files=[],
    target_branch='refs/heads/main',
    merge_commit_oid=None,
    diff='diff --git a/README.md b/README.md\nindex a6ae3b9294edf8d0eda0d67c7780a10241242a7e..3a1814f212bc3f0d3cc8f74bdbd316de4ae7b9e3 100644\n--- a/README.md\n+++ b/README.md\n@@ -132,7 +132,7 [...]',
)
```

`HfApi.get_discussion_details()` 返回一个 `DiscussionWithDetails` 对象，它是 `Discussion` 的子类，包含有关讨论或拉取请求（Pull Request）的更详细信息。详细信息包括所有评论、状态更改以及讨论的重命名信息，可通过 `DiscussionWithDetails.events` 获取。

如果是拉取请求（Pull Request），您可以通过 `DiscussionWithDetails.diff` 获取原始的 git diff。拉取请求（Pull Request）的所有提交都列在 `DiscussionWithDetails.events` 中。


## 以编程方式创建和编辑讨论或拉取请求

`HfApi` 类还提供了创建和编辑讨论及拉取请求（Pull Request）的方法。
您需要一个 [访问令牌](https://huggingface.co/docs/hub/security-tokens) 来创建和编辑讨论或拉取请求（Pull Request）。

在 Hub 上对 repo 提出修改建议的最简单方法是使用 `create_commit()` API：只需将 `create_pr` 参数设置为 `True` 。此参数也适用于其他封装了 `create_commit()` 的方法：

    * `upload_file()`
    * `upload_folder()`
    * `delete_file()`
    * `delete_folder()`
    * `metadata_update()`

```python
>>> from huggingface_hub import metadata_update

>>> metadata_update(
...     repo_id="username/repo_name",
...     metadata={"tags": ["computer-vision", "awesome-model"]},
...     create_pr=True,
... )
```

您还可以使用 `HfApi.create_discussion()`（或 `HfApi.create_pull_request()`）在仓库上创建讨论（或拉取请求）。以这种方式打开拉取请求在您需要本地处理更改时很有用。以这种方式打开的拉取请求将处于“draft”模式。

```python
>>> from huggingface_hub import create_discussion, create_pull_request

>>> create_discussion(
...     repo_id="username/repo-name",
...     title="Hi from the huggingface_hub library!",
...     token="<insert your access token here>",
... )
DiscussionWithDetails(...)

>>> create_pull_request(
...     repo_id="username/repo-name",
...     title="Hi from the huggingface_hub library!",
...     token="<insert your access token here>",
... )
DiscussionWithDetails(..., is_pull_request=True)
```

您可以使用 `HfApi` 类来方便地管理拉取请求和讨论。例如：

    * `comment_discussion()` 添加评论
    * `edit_discussion_comment()` 编辑评论
    * `rename_discussion()` 重命名讨论或拉取请求
    * `change_discussion_status()` 打开或关闭讨论/拉取请求
    * `merge_pull_request()` 合并拉取请求


请访问 `HfApi` 文档页面，获取所有可用方法的完整参考

## 推送更改到拉取请求（Pull Request）

*敬请期待！*

## 参见

有关更详细的参考，请访问 [讨论和拉取请求](../package_reference/community) 和 [hf_api](../package_reference/hf_api) 文档页面。


<EditOnGithub source="https://github.com/huggingface/huggingface_hub/blob/main/docs/source/cn/guides/community.md" />

### 通过文件系统 API 与 Hub 交互
https://huggingface.co/docs/huggingface_hub/main/cn/guides/hf_file_system.md

# 通过文件系统 API 与 Hub 交互

除了 `HfApi`，`huggingface_hub` 库还提供了 `HfFileSystem`，这是一个符合 [fsspec](https://filesystem-spec.readthedocs.io/en/latest/) 规范的 Python 文件接口，用于与 Hugging Face Hub 交互。`HfFileSystem` 基于 `HfApi` 构建，提供了典型的文件系统操作，如 `cp`、`mv`、`ls`、`du`、`glob`、`get_file` 和 `put_file`。

> [!WARNING]
> `HfFileSystem` 提供了 fsspec 兼容性，这对于需要它的库（例如，直接使用 `pandas` 读取 Hugging Face 数据集）非常有用。然而，由于这种兼容性层，会引入额外的开销。为了更好的性能和可靠性，建议尽可能使用 `HfApi` 方法。

## 使用方法

```python
>>> from huggingface_hub import HfFileSystem
>>> fs = HfFileSystem()

>>> # 列出目录中的所有文件
>>> fs.ls("datasets/my-username/my-dataset-repo/data", detail=False)
['datasets/my-username/my-dataset-repo/data/train.csv', 'datasets/my-username/my-dataset-repo/data/test.csv']

>>> # 列出仓库中的所有 ".csv" 文件
>>> fs.glob("datasets/my-username/my-dataset-repo/**/*.csv")
['datasets/my-username/my-dataset-repo/data/train.csv', 'datasets/my-username/my-dataset-repo/data/test.csv']

>>> # 读取远程文件
>>> with fs.open("datasets/my-username/my-dataset-repo/data/train.csv", "r") as f:
...     train_data = f.readlines()

>>> # 远程文件内容读取为字符串
>>> train_data = fs.read_text("datasets/my-username/my-dataset-repo/data/train.csv", revision="dev")

>>> # 写入远程文件
>>> with fs.open("datasets/my-username/my-dataset-repo/data/validation.csv", "w") as f:
...     f.write("text,label")
...     f.write("Fantastic movie!,good")
```

可以传递可选的 `revision` 参数，以从特定提交（如分支、标签名或提交哈希）运行操作。

与 Python 内置的 `open` 不同，`fsspec` 的 `open` 默认是二进制模式 `"rb"`。这意味着您必须明确设置模式为 `"r"` 以读取文本模式，或 `"w"` 以写入文本模式。目前不支持追加到文件（模式 `"a"` 和 `"ab"`）

## 集成

`HfFileSystem` 可以与任何集成了 `fsspec` 的库一起使用，前提是 URL 遵循以下格式：

```
hf://[<repo_type_prefix>]<repo_id>[@<revision>]/<path/in/repo>
```

<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/huggingface_hub/hf_urls.png"/>
</div>

对于数据集，`repo_type_prefix` 为 `datasets/`，对于Space，`repo_type_prefix`为 `spaces/`，模型不需要在 URL 中使用这样的前缀。

以下是一些 `HfFileSystem` 简化与 Hub 交互的有趣集成：

* 从 Hub 仓库读取/写入 [Pandas](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#reading-writing-remote-files) DataFrame ：

  ```python
  >>> import pandas as pd

  >>> # 将远程 CSV 文件读取到 DataFrame
  >>> df = pd.read_csv("hf://datasets/my-username/my-dataset-repo/train.csv")

  >>> # 将 DataFrame 写入远程 CSV 文件
  >>> df.to_csv("hf://datasets/my-username/my-dataset-repo/test.csv")
  ```

同样的工作流程也适用于 [Dask](https://docs.dask.org/en/stable/how-to/connect-to-remote-data.html) 和 [Polars](https://pola-rs.github.io/polars/py-polars/html/reference/io.html) DataFrames.

* 使用 [DuckDB](https://duckdb.org/docs/guides/python/filesystems) 查询(远程)Hub文件：

  ```python
  >>> from huggingface_hub import HfFileSystem
  >>> import duckdb

  >>> fs = HfFileSystem()
  >>> duckdb.register_filesystem(fs)
  >>> # 查询远程文件并将结果返回为 DataFrame
  >>> fs_query_file = "hf://datasets/my-username/my-dataset-repo/data_dir/data.parquet"
  >>> df = duckdb.query(f"SELECT * FROM '{fs_query_file}' LIMIT 10").df()
  ```

* 使用 [Zarr](https://zarr.readthedocs.io/en/stable/tutorial.html#io-with-fsspec) 将 Hub 作为数组存储：

  ```python
  >>> import numpy as np
  >>> import zarr

  >>> embeddings = np.random.randn(50000, 1000).astype("float32")

  >>> # 将数组写入仓库
  >>> with zarr.open_group("hf://my-username/my-model-repo/array-store", mode="w") as root:
  ...    foo = root.create_group("embeddings")
  ...    foobar = foo.zeros('experiment_0', shape=(50000, 1000), chunks=(10000, 1000), dtype='f4')
  ...    foobar[:] = embeddings

  >>> # 从仓库读取数组
  >>> with zarr.open_group("hf://my-username/my-model-repo/array-store", mode="r") as root:
  ...    first_row = root["embeddings/experiment_0"][0]
  ```

## 认证

在许多情况下，您必须登录 Hugging Face 账户才能与 Hub 交互。请参阅文档的[认证](../quick-start#authentication) 部分，了解有关 Hub 上认证方法的更多信息。

也可以通过将您的 token 作为参数传递给 `HfFileSystem` 以编程方式登录：

```python
>>> from huggingface_hub import HfFileSystem
>>> fs = HfFileSystem(token=token)
```

如果您以这种方式登录，请注意在共享源代码时不要意外泄露令牌！ 


<EditOnGithub source="https://github.com/huggingface/huggingface_hub/blob/main/docs/source/cn/guides/hf_file_system.md" />

### 搜索 Hub
https://huggingface.co/docs/huggingface_hub/main/cn/guides/search.md

# 搜索 Hub

在本教程中，您将学习如何使用 `huggingface_hub` 在 Hub 上搜索模型、数据集和Spaces。

## 如何列出仓库？

`huggingface_hub`库包括一个 HTTP 客户端 `HfApi`，用于与 Hub 交互。 除此之外，它还可以列出存储在 Hub 上的模型、数据集和Spaces：

```py
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> models = api.list_models()
```

`list_models()` 返回一个迭代器，包含存储在 Hub 上的模型。

同样，您可以使用 `list_datasets()` 列出数据集，使用 `list_spaces()` 列出 Spaces。

## 如何过滤仓库？

列出仓库是一个好开始，但现在您可能希望对搜索结果进行过滤。
列出时，可以使用多个属性来过滤结果，例如：
- `filter`
- `author`
- `search`
- ...

让我们看一个示例，获取所有在 Hub 上进行图像分类的模型，这些模型已在 imagenet 数据集上训练，并使用 PyTorch 运行。

```py
models = hf_api.list_models(
	task="image-classification",
	library="pytorch",
	trained_dataset="imagenet",
)
```

在过滤时，您还可以对模型进行排序，并仅获取前几个结果。例如，以下示例获取了 Hub 上下载量最多的前 5 个数据集：

```py
>>> list(list_datasets(sort="downloads", direction=-1, limit=5))
[DatasetInfo(
	id='argilla/databricks-dolly-15k-curated-en',
	author='argilla',
	sha='4dcd1dedbe148307a833c931b21ca456a1fc4281',
	last_modified=datetime.datetime(2023, 10, 2, 12, 32, 53, tzinfo=datetime.timezone.utc),
	private=False,
	downloads=8889377,
	(...)
```



如果您想要在Hub上探索可用的过滤器, 请在浏览器中访问 [models](https://huggingface.co/models) 和 [datasets](https://huggingface.co/datasets) 页面
，尝试不同的参数并查看URL中的值。


<EditOnGithub source="https://github.com/huggingface/huggingface_hub/blob/main/docs/source/cn/guides/search.md" />
