Hub Python 庫文件

Webhooks

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

Webhooks

Webhooks 是 MLOps 相關功能的基礎。它們允許您監聽特定倉庫或您感興趣的所有使用者/組織所屬的所有倉庫的新更改。本指南將首先解釋如何以程式設計方式管理 Webhooks。然後我們將看到如何利用 huggingface_hub 建立一個監聽 Webhooks 的伺服器並將其部署到 Space。

本指南假設您熟悉 Huggingface Hub 上 Webhooks 的概念。要了解有關 Webhooks 本身的更多資訊,您應該首先閱讀這篇指南

管理 Webhooks

huggingface_hub 允許您以程式設計方式管理您的 Webhooks。您可以列出現有的 Webhooks,建立新的,以及更新、啟用、停用或刪除它們。本節將指導您使用 Hugging Face Hub 的 API 函式完成這些操作。

建立 Webhook

要建立新的 Webhook,請使用 create_webhook() 並指定應傳送有效負載的 URL、應監視的事件,以及可選地設定域和金鑰以確保安全。

from huggingface_hub import create_webhook

# Example: Creating a webhook
webhook = create_webhook(
    url="https://webhook.site/your-custom-url",
    watched=[{"type": "user", "name": "your-username"}, {"type": "org", "name": "your-org-name"}],
    domains=["repo", "discussion"],
    secret="your-secret"
)

列出 Webhook

要檢視您配置的所有 Webhook,可以使用 list_webhooks() 列出它們。這對於檢視它們的 ID、URL 和狀態非常有用。

from huggingface_hub import list_webhooks

# Example: Listing all webhooks
webhooks = list_webhooks()
for webhook in webhooks:
    print(webhook)

更新 Webhook

如果您需要更改現有 Webhook 的配置,例如 URL 或其監視的事件,您可以使用 update_webhook() 進行更新。

from huggingface_hub import update_webhook

# Example: Updating a webhook
updated_webhook = update_webhook(
    webhook_id="your-webhook-id",
    url="https://new.webhook.site/url",
    watched=[{"type": "user", "name": "new-username"}],
    domains=["repo"]
)

啟用和停用 Webhook

您可能希望暫時停用 Webhook 而不刪除它。這可以使用 disable_webhook() 完成,並且之後可以使用 enable_webhook() 重新啟用 Webhook。

from huggingface_hub import enable_webhook, disable_webhook

# Example: Enabling a webhook
enabled_webhook = enable_webhook("your-webhook-id")
print("Enabled:", enabled_webhook)

# Example: Disabling a webhook
disabled_webhook = disable_webhook("your-webhook-id")
print("Disabled:", disabled_webhook)

刪除 Webhook

當不再需要 Webhook 時,可以使用 delete_webhook() 永久刪除它。

from huggingface_hub import delete_webhook

# Example: Deleting a webhook
delete_webhook("your-webhook-id")

Webhooks 伺服器

本指南部分將使用的基類是 WebhooksServer()。它是一個用於輕鬆配置能夠從 Huggingface Hub 接收 Webhooks 的伺服器的類。該伺服器基於 Gradio 應用程式。它有一個 UI 來顯示您或您的使用者的說明,以及一個 API 來監聽 Webhooks。

要檢視 Webhook 伺服器的執行示例,請檢視 Spaces CI Bot。它是一個在 Space 上開啟 PR 時啟動臨時環境的 Space。

這是一個實驗性功能。這意味著我們仍在努力改進 API。未來可能會在未經事先通知的情況下引入重大更改。請確保在您的需求中鎖定 huggingface_hub 的版本。

建立端點

實現 Webhook 端點就像裝飾函式一樣簡單。讓我們看一個解釋主要概念的第一個例子

# app.py
from huggingface_hub import webhook_endpoint, WebhookPayload

@webhook_endpoint
async def trigger_training(payload: WebhookPayload) -> None:
    if payload.repo.type == "dataset" and payload.event.action == "update":
        # Trigger a training job if a dataset is updated
        ...

將此程式碼片段儲存到名為 'app.py' 的檔案中,並使用 'python app.py' 執行它。您應該會看到類似以下訊息

Webhook secret is not defined. This means your webhook endpoints will be open to everyone.
To add a secret, set `WEBHOOK_SECRET` as environment variable or pass it at initialization:
        `app = WebhooksServer(webhook_secret='my_secret', ...)`
For more details about webhook secrets, please refer to https://huggingface.co/docs/hub/webhooks#webhook-secret.
Running on local URL:  http://127.0.0.1:7860
Running on public URL: https://1fadb0f52d8bf825fc.gradio.live

This share link expires in 72 hours. For free permanent hosting and GPU upgrades (NEW!), check out Spaces: https://huggingface.co/spaces

Webhooks are correctly setup and ready to use:
  - POST https://1fadb0f52d8bf825fc.gradio.live/webhooks/trigger_training
Go to https://huggingface.co/settings/webhooks to setup your webhooks.

幹得好!您剛剛啟動了一個 Webhook 伺服器!讓我們詳細分解一下發生了什麼

  1. 透過使用 webhook_endpoint() 裝飾函式,已在後臺建立了一個 WebhooksServer() 物件。如您所見,此伺服器是一個在 http://127.0.0.1:7860 執行的 Gradio 應用程式。如果您在瀏覽器中開啟此 URL,您將看到一個包含已註冊 Webhook 說明的登陸頁面。
  2. Gradio 應用程式底層是一個 FastAPI 伺服器。它已添加了一個新的 POST 路由 /webhooks/trigger_training。這是將監聽 Webhook 並在觸發時執行 trigger_training 函式的路由。FastAPI 將自動解析有效負載並將其作為 WebhookPayload 物件傳遞給函式。這是一個包含觸發 Webhook 的事件所有資訊的 pydantic 物件。
  3. Gradio 應用程式還打開了一個隧道來接收來自網際網路的請求。這是有趣的部分:您可以在 https://huggingface.co/settings/webhooks 配置一個指向您本地機器的 Webhook。這對於除錯您的 Webhook 伺服器和在部署到 Space 之前快速迭代非常有用。
  4. 最後,日誌還告訴您您的伺服器當前未受金鑰保護。這對於本地除錯不是問題,但以後需要牢記。

預設情況下,伺服器在指令碼末尾啟動。如果您在 notebook 中執行它,可以透過呼叫 decorated_function.run() 手動啟動伺服器。由於使用唯一的伺服器,即使您有多個端點,也只需啟動伺服器一次。

配置 Webhook

現在您已經運行了一個 Webhook 伺服器,您需要配置一個 Webhook 以開始接收訊息。轉到 https://huggingface.co/settings/webhooks,點選“新增新 Webhook”並配置您的 Webhook。設定您要監視的目標儲存庫和 Webhook URL,這裡是 https://1fadb0f52d8bf825fc.gradio.live/webhooks/trigger_training

就這樣!現在您可以透過更新目標儲存庫(例如,推送提交)來觸發該 Webhook。檢查 Webhook 的“活動”選項卡以檢視已觸發的事件。現在您已經設定了一個可用的環境,您可以測試並快速迭代。如果您修改程式碼並重新啟動伺服器,您的公共 URL 可能會更改。如果需要,請務必更新 Hub 上的 Webhook 配置。

部署到 Space

現在您已經有了一個可用的 Webhook 伺服器,目標是將其部署到 Space。轉到 https://huggingface.co/new-space 建立一個 Space。給它一個名稱,選擇 Gradio SDK,然後點選“建立 Space”。將您的程式碼上傳到 Space 中的 app.py 檔案。您的 Space 將自動啟動!有關 Spaces 的更多詳細資訊,請參閱此指南

您的 Webhook 伺服器現在正在公共 Space 上執行。在大多數情況下,您會希望使用金鑰對其進行保護。轉到您的 Space 設定 > “儲存庫金鑰”部分 > “新增金鑰”。將 WEBHOOK_SECRET 環境變數設定為您選擇的值。返回Webhooks 設定並在 Webhook 配置中設定金鑰。現在,只有具有正確金鑰的請求才會被您的伺服器接受。

就這樣!您的 Space 現在已準備好接收來自 Hub 的 Webhooks。請記住,如果您在免費的“cpu-basic”硬體上執行 Space,它將在不活動 48 小時後關閉。如果您需要永久 Space,您應該考慮將其設定為升級的硬體

高階用法

上面的指南解釋了設定 WebhooksServer() 的最快方法。在本節中,我們將看到如何進一步自定義它。

多個端點

您可以在同一伺服器上註冊多個端點。例如,您可能希望一個端點觸發訓練作業,另一個端點觸發模型評估。您可以透過新增多個 @webhook_endpoint 裝飾器來實現這一點

# app.py
from huggingface_hub import webhook_endpoint, WebhookPayload

@webhook_endpoint
async def trigger_training(payload: WebhookPayload) -> None:
    if payload.repo.type == "dataset" and payload.event.action == "update":
        # Trigger a training job if a dataset is updated
        ...

@webhook_endpoint
async def trigger_evaluation(payload: WebhookPayload) -> None:
    if payload.repo.type == "model" and payload.event.action == "update":
        # Trigger an evaluation job if a model is updated
        ...

這將建立兩個端點

(...)
Webhooks are correctly setup and ready to use:
  - POST https://1fadb0f52d8bf825fc.gradio.live/webhooks/trigger_training
  - POST https://1fadb0f52d8bf825fc.gradio.live/webhooks/trigger_evaluation

自定義伺服器

為了獲得更大的靈活性,您還可以直接建立 WebhooksServer() 物件。如果您想自定義伺服器的登陸頁面,這將非常有用。您可以透過傳遞將覆蓋預設頁面的 Gradio UI 來實現此目的。例如,您可以為使用者新增說明或新增表單以手動觸發 Webhook。建立 WebhooksServer() 時,您可以使用 add_webhook() 裝飾器註冊新的 Webhook。

這是一個完整的例子

import gradio as gr
from fastapi import Request
from huggingface_hub import WebhooksServer, WebhookPayload

# 1. Define  UI
with gr.Blocks() as ui:
    ...

# 2. Create WebhooksServer with custom UI and secret
app = WebhooksServer(ui=ui, webhook_secret="my_secret_key")

# 3. Register webhook with explicit name
@app.add_webhook("/say_hello")
async def hello(payload: WebhookPayload):
    return {"message": "hello"}

# 4. Register webhook with implicit name
@app.add_webhook
async def goodbye(payload: WebhookPayload):
    return {"message": "goodbye"}

# 5. Start server (optional)
app.run()
  1. 我們使用 Gradio 塊定義了一個自定義 UI。此 UI 將顯示在伺服器的登陸頁面上。
  2. 我們建立了一個帶有自定義 UI 和金鑰的 WebhooksServer() 物件。金鑰是可選的,可以使用 WEBHOOK_SECRET 環境變數進行設定。
  3. 我們註冊了一個具有顯式名稱的 Webhook。這將建立一個位於 /webhooks/say_hello 的端點。
  4. 我們註冊了一個具有隱式名稱的 Webhook。這將建立一個位於 /webhooks/goodbye 的端點。
  5. 我們啟動伺服器。這是可選的,因為您的伺服器將在指令碼結束時自動啟動。
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.