# Webhook 指南：设置一个自动系统，在数据集更改时重新训练模型

本指南将引导您使用 HF Datasets、Webhooks、Spaces 和 AutoTrain 在 Hugging Face 平台上搭建自动训练流水线。

我们将构建一个 Webhook，用于监听图像分类数据集的变更，并触发使用 [AutoTrain](https://huggingface.co/autotrain) 对 [microsoft/resnet-50](https://huggingface.co/microsoft/resnet-50) 进行微调。

## 先决条件：将您的数据集上传到 Hub

为了便于示例，我们将使用一个[简单的图像分类数据集](https://huggingface.co/datasets/huggingface-projects/auto-retrain-input-dataset)。有关将数据上传到 Hub 的更多信息，请参见[此处](https://huggingface.co/docs/datasets/upload_dataset)。

![dataset](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/webhooks-guides/002-auto-retrain/dataset.png)

## 创建 Webhook 以响应数据集的更改

首先，让我们从您的[设置]( https://huggingface.co/settings/webhooks)中创建一个 Webhook。

- 选择您的数据集作为目标仓库。在本示例中，我们将以 [huggingface-projects/input-dataset](https://huggingface.co/datasets/huggingface-projects/input-dataset) 为目标。
- 目前可以先填入一个占位的 Webhook URL。定义好 Webhook 后，你就可以查看将发送到该地址的事件。此外，你还可以重放这些事件，这在调试时会非常有用！
- 输入一个密钥以增强安全性。
- 订阅“Repo update”事件，因为我们希望响应数据变更

您的 Webhook 将如下所示：

![webhook-creation](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/webhooks-guides/002-auto-retrain/webhook-creation.png)

## 创建一个 Space 以响应你的 Webhook

现在我们需要一种方式来响应你的 Webhook 事件。一种简单的方法是使用 [Space](https://huggingface.co/docs/hub/spaces-overview)！

您可以在[此处](https://huggingface.co/spaces/huggingface-projects/auto-retrain/tree/main)找到一个示例 Space。

此 Space 使用 Docker、Python、[FastAPI](https://fastapi.tiangolo.com/) 和 [uvicorn](https://uvicorn.dev) 来运行一个简单的 HTTP 服务器。有关 Docker Spaces 的更多信息，请参见[此处](https://huggingface.co/docs/hub/spaces-sdks-docker)。

入口点是 [src/main.py](https://huggingface.co/spaces/huggingface-projects/auto-retrain/blob/main/src/main.py)。让我们逐步查看此文件，并详细说明其功能：

1. 它会启动一个 FastAPI 应用，用于监听 `/webhook` 上的 HTTP `POST` 请求：

```python
from fastapi import FastAPI

# [...]
@app.post("/webhook")
async def post_webhook(
	# ...
):

# ...
```

2.  2. 此路由会检查 `X-Webhook-Secret` 请求头是否存在，且其值与您 Webhook 设置中配置的值一致。`WEBHOOK_SECRET` 密钥必须在 Space 的设置中配置，并且与 Webhook 中设置的密钥相同。

```python
# [...]

WEBHOOK_SECRET = os.getenv("WEBHOOK_SECRET")

# [...]

@app.post("/webhook")
async def post_webhook(
	# [...]
	x_webhook_secret:  Optional[str] = Header(default=None),
	# ^ checks for the X-Webhook-Secret HTTP header
):
	if x_webhook_secret is None:
		raise HTTPException(401)
	if x_webhook_secret != WEBHOOK_SECRET:
		raise HTTPException(403)
	# [...]
```

3. 事件的负载以 JSON 编码。在这里，我们将使用 pydantic 模型来解析事件负载。我们还指定了仅在以下情况下运行我们的 Webhook：
- 该事件涉及输入数据集
- 该事件是仓库内容的更新，即存在新的提交

```python
# defined in src/models.py
class WebhookPayloadEvent(BaseModel):
	action: Literal["create", "update", "delete", "move"]
	scope: str

class WebhookPayloadRepo(BaseModel):
	type: Literal["dataset", "model", "space"]
	name: str
	id: str
	private: bool
	headSha: str

class WebhookPayload(BaseModel):
	event: WebhookPayloadEvent
	repo: WebhookPayloadRepo

# [...]

@app.post("/webhook")
async def post_webhook(
	# [...]
	payload: WebhookPayload,
	# ^ Pydantic model defining the payload format
):
	# [...]
	if not (
		payload.event.action == "update"
		and payload.event.scope.startswith("repo.content")
		and payload.repo.name == config.input_dataset
		and payload.repo.type == "dataset"
	):
		# no-op if the payload does not match our expectations
		return {"processed": False}
	#[...]
```

4. 如果有效载荷合法，下一步是在 AutoTrain 上创建一个项目，安排对输入模型（在我们的示例中为 `microsoft/resnet-50`）在输入数据集上进行微调，并在完成后于该数据集上创建一条讨论！

```python
def schedule_retrain(payload: WebhookPayload):
	# Create the autotrain project
	try:
		project = AutoTrain.create_project(payload)
		AutoTrain.add_data(project_id=project["id"])
		AutoTrain.start_processing(project_id=project["id"])
	except requests.HTTPError as err:
		print("ERROR while requesting AutoTrain API:")
		print(f"  code: {err.response.status_code}")
		print(f"  {err.response.json()}")
		raise
	# Notify in the community tab
	notify_success(project["id"])
```

访问注释中的链接以查看训练成本估算，然后开始微调模型！

![community tab notification](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/webhooks-guides/002-auto-retrain/notification.png)

在此示例中，我们使用 Hugging Face AutoTrain 快速微调了模型，但您当然也可以接入自己的训练基础设施！

您可以随意将该 Space 复制到您的个人命名空间中进行尝试。您需要提供两个密钥：
- `WEBHOOK_SECRET`：来自您的 Webhook 的密钥。
- `HF_ACCESS_TOKEN`：一个具有 `write` 权限的用户访问令牌。您可以 [从您的设置中](https://huggingface.co/settings/tokens) 创建一个。

您还需要调整 [`config.json` 文件](https://huggingface.co/spaces/huggingface-projects/auto-retrain/blob/main/config.json)，以使用您选择的数据集和模型：

```json
{
	"target_namespace": "the namespace where the trained model should end up",
	"input_dataset": "the dataset on which the model will be trained",
	"input_model": "the base model to re-train",
	"autotrain_project_prefix": "A prefix for the AutoTrain project"
}
```

## 配置您的 Webhook 以将事件发送到您的 Space

最后，你需要配置 webhook，使其向你的 Space 发送 POST 请求。

首先，让我们从上下文菜单中获取我们 Space 的“直接 URL”。点击“嵌入此 Space”，然后复制“直接 URL”。

![embed this Space](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/webhooks-guides/002-auto-retrain/duplicate-space.png)

![direct URL](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/webhooks-guides/002-auto-retrain/direct-url.png)

更新您的 Webhook，以向该 URL 发送请求：

![webhook settings](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/webhooks-guides/002-auto-retrain/update-webhook.png)

就是这样！现在，对输入数据集的每次提交都会触发使用 AutoTrain 对 ResNet-50 进行微调 🎉

