# 创建和管理仓库

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#authentication)。在本指南的其余部分中，我们将假设您的机器已登录。

## 列出你的仓库

您可以使用 [list_user_repos()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.list_user_repos) 列出您的账户或组织的所有仓库（模型、数据集、空间和存储桶）。结果包含存储信息，并按存储用量排序。

```py
>>> from huggingface_hub import list_user_repos

# List repos for the authenticated user
>>> repos = list(list_user_repos())
>>> for repo in repos[:3]:
...     print(f"{repo.id} ({repo.type}) - {repo.storage} bytes")
username/my-model (model) - 4828692480 bytes
username/my-dataset (dataset) - 598427559 bytes
username/my-space (space) - 120620146 bytes

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

或通过 CLI（默认显示 30 个仓库，使用 `--limit 0` 可列出所有仓库）：

```bash
>>> hf repos ls
>>> hf repos ls --namespace my-org --type model
>>> hf repos ls --limit 0 --format json | jq '.[].id'
```

## 创建和删除仓库

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

### 创建仓库

使用 [create_repo()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.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'
```

或通过 CLI：

```bash
>>> hf repos create lysandre/test-model
Successfully created lysandre/test-model on the Hub.
Your repo is now available at https://huggingface.co/lysandre/test-model
```

默认情况下，[create_repo()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.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'
```

或通过 CLI：

```bash
>>> hf repos create lysandre/test-dataset --repo-type dataset
```

创建仓库时，您可以通过`visibility`参数设置仓库的可见性：

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

或通过 CLI：

```bash
>>> hf repos create lysandre/test-private --private
```

如果想在稍后更改仓库的可见性，可以使用 [update_repo_settings()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.update_repo_settings) 函数。

> [!TIP]
> 如果您所在组织使用的是 Enterprise 计划，您可以通过将 `resource_group_id` 作为参数传递给 [create_repo()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.create_repo) 来在特定的资源组中创建仓库。资源组是一项安全功能，用于控制组织中的哪些成员可以访问特定资源。您可以通过从 Hub 上组织设置页面的 URL 中复制资源组 ID 来获取它（例如 `"https://huggingface.co/organizations/huggingface/settings/resource-groups/66670e5163145ca562cb1988"` => `"66670e5163145ca562cb1988"`）。有关资源组的更多详细信息，请参阅此[指南](https://huggingface.co/docs/hub/en/security-resource-groups)。

你还可以通过将 `region` 作为参数传入，在特定的云区域中创建仓库：

```py
>>> from huggingface_hub import create_repo
>>> create_repo("lysandre/test-model", region="us")
```

### 删除一个仓库

使用 [delete_repo()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.delete_repo) 删除仓库。请确保您确实想要删除该仓库，因为此操作不可逆！

指定要删除的仓库的 `repo_id`：

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

传入 `missing_ok=True` 以在仓库不存在时静默忽略该调用：

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

或通过 CLI：

```bash
>>> hf repos delete lysandre/my-corrupted-dataset --repo-type dataset
```

### 复制一个仓库

在某些情况下，您可能希望复制他人的仓库以适配您的使用场景。您可以使用 [duplicate_repo()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.duplicate_repo) 方法来实现这一点。该方法会复制整个仓库，并保留完整的 git 历史记录。此功能适用于模型、数据集和 Spaces。对于 Spaces，您仍需自行配置相关设置（硬件、休眠时间、存储、变量和密钥）。有关更多详细信息，请参阅我们的 [Manage your Space](./manage-spaces) 指南。

```py
>>> from huggingface_hub import duplicate_repo

# Duplicate a Space
>>> duplicate_repo("multimodalart/dreambooth-training", repo_type="space", private=False)
RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)

# Duplicate a dataset
>>> duplicate_repo("openai/gdpval", repo_type="dataset")
RepoUrl('https://huggingface.co/datasets/nateraw/gdpval',...)
```

与 [create_repo()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.create_repo) 类似，[duplicate_repo()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.duplicate_repo) 接受 `resource_group_id` 参数，以便在您的企业组织的资源组内直接创建副本（在 `hf repos duplicate` 中使用 `--resource-group-id`）。

Git 历史记录会立即复制，但 [duplicate_repo()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.duplicate_repo) 返回后，LFS/Xet 文件可能仍在后台继续复制。在复制完成之前，从新仓库下载这些文件可能会失败。请检查返回值中的 `files_copy_pending` 以了解复制是否仍在进行中：

```py
>>> from huggingface_hub import duplicate_repo
>>> repo_url = duplicate_repo("openai/gdpval", repo_type="dataset")
>>> repo_url.files_copy_pending
True
```

## 搜索 Spaces

Hub 提供了一个用于发现 Spaces 的语义搜索 API。您可以使用自然语言查询，通过 [search_spaces()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.search_spaces) 进行搜索：

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

有关更多详细信息和筛选选项，请参阅[管理您的 Spaces](./manage-spaces#search-for-spaces)指南。

## 上传和下载文件

现在，您已经创建了仓库，接下来您希望将更改推送到该仓库，并从中下载文件。

这两个主题值得拥有各自的指南。请参阅[上传](./upload)和[下载](./download)指南，以了解如何使用您的仓库。

## 复制文件

使用 [copy_files()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.copy_files) 可以将已托管在 Hub 上的文件从一个仓库复制到另一个仓库（甚至在同一仓库内），而无需下载并重新上传。该功能支持单个文件和整个文件夹，并且通过 Xet 或 LFS 跟踪的文件会按哈希值在服务端进行复制。

```py
>>> from huggingface_hub import copy_files

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

# Copy an entire folder (a trailing "/" copies the folder *contents*, rsync-style)
>>> copy_files(
...     "hf://datasets/username/my-dataset/data/",
...     "hf://datasets/username/my-dataset-copy/data/",
... )
```

或者通过 CLI，使用统一的 `hf cp` 命令（也可用 `hf repos cp`）：

```bash
# Copy a single file between repositories
>>> hf cp hf://username/source-model/config.json hf://username/dest-model/config.json

# Copy a file from a repo to your local machine
>>> hf repos cp hf://username/my-model/config.json ./config.json

# Upload a local file to a repository
>>> hf repos cp ./model.safetensors hf://username/my-model/model.safetensors
```

> [!TIP]
> `copy_files` (and `hf cp`) can also copy files from a repository to a [Bucket](./buckets). Copying *from* a bucket *to* a repository is not supported. See the [Buckets](./buckets) guide for more details.

> [!WARNING]
> 服务器端副本仅在同一个[存储区域](https://huggingface.co/docs/hub/storage-regions)内有效。

## 分支和标签

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

### 创建分支和标签

您可以使用 [create_branch()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.create_branch) 和 [create_tag()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.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_tag("bigcode/the-stack", repo_type="dataset", revision="v0.1-release", tag="v0.1.1", tag_message="Bump release version.")
```

或通过 CLI：

```bash
>>> hf repos branch create Matthijs/speecht5-tts-demo handle-dog-speaker --repo-type space
>>> hf repos tag create bigcode/the-stack v0.1.1 --repo-type dataset --revision v0.1-release -m "Bump release version."
```

您可以以相同的方式使用 [delete_branch()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.delete_branch) 和 [delete_tag()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.delete_tag) 函数来删除分支或标签，或者在 CLI 中分别使用 `hf repos branch delete` 和 `hf repos tag delete`。

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

您还可以通过 [list_repo_refs()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.list_repo_refs) 列出仓库中现有的 git refs：

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

或通过 CLI：

```bash
>>> hf repos settings lysandre/test-private --private true
```

### 设置受控访问

为了更精细地控制仓库的使用方式，Hub 允许仓库作者为其仓库启用**访问请求**。启用后，用户必须同意与仓库作者共享其联系信息（用户名和电子邮件地址），才能访问文件。启用了访问请求的仓库被称为**受控仓库**。

您可以使用 [update_repo_settings()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.update_repo_settings) 将仓库设置为受限访问：

```py
>>> from huggingface_hub import HfApi

>>> api = HfApi()
>>> api.update_repo_settings(repo_id=repo_id, gated="auto")  # Set automatic gating for a model
```

或通过 CLI：

```bash
>>> hf repos settings lysandre/test-private --gated auto
```

### 重命名您的仓库

您可以在 Hub 上使用 [move_repo()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.move_repo) 重命名您的仓库。使用此方法，您还可以将仓库从用户移至组织。执行此操作时，有一些 [限制](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")
```

或通过 CLI：

```bash
>>> hf repos move Wauplin/cool-model huggingface/cool-model
```

## 内核仓库

Hub 支持 `"kernel"` 仓库类型，用于托管计算内核。这**并非**一种完全兼容的仓库类型。目前仅有一组有限的方法经过测试并得到官方支持：

- [kernel_info()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.kernel_info)
- [hf_hub_download()](/docs/huggingface_hub/v2.4.0/zh/package_reference/file_download#huggingface_hub.hf_hub_download)
- [snapshot_download()](/docs/huggingface_hub/v2.4.0/zh/package_reference/file_download#huggingface_hub.snapshot_download)
- [list_repo_refs()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.list_repo_refs)
- [list_repo_files()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.list_repo_files)
- [list_repo_tree()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.list_repo_tree)

请注意，[create_repo()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.create_repo) 和 [delete_repo()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.delete_repo) 也兼容，但仅限于 Hub 上允许使用的一小部分用户和组织。

如需构建、发布和使用内核仓库，请改用专用的 [`kernels`](https://github.com/huggingface/kernels) 包。有关更多详细信息，请参阅 [Kernels 文档](https://huggingface.co/docs/kernels/index)。

