Hub Python 庫文件
HfApi 客戶端
並獲得增強的文件體驗
開始使用
HfApi 客戶端
以下是 HfApi 類的文件,它作為 Hugging Face Hub API 的 Python 封裝器。
HfApi 的所有方法都可以直接從包的根目錄訪問。兩種方法都將在下面詳細介紹。
使用根目錄方法更直接,但 HfApi 類為您提供了更大的靈活性。特別是,您可以傳遞一個將在所有 HTTP 呼叫中重用的 token。這與 hf auth login 或 login() 不同,因為 token 不會持久儲存在機器上。還可以提供不同的端點或配置自定義使用者代理。
from huggingface_hub import HfApi, list_models
# Use root method
models = list_models()
# Or configure a HfApi client
hf_api = HfApi(
endpoint="https://huggingface.co", # Can be a Private Hub endpoint.
token="hf_xxx", # Token is not persisted on the machine.
)
models = hf_api.list_models()HfApi
class huggingface_hub.HfApi
< 原始碼 >( endpoint: Optional[str] = None token: Union[str, bool, None] = None library_name: Optional[str] = None library_version: Optional[str] = None user_agent: Union[dict, str, None] = None headers: Optional[dict[str, str]] = None )
引數
- endpoint (
str, optional) — Hub 的端點。預設為 https://huggingface.co。 - token (
bool或str, optional) — 有效的使用者訪問 token (字串)。預設為本地儲存的 token,這是推薦的認證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用認證,請傳遞False。 - library_name (
str, optional) — 發起 HTTP 請求的庫名稱。將新增到使用者代理頭。例如:"transformers"。 - library_version (
str, optional) — 發起 HTTP 請求的庫版本。將新增到使用者代理頭。例如:"4.24.0"。 - user_agent (
str,dict, optional) — 使用者代理資訊,可以是字典或單個字串。它將與已安裝包的資訊一起填寫。 - headers (
dict, optional) — 新增到每個請求中的其他標頭。例如:{"X-My-Header": "value"}。此處傳遞的標頭將覆蓋預設標頭。
用於透過 HTTP 與 Hugging Face Hub 互動的客戶端。
客戶端使用在所有 Hub 請求中使用的某些高階設定進行初始化(HF 端點、認證、使用者代理等)。雖然推薦使用 HfApi 客戶端,但並非強制要求,因為其所有公共方法都直接暴露在 huggingface_hub 的根目錄中。
accept_access_request
< 原始碼 >( repo_id: str user: str repo_type: Optional[str] = None token: Union[bool, str, None] = None )
引數
- repo_id (
str) — 要接受訪問請求的倉庫 ID。 - user (
str) — 應接受其訪問請求的使用者使用者名稱。 - repo_type (
str, optional) — 要接受訪問請求的倉庫型別。必須是model、dataset或space之一。預設為model。 - token (
bool或str, optional) — 有效的使用者訪問 token (字串)。預設為本地儲存的 token,這是推薦的認證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用認證,請傳遞False。
引發
HfHubHTTPError
HfHubHTTPError— 如果倉庫未受保護,則為 HTTP 400。HfHubHTTPError— 如果您只有倉庫的只讀訪問許可權,則為 HTTP 403。如果您的組織(倉庫所屬的組織)沒有write或admin角色,或者您傳遞了readtoken,則可能出現這種情況。HfHubHTTPError— 如果使用者不存在於 Hub 上,則為 HTTP 404。HfHubHTTPError— 如果找不到使用者訪問請求,則為 HTTP 404。HfHubHTTPError— 如果使用者訪問請求已在接受列表中,則為 HTTP 404。
接受使用者對給定受保護倉庫的訪問請求。
一旦請求被接受,使用者將能夠下載倉庫的任何檔案並訪問社群選項卡。如果批准模式是自動的,您不必手動接受請求。隨時可以使用 cancel_access_request() 和 reject_access_request() 取消或拒絕已接受的請求。
有關受保護倉庫的更多資訊,請參閱 https://huggingface.co/docs/hub/models-gated。
add_collection_item
< 原始碼 >( collection_slug: str item_id: str item_type: CollectionItemType_T note: Optional[str] = None exists_ok: bool = False token: Union[bool, str, None] = None )
引數
- collection_slug (
str) — 要更新的集合的 slug。例如:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。 - item_id (
str) — 要新增到集合中的專案的 ID。對於倉庫/Spaces/資料集,請使用 repo_id;對於論文,請使用 paper id;對於其他集合,請使用其 slug(例如"moonshotai/kimi-k2")。 - item_type (
str) — 要新增的專案的型別。可以是"model"、"dataset"、"space"、"paper"或"collection"之一。 - note (
str, 可選) — 要附加到收藏項中的註釋。註釋的最大長度為 500 個字元。 - exists_ok (
bool, 可選) — 如果為True,則如果專案已存在,則不引發錯誤。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
引發
HfHubHTTPError
HfHubHTTPError— 如果您只有倉庫的只讀訪問許可權,則為 HTTP 403。如果您的組織(倉庫所屬的組織)沒有write或admin角色,或者您傳遞了readtoken,則可能出現這種情況。HfHubHTTPError— 如果嘗試新增到收藏項中的專案在 Hub 上不存在,則返回 HTTP 404。HfHubHTTPError— 如果嘗試新增到收藏項中的專案已在收藏中(且 exists_ok=False),則返回 HTTP 409
將一個專案新增到 Hub 上的收藏中。
返回: Collection
示例
>>> from huggingface_hub import add_collection_item
>>> collection = add_collection_item(
... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
... item_id="pierre-loic/climate-news-articles",
... item_type="dataset"
... )
>>> collection.items[-1].item_id
"pierre-loic/climate-news-articles"
# ^item got added to the collection on last position
# Add item with a note
>>> add_collection_item(
... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab",
... item_id="datasets/climate_fever",
... item_type="dataset"
... note="This dataset adopts the FEVER methodology that consists of 1,535 real-world claims regarding climate-change collected on the internet."
... )
(...)add_space_secret
< source >( repo_id: str key: str value: str description: Optional[str] = None token: Union[bool, str, None] = None )
引數
- repo_id (
str) — 要更新的倉庫 ID。例如:"bigcode/in-the-stack"。 - key (
str) — 金鑰。例如:"GITHUB_API_KEY" - value (
str) — 金鑰值。例如:"your_github_api_key"。 - description (
str, 可選) — 金鑰描述。例如:"Github API key to access the Github API"。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
在 Hub 上的收藏中新增或更新一個專案。
金鑰允許在不硬編碼的情況下為 Space 設定金鑰或令牌。有關更多詳細資訊,請參見 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。
add_space_variable
< source >( repo_id: str key: str value: str description: Optional[str] = None token: Union[bool, str, None] = None )
引數
- repo_id (
str) — 要更新的倉庫 ID。例如:"bigcode/in-the-stack"。 - key (
str) — 變數鍵。例如:"MODEL_REPO_ID" - value (
str) — 變數值。例如:"the_model_repo_id"。 - description (
str) — 變數的描述。例如:"Model Repo ID of the implemented model"。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
在 Space 中新增或更新一個變數。
變數允許在不硬編碼的情況下為 Space 設定環境變數。有關更多詳細資訊,請參見 https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
auth_check
< source >( repo_id: str repo_type: Optional[str] = None token: Union[bool, str, None] = None )
引數
- repo_id (
str) — 要檢查訪問許可權的儲存庫。格式應為"user/repo_name"。例如:"user/my-cool-model"。 - repo_type (
str, 可選) — 儲存庫的型別。應為"model"、"dataset"或"space"之一。如果未指定,則預設為"model"。 - token (
Union[bool, str, None], 可選) — 一個有效的使用者訪問令牌。如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。設定為False以停用身份驗證。參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
-
RepositoryNotFoundError — 如果儲存庫不存在、私有或使用者沒有訪問許可權,則引發。這可能是因為
repo_id或repo_type不正確,或者儲存庫是私有的但使用者未進行身份驗證。 -
GatedRepoError — 如果儲存庫存在但受門控,並且使用者無權訪問它,則引發。
檢查提供的使用者令牌是否可以訪問 Hugging Face Hub 上的特定儲存庫。
此方法驗證透過提供的令牌進行身份驗證的使用者是否可以訪問指定的儲存庫。如果找不到儲存庫或使用者缺少訪問所需的許可權,則該方法將引發適當的異常。
示例
檢查使用者對儲存庫的訪問許可權
>>> from huggingface_hub import auth_check
>>> from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError
try:
auth_check("user/my-cool-model")
except GatedRepoError:
# Handle gated repository error
print("You do not have permission to access this gated repository.")
except RepositoryNotFoundError:
# Handle repository not found error
print("The repository was not found or you do not have access.")在此示例中
- 如果使用者有權訪問,該方法將成功完成。
- 如果儲存庫受門控或不存在,將引發適當的異常,允許使用者相應地處理它們。
cancel_access_request
< source >( repo_id: str user: str repo_type: Optional[str] = None token: Union[bool, str, None] = None )
引數
- repo_id (
str) — 要為其取消訪問請求的倉庫 ID。 - user (
str) — 要取消其訪問請求的使用者名稱。 - repo_type (
str, 可選) — 要為其取消訪問請求的儲存庫型別。必須是model、dataset或space之一。預設為model。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
引發
HfHubHTTPError
HfHubHTTPError— 如果倉庫未受保護,則為 HTTP 400。HfHubHTTPError— 如果您只有倉庫的只讀訪問許可權,則為 HTTP 403。如果您的組織(倉庫所屬的組織)沒有write或admin角色,或者您傳遞了readtoken,則可能出現這種情況。HfHubHTTPError— 如果使用者不存在於 Hub 上,則為 HTTP 404。HfHubHTTPError— 如果找不到使用者訪問請求,則為 HTTP 404。HfHubHTTPError— 如果使用者訪問請求已在待處理列表中,則返回 HTTP 404。
取消使用者對給定受門控儲存庫的訪問請求。
被取消的請求將返回待處理列表,使用者將失去對該儲存庫的訪問許可權。
有關受保護倉庫的更多資訊,請參閱 https://huggingface.co/docs/hub/models-gated。
cancel_job
< source >( job_id: str namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- job_id (
str) — 作業的 ID。 - namespace (
str, optional) — 作業執行的名稱空間。預設為當前使用者的名稱空間。 - token (
Union[bool, str, None], optional) — 一個有效的使用者訪問令牌。如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。設定為False以停用身份驗證。參考: https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
取消 Hugging Face 基礎架構上的計算作業。
change_discussion_status
< source >( repo_id: str discussion_num: int new_status: Literal['open', 'closed'] token: Union[bool, str, None] = None comment: Optional[str] = None repo_type: Optional[str] = None ) → DiscussionStatusChange
引數
- repo_id (
str) — 由/分隔的使用者或組織和倉庫名稱。 - discussion_num (
int) — 討論或拉取請求的編號。必須是嚴格正整數。 - new_status (
str) — 討論的新狀態,可以是"open"或"closed"。 - comment (
str, optional) — 狀態更改時附帶的可選評論。 - repo_type (
str, optional) — 如果上傳到資料集或 space,請設定為"dataset"或"space",如果上傳到模型,則為None或"model"。預設為None。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
狀態更改事件
關閉或重新開啟討論或拉取請求。
示例
>>> new_title = "New title, fixing a typo"
>>> HfApi().rename_discussion(
... repo_id="username/repo_name",
... discussion_num=34
... new_title=new_title
... )
# DiscussionStatusChange(id='deadbeef0000000', type='status-change', ...)
引發以下錯誤
HTTPError如果 HuggingFace API 返回錯誤ValueError如果某些引數值無效- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。
comment_discussion
< source >( repo_id: str discussion_num: int comment: str token: Union[bool, str, None] = None repo_type: Optional[str] = None ) → DiscussionComment
引數
- repo_id (
str) — 由/分隔的使用者或組織和倉庫名稱。 - discussion_num (
int) — 討論或拉取請求的編號。必須是嚴格正整數。 - comment (
str) — 要建立的評論內容。評論支援 markdown 格式。 - repo_type (
str, optional) — 如果上傳到資料集或 space,請設定為"dataset"或"space",如果上傳到模型,則為None或"model"。預設為None。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
新建立的評論
在給定的討論中建立新評論。
示例
>>> comment = """
... Hello @otheruser!
...
... # This is a title
...
... **This is bold**, *this is italic* and ~this is strikethrough~
... And [this](http://url) is a link
... """
>>> HfApi().comment_discussion(
... repo_id="username/repo_name",
... discussion_num=34
... comment=comment
... )
# DiscussionComment(id='deadbeef0000000', type='comment', ...)
引發以下錯誤
HTTPError如果 HuggingFace API 返回錯誤ValueError如果某些引數值無效- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。
create_branch
< source >( repo_id: str branch: str revision: Optional[str] = None token: Union[bool, str, None] = None repo_type: Optional[str] = None exist_ok: bool = False )
引數
- repo_id (
str) — 將建立分支的倉庫。例如:"user/my-cool-model"。 - branch (
str) — 要建立的分支的名稱。 - revision (
str, optional) — 用於建立分支的 git 版本。它可以是分支名稱,也可以是提交的 OID/SHA(十六進位制字串)。預設為"main"分支的 head。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - repo_type (
str, optional) — 如果在資料集或 space 上建立分支,則設定為"dataset"或"space",如果標記模型,則設定為None或"model"。預設為None。 - exist_ok (
bool, optional, defaults toFalse) — 如果True,則當分支已存在時不會引發錯誤。
- RepositoryNotFoundError — 如果倉庫未找到(錯誤 404):repo_id/repo_type 錯誤,私有但未經驗證或倉庫不存在。
- BadRequestError — 如果分支的引用無效。例如
refs/pr/5或 ‘refs/foo/bar’。 - HfHubHTTPError — 如果分支已存在於倉庫中(錯誤 409)且
exist_ok設定為False。
為 Hub 上的倉庫建立新分支,從指定版本(預設為 main)開始。要查詢適合您需求的版本,您可以使用 list_repo_refs() 或 list_repo_commits()。
create_collection
< source >( title: str namespace: Optional[str] = None description: Optional[str] = None private: bool = False exists_ok: bool = False token: Union[bool, str, None] = None )
引數
- title (
str) — 要建立的收藏的標題。例如:"Recent models"。 - namespace (
str, optional) — 要建立的 collection 的名稱空間(使用者名稱或組織)。將預設為所有者名稱。 - description (
str, optional) — 要建立的 collection 的描述。 - private (
bool, optional) — Collection 是否應設為私有。預設為False(即公共 collection)。 - exists_ok (
bool, optional) — 如果 collection 已存在,則不引發錯誤。 - token (
bool或str, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳入False。
在 Hub 上建立新的 Collection。
返回: Collection
create_commit
< source >( repo_id: str operations: Iterable[CommitOperation] commit_message: str commit_description: Optional[str] = None token: Union[str, bool, None] = None repo_type: Optional[str] = None revision: Optional[str] = None create_pr: Optional[bool] = None num_threads: int = 5 parent_commit: Optional[str] = None run_as_future: bool = False ) → CommitInfo 或 Future
引數
- repo_id (
str) — 將建立 commit 的倉庫,例如:"username/custom_transformers" - operations (
IterableofCommitOperation()) — 要包含在 commit 中的操作列表,可以是:- CommitOperationAdd 用於上傳檔案
- CommitOperationDelete 用於刪除檔案
- CommitOperationCopy 用於複製檔案
操作物件將被修改以包含與上傳相關的資訊。請勿將同一物件用於多個 commit。
- commit_message (
str) — 將要建立的 commit 的摘要(第一行)。 - commit_description (
str, optional) — 將要建立的 commit 的描述 - token (
bool或str, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳入False。 - repo_type (
str, optional) — 如果上傳到 dataset 或 space,請設定為"dataset"或"space",如果上傳到 model,則為None或"model"。預設為None。 - revision (
str, optional) — 要從中 commit 的 git revision。預設為"main"分支的最新提交。 - create_pr (
boolean, optional) — 是否為該 commit 建立 Pull Request。預設為False。如果未設定revision,則 PR 將針對"main"分支開啟。如果設定了revision並且是一個分支,則 PR 將針對該分支開啟。如果設定了revision並且不是分支名稱(例如:commit OID),伺服器將返回RevisionNotFoundError。 - num_threads (
int, optional) — 上傳檔案的併發執行緒數。預設為 5。設定為 2 表示最多同時上傳 2 個檔案。 - parent_commit (
str, optional) — 父 commit 的 OID / SHA,作為十六進位制字串。也支援簡寫(前 7 個字元)。如果指定且create_pr為False,如果revision未指向parent_commit,則 commit 將失敗。如果指定且create_pr為True,則將從parent_commit建立 pull request。指定parent_commit可確保在 commit 更改之前 repo 未被修改,在 repo 被併發更新/commit 時特別有用。 - run_as_future (
bool, optional) — 是否在此方法中後臺執行。後臺作業會順序執行,不會阻塞主執行緒。傳入run_as_future=True將返回一個 Future 物件。預設為False。
返回
CommitInfo 或 Future
包含新建立 commit 資訊(commit hash, commit url, pr url, commit message 等)的 CommitInfo 例項。如果傳入 run_as_future=True,則返回一個 Future 物件,執行時將包含結果。
引發
ValueError 或 RepositoryNotFoundError
ValueError— 如果 commit message 為空。ValueError— 如果 parent commit 不是有效的 commit OID。ValueError— 如果 commit 的 README.md 檔案包含無效的元資料部分。在這種情況下,commit 會提前失敗,在嘗試上傳任何檔案之前。ValueError— 如果create_pr為True且 revision 不是None也不是"main"。- RepositoryNotFoundError — 如果倉庫未找到(錯誤 404):repo_id/repo_type 錯誤,私有但未經驗證或倉庫不存在。
在給定的 repo 中建立 commit,根據需要刪除和上傳檔案。
輸入的
CommitOperation列表在 commit 過程中會被修改。請勿將同一物件用於多個 commit。
create_commit假定 repo 已存在於 Hub 上。如果您收到 Client error 404,請確保您已透過身份驗證並且repo_id和repo_type設定正確。如果 repo 不存在,請先使用 create_repo() 建立它。
create_commit限制為 25k LFS 檔案和 1GB 的普通檔案負載。
create_discussion
< source >( repo_id: str title: str token: Union[bool, str, None] = None description: Optional[str] = None repo_type: Optional[str] = None pull_request: bool = False )
引數
- repo_id (
str) — 一個由/分隔的名稱空間(使用者或組織)和倉庫名稱。 - title (
str) — discussion 的標題。最多可包含 200 個字元,且必須至少有 3 個字元。將去除首尾空格。 - token (
bool或str, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳入False。 - description (
str, optional) — Pull Request 的可選描述。預設為"Discussion opened with the huggingface_hub Python library" - pull_request (
bool, 可選) — 是建立 Pull Request 還是討論。如果為True,則建立 Pull Request。如果為False,則建立討論。預設為False。 - repo_type (
str, 可選) — 如果上傳到資料集或空間,則設定為"dataset"或"space";如果上傳到模型,則設定為None或"model"。預設為None。
建立討論或 Pull Request。
以程式設計方式建立的 Pull Request 將處於 "draft" 狀態。
使用 HfApi.create_commit() 也可以一次性建立帶有更改的 Pull Request。
引發以下錯誤
HTTPError如果 HuggingFace API 返回錯誤ValueError如果某些引數值無效- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。
create_inference_endpoint
< source >( name: str repository: str framework: str accelerator: str instance_size: str instance_type: str region: str vendor: str account_id: Optional[str] = None min_replica: int = 1 max_replica: int = 1 scaling_metric: Optional[InferenceEndpointScalingMetric] = None scaling_threshold: Optional[float] = None scale_to_zero_timeout: Optional[int] = None revision: Optional[str] = None task: Optional[str] = None custom_image: Optional[dict] = None env: Optional[dict[str, str]] = None secrets: Optional[dict[str, str]] = None type: InferenceEndpointType = <InferenceEndpointType.PROTECTED: 'protected'> domain: Optional[str] = None path: Optional[str] = None cache_http_responses: Optional[bool] = None tags: Optional[list[str]] = None namespace: Optional[str] = None token: Union[bool, str, None] = None ) → InferenceEndpoint
引數
- name (
str) — 新的推理端點的唯一名稱。 - repository (
str) — 與推理端點關聯的模型儲存庫名稱(例如"gpt2")。 - framework (
str) — 模型使用的機器學習框架(例如"custom")。 - accelerator (
str) — 推理使用的硬體加速器(例如"cpu")。 - instance_size (
str) — 用於託管模型的例項的大小或型別(例如"x4")。 - instance_type (
str) — 推理端點將部署到的雲實例型別(例如"intel-icl")。 - region (
str) — 推理端點將被建立的雲區域(例如"us-east-1")。 - vendor (
str) — 推理端點將託管的雲提供商或供應商(例如"aws")。 - account_id (
str, optional) — 用於將 VPC 連結到私有推理端點的賬戶 ID(如果適用)。 - min_replica (
int, optional) — 最少要保持執行的推理端點副本(例項)數量。要啟用縮放到零,請將此值設定為 0 並相應調整scale_to_zero_timeout。預設為 1。 - max_replica (
int, optional) — 推理端點可以擴充套件到的最大副本(例項)數量。預設為 1。 - scaling_metric (
str或InferenceEndpointScalingMetric, optional) — 用於擴充套件的度量參考。提供時為“pendingRequests”或“hardwareUsage”。預設為 None(表示:讓 HF Endpoints 服務指定度量)。 - scaling_threshold (
float, optional) — 用於觸發擴充套件的擴充套件度量閾值。在未提供擴充套件度量時被忽略。預設為 None(表示:讓 HF Endpoints 服務指定閾值)。 - scale_to_zero_timeout (
int, optional) — 非活動端點縮放到零之前的分鐘數,或者如果設定為 None 且min_replica不為 0,則不進行縮放到零。預設為 None。 - revision (
str, optional) — 在推理端點上部署的具體模型修訂版本(例如"6c0e6080953db56375760c0471a8c5f2929baf11")。 - task (
str, optional) — 部署模型的任務(例如"text-classification")。 - custom_image (
dict, optional) — 用於推理端點的自定義 Docker 映象。如果您想部署在text-generation-inference(TGI) 框架上執行的推理端點,這會很有用(請參閱示例)。 - env (
dict[str, str], optional) — 要注入到容器環境中的非敏感環境變數。 - secrets (
dict[str, str], optional) — 要注入到容器環境中的敏感值。 - type ([`InferenceEndpointType]
, *optional*) -- 推理端點的型別,可以是“protected”(預設)、“public”或“private”`。 - domain (
str, optional) — 推理端點的自定義域,如果設定了該域,推理端點將在此域上可用(例如"my-new-domain.cool-website.woof")。 - path (
str, optional) — 部署到推理端點的自定義路徑,應以/開頭(例如"/models/google-bert/bert-base-uncased")。 - cache_http_responses (
bool, optional) — 是否快取來自推理端點的 HTTP 響應。預設為False。 - tags (
list[str], optional) — 要與推理端點關聯的標籤列表。 - namespace (
str, optional) — 將建立推理端點的名稱空間。預設為當前使用者的名稱空間。 - token (
bool或str, 可選) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
已更新的推理端點資訊。
建立新的推理端點。
示例
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.create_inference_endpoint(
... "my-endpoint-name",
... repository="gpt2",
... framework="pytorch",
... task="text-generation",
... accelerator="cpu",
... vendor="aws",
... region="us-east-1",
... type="protected",
... instance_size="x2",
... instance_type="intel-icl",
... )
>>> endpoint
InferenceEndpoint(name='my-endpoint-name', status="pending",...)
# Run inference on the endpoint
>>> endpoint.client.text_generation(...)
"..."# Start an Inference Endpoint running Zephyr-7b-beta on TGI
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.create_inference_endpoint(
... "aws-zephyr-7b-beta-0486",
... repository="HuggingFaceH4/zephyr-7b-beta",
... framework="pytorch",
... task="text-generation",
... accelerator="gpu",
... vendor="aws",
... region="us-east-1",
... type="protected",
... instance_size="x1",
... instance_type="nvidia-a10g",
... env={
... "MAX_BATCH_PREFILL_TOKENS": "2048",
... "MAX_INPUT_LENGTH": "1024",
... "MAX_TOTAL_TOKENS": "1512",
... "MODEL_ID": "/repository"
... },
... custom_image={
... "health_route": "/health",
... "url": "ghcr.io/huggingface/text-generation-inference:1.1.0",
... },
... secrets={"MY_SECRET_KEY": "secret_value"},
... tags=["dev", "text-generation"],
... )# Start an Inference Endpoint running ProsusAI/finbert while scaling to zero in 15 minutes
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.create_inference_endpoint(
... "finbert-classifier",
... repository="ProsusAI/finbert",
... framework="pytorch",
... task="text-classification",
... min_replica=0,
... scale_to_zero_timeout=15,
... accelerator="cpu",
... vendor="aws",
... region="us-east-1",
... type="protected",
... instance_size="x2",
... instance_type="intel-icl",
... )
>>> endpoint.wait(timeout=300)
# Run inference on the endpoint
>>> endpoint.client.text_generation(...)
TextClassificationOutputElement(label='positive', score=0.8983615040779114)create_inference_endpoint_from_catalog
< source >( repo_id: str name: Optional[str] = None token: Union[bool, str, None] = None namespace: Optional[str] = None ) → InferenceEndpoint
引數
- repo_id (
str) — 要作為推理端點部署的目錄中的模型 ID。 - name (
str, 可選) — 新推理端點的唯一名稱。如果未提供,將生成一個隨機名稱。 - token (
bool或str, 可選) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。 - namespace (
str, 可選) — 將建立推理端點的名稱空間。預設為當前使用者的名稱空間。
新推理端點的資訊。
從 Hugging Face 推理目錄中的模型建立新的推理端點。
推理目錄的目的是提供一個精選的模型列表,這些模型經過了推理最佳化,並且已經測試了預設配置。有關目錄中可用模型的列表,請參閱 https://endpoints.huggingface.co/catalog。
create_inference_endpoint_from_catalog是實驗性的。其 API 在未來可能會發生變化。如果您有任何建議或請求,請提供反饋。
create_pull_request
< source >( repo_id: str title: str token: Union[bool, str, None] = None description: Optional[str] = None repo_type: Optional[str] = None )
引數
- repo_id (
str) — 一個名稱空間(使用者或組織)和由/分隔的倉庫名稱。 - title (
str) — Discussion 的標題。最多可包含 200 個字元,最少 3 個字元。將刪除前導和尾隨空格。 - token (
bool或str, 可選) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - description (
str, 可選) — Pull Request 的可選描述。預設為"Discussion opened with the huggingface_hub Python library" - repo_type (
str, 可選) — 如果上傳到資料集或空間,請設定為"dataset"或"space",如果上傳到模型,請設定為None或"model"。預設為None。
建立 Pull Request。以程式設計方式建立的 Pull Request 將處於 "draft" 狀態。
使用 HfApi.create_commit() 也可以一次性建立帶有更改的 Pull Request;
這是 HfApi.create_discussion() 的包裝器。
引發以下錯誤
HTTPError如果 HuggingFace API 返回錯誤ValueError如果某些引數值無效- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。
create_repo
< source >( repo_id: str token: Union[str, bool, None] = None private: Optional[bool] = None repo_type: Optional[str] = None exist_ok: bool = False resource_group_id: Optional[str] = None space_sdk: Optional[str] = None space_hardware: Optional[SpaceHardware] = None space_storage: Optional[SpaceStorage] = None space_sleep_time: Optional[int] = None space_secrets: Optional[list[dict[str, str]]] = None space_variables: Optional[list[dict[str, str]]] = None ) → RepoUrl
引數
- repo_id (
str) — 一個名稱空間(使用者或組織)和由/分隔的倉庫名稱。 - token (
bool或str, 可選) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - private (
bool, 可選) — 是否使倉庫私有。如果為None(預設),倉庫將是公開的,除非組織的預設設定為私有。如果倉庫已存在,則忽略此值。 - repo_type (
str, 可選) — 如果上傳到資料集或空間,請設定為"dataset"或"space",如果上傳到模型,請設定為None或"model"。預設為None。 - exist_ok (
bool, 可選, 預設為False) — 如果為True,則在倉庫已存在時不會引發錯誤。 - resource_group_id (
str, 可選) — 要建立倉庫的資源組。資源組僅適用於 Enterprise Hub 組織,並允許定義組織中哪些成員可以訪問該資源。資源組的 ID 可以在 Hub 上該資源的頁面 URL 中找到(例如,"66670e5163145ca562cb1988")。要了解有關資源組的更多資訊,請參閱 https://huggingface.co/docs/hub/en/security-resource-groups。 - space_sdk (
str, 可選) — 如果 repo_type 是 “space”,則選擇要使用的 SDK。可以是 “streamlit”、“gradio”、“docker” 或 “static”。 - space_hardware (
SpaceHardware或str, 可選) — 如果 repo_type 是 “space”,則選擇硬體。請參閱 SpaceHardware 以獲取完整列表。 - space_storage (
SpaceStorage或str, 可選) — 選擇持久儲存層。例如:"small"。請參閱 SpaceStorage 以獲取完整列表。 - space_sleep_time (
int, 可選) — 在將 Space 進入睡眠狀態之前等待的非活動秒數。如果不想讓 Space 進入睡眠狀態,請設定為-1(升級硬體的預設行為)。對於免費硬體,您無法配置睡眠時間(固定為 48 小時非活動時間)。有關更多詳細資訊,請參閱 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。 - space_secrets (
list[dict[str, str]], 可選) — 要在您的 Space 中設定的 secret 金鑰列表。每個專案格式為{"key": ..., "value": ..., "description": ...},其中 description 是可選的。有關更多詳細資訊,請參閱 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。 - space_variables (
list[dict[str, str]], 可選) — 要在您的 Space 中設定的公共環境變數列表。每個專案格式為{"key": ..., "value": ..., "description": ...},其中 description 是可選的。有關更多詳細資訊,請參閱 https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables。
返回
新建立的倉庫的 URL。值是 str 的子類,包含 endpoint、repo_type 和 repo_id 等屬性。
在 HuggingFace Hub 上建立一個空倉庫。
create_scheduled_job
< source >( image: str command: list[str] schedule: str suspend: Optional[bool] = None concurrency: Optional[bool] = None env: Optional[dict[str, Any]] = None secrets: Optional[dict[str, Any]] = None flavor: Optional[SpaceHardware] = None timeout: Optional[Union[int, float, str]] = None labels: Optional[dict[str, str]] = None namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- image (
str) — 要使用的 Docker 映象。示例:"ubuntu"、"python:3.12"、"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"。來自 Space 的映象示例:"hf.co/spaces/lhoestq/duckdb"。 - command (
list[str]) — 要執行的命令。示例:["echo", "hello"]。 - schedule (
str) — “@annually”、“@yearly”、“@monthly”、“@weekly”、“@daily”、“@hourly”,或 CRON 計劃表示式(例如,'0 9 * * 1' 表示每週一上午 9 點)。 - suspend (
bool, 可選) — 如果為 True,則計劃的 Job 將被掛起(暫停)。預設為 False。 - concurrency (
bool, 可選) — 如果為 True,則此 Job 的多個例項可以併發執行。預設為 False。 - env (
dict[str, Any], 可選) — 定義 Job 的環境變數。 - secrets (
dict[str, Any], 可選) — 定義 Job 的 secret 環境變數。 - flavor (
str, 可選) — 硬體的 flavor,如 Hugging Face Spaces 中所示。有關可能的值,請參閱 SpaceHardware。預設為"cpu-basic"。 - timeout (
Union[int, float, str], 可選) — Job 的最大持續時間:int/float 帶 s(秒,預設)、m(分鐘)、h(小時)或 d(天)。示例:300或"5m"表示 5 分鐘。 - labels (
dict[str, str], 可選) — 要附加到 Job 的標籤(鍵值對)。 - namespace (
str, 可選) — 將建立 Job 的名稱空間。預設為當前使用者的名稱空間。 - token
(Union[bool, str, None], 可選) — 一個有效的使用者訪問令牌。如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。設定為False以停用身份驗證。參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
在 Hugging Face 基礎設施上建立計劃的計算 Job。
示例
建立您的第一個計劃 Job
>>> from huggingface_hub import create_scheduled_job
>>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly")使用 CRON 計劃表示式
>>> from huggingface_hub import create_scheduled_job
>>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('this runs every 5min')"], schedule="*/5 * * * *")建立計劃的 GPU Job
>>> from huggingface_hub import create_scheduled_job
>>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"
>>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"]
>>> create_scheduled_job(image, command, flavor="a10g-small", schedule="@hourly")create_scheduled_uv_job
< source >( script: str script_args: Optional[list[str]] = None schedule: str suspend: Optional[bool] = None concurrency: Optional[bool] = None dependencies: Optional[list[str]] = None python: Optional[str] = None image: Optional[str] = None env: Optional[dict[str, Any]] = None secrets: Optional[dict[str, Any]] = None flavor: Optional[SpaceHardware] = None timeout: Optional[Union[int, float, str]] = None labels: Optional[dict[str, str]] = None namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- script (
str) — UV 指令碼的路徑或 URL,或命令。 - script_args (
list[str], 可選) — 要傳遞給指令碼的引數,或命令。 - schedule (
str) — “@annually”、“@yearly”、“@monthly”、“@weekly”、“@daily”、“@hourly”,或 CRON 計劃表示式(例如,'0 9 * * 1' 表示每週一上午 9 點)。 - suspend (
bool, 可選) — 如果為 True,則計劃的 Job 將被掛起(暫停)。預設為 False。 - concurrency (
bool, 可選) — 如果為 True,則此 Job 的多個例項可以併發執行。預設為 False。 - dependencies (
list[str], 可選) — 用於執行 UV 指令碼的依賴項。 - python (
str, 可選) — 使用特定的 Python 版本。預設為 3.12。 - image (
str, 可選, 預設為 “ghcr.io/astral-sh/uv —python3.12-bookworm”): 使用自定義 Docker 映象,其中已安裝uv。 - env (
dict[str, Any], 可選) — 定義 Job 的環境變數。 - secrets (
dict[str, Any], optional) — 定義 Job 的秘密環境變數。 - flavor (
str, optional) — 硬體的配置,如 Hugging Face Spaces 中那樣。有關可能的值,請參閱 SpaceHardware。預設為"cpu-basic"。 - timeout (
Union[int, float, str], optional) — Job 的最長持續時間:int/float 表示秒 (s) (預設),m (分鐘),h (小時) 或 d (天)。示例:300或"5m"表示 5 分鐘。 - labels (
dict[str, str], optional) — 要附加到 Job 的標籤(鍵值對)。 - namespace (
str, optional) — 將建立 Job 的名稱空間。預設為當前使用者的名稱空間。 - token (
Union[bool, str, None], optional) — 有效的使用者訪問令牌。如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。設定為False以停用身份驗證。參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
在 Hugging Face 基礎設施上執行一個 UV 指令碼 Job。
示例
排程一個來自 URL 的指令碼
>>> from huggingface_hub import create_scheduled_uv_job
>>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
>>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
>>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")排程一個本地指令碼
>>> from huggingface_hub import create_scheduled_uv_job
>>> script = "my_sft.py"
>>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
>>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly")排程一個命令
>>> from huggingface_hub import create_scheduled_uv_job
>>> script = "lighteval"
>>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
>>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small", schedule="@weekly")create_tag
< source >( repo_id: str tag: str tag_message: Optional[str] = None revision: Optional[str] = None token: Union[bool, str, None] = None repo_type: Optional[str] = None exist_ok: bool = False )
引數
- repo_id (
str) — 在其中標記提交的儲存庫。示例:"user/my-cool-model"。 - tag (
str) — 要建立的標籤的名稱。 - tag_message (
str, optional) — 要建立的標籤的描述。 - revision (
str, optional) — 要標記的 git revision。它可以是分支名稱或提交的 OID/SHA(十六進位制字串)。也支援簡寫(前 7 個字元)。預設為"main"分支的 head。 - token (
bool或str, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - repo_type (
str, optional) — 如果標記資料集或空間,則設定為"dataset"或"space",如果標記模型,則設定為None或"model"。預設為None。 - exist_ok (
bool, optional, defaults toFalse) — 如果True,則在標籤已存在時不要引發錯誤。
- RepositoryNotFoundError — 如果倉庫未找到(錯誤 404):repo_id/repo_type 錯誤,私有但未經驗證或倉庫不存在。
- RevisionNotFoundError — 如果在儲存庫中找不到 revision(錯誤 404)。
- HfHubHTTPError — 如果分支已存在於倉庫中(錯誤 409)且
exist_ok設定為False。
標記 Hub 上給定儲存庫的某個提交。
create_webhook
< source >( url: Optional[str] = None job_id: Optional[str] = None watched: list[Union[dict, WebhookWatchedItem]] domains: Optional[list[constants.WEBHOOK_DOMAIN_T]] = None secret: Optional[str] = None token: Union[bool, str, None] = None ) → WebhookInfo
引數
- url (
str) — 傳送 payload 的 URL。 - job_id (
str) — 源 Job 的 ID,將觸發帶有環境變數 WEBHOOK_PAYLOAD 的 webhook 有效負載。此外,還提供以下環境變數以方便使用:WEBHOOK_REPO_ID、WEBHOOK_REPO_TYPE 和 WEBHOOK_SECRET。 - watched (
list[WebhookWatchedItem]) — 要被 webhook 監視的 WebhookWatchedItem 列表。也可以將“watched items”作為純字典提供。 - domains (
list[Literal["repo", "discussion"]], optional) — 要監視的域列表。可以是“repo”、“discussion”或兩者都選。 - secret (
str, optional) — 用於簽名 payload 的金鑰。 - token (
bool或str, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
新建立的 webhook 的資訊。
建立新的 webhook。
Webhook 可以向 URL 傳送 payload,也可以觸發 Job 在 Hugging Face 基礎設施上執行。此函式應使用 url 或 job_id 呼叫,但不能同時使用兩者。
示例
建立一個向 URL 傳送 payload 的 webhook
>>> from huggingface_hub import create_webhook
>>> payload = create_webhook(
... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
... url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
... domains=["repo", "discussion"],
... secret="my-secret",
... )
>>> print(payload)
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
job=None,
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
domains=["repo", "discussion"],
secret="my-secret",
disabled=False,
)執行一個 Job,然後建立一個觸發該 Job 的 webhook
>>> from huggingface_hub import create_webhook, run_job
>>> job = run_job(
... image="ubuntu",
... command=["bash", "-c", r"echo An event occured in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD"],
... )
>>> payload = create_webhook(
... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
... job_id=job.id,
... domains=["repo", "discussion"],
... secret="my-secret",
... )
>>> print(payload)
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
url=None,
job=JobSpec(
docker_image='ubuntu',
space_id=None,
command=['bash', '-c', 'echo An event occured in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD'],
arguments=[],
environment={},
secrets=[],
flavor='cpu-basic',
timeout=None,
tags=None,
arch=None
),
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
domains=["repo", "discussion"],
secret="my-secret",
disabled=False,
)dataset_info
< source >( repo_id: str revision: Optional[str] = None timeout: Optional[float] = None files_metadata: bool = False expand: Optional[list[ExpandDatasetProperty_T]] = None token: Union[bool, str, None] = None ) → hf_api.DatasetInfo
引數
- repo_id (
str) — 一個由/分隔的名稱空間(使用者或組織)和儲存庫名稱。 - revision (
str, optional) — 要從中獲取資訊的 dataset 倉庫的版本。 - timeout (
float, optional) — 是否為請求設定 Hub 超時。 - files_metadata (
bool, optional) — 是否檢索倉庫中檔案的元資料(大小、LFS 元資料等)。預設為False。 - expand (
list[ExpandDatasetProperty_T], optional) — 列表中需要返回的屬性。使用時,只返回列表中的屬性。如果傳入了files_metadata,則此引數不能使用。可能的值包括"author","cardData","citation","createdAt","disabled","description","downloads","downloadsAllTime","gated","lastModified","likes","paperswithcode_id","private","siblings","sha","tags","trendingScore","usedStorage", 和"resourceGroup"。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
資料集倉庫資訊。
獲取 huggingface.co 上特定資料集的資訊。
如果傳遞了可接受的 token,資料集可以設定為私有。
引發以下錯誤
- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。- RevisionNotFoundError 如果找不到要從中下載的版本。
delete_branch
< source >( repo_id: str branch: str token: Union[bool, str, None] = None repo_type: Optional[str] = None )
引數
- repo_id (
str) — 要刪除分支的倉庫。示例:"user/my-cool-model"。 - branch (
str) — 要刪除的分支名稱。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - repo_type (
str, optional) — 如果在資料集或空間上建立分支,則設定為"dataset"或"space",如果標記模型,則設定為None或"model"。預設為None。
- RepositoryNotFoundError — 如果倉庫未找到(錯誤 404):repo_id/repo_type 錯誤,私有但未經驗證或倉庫不存在。
- HfHubHTTPError — 如果嘗試刪除受保護的分支。例如
main無法刪除。 - HfHubHTTPError — 如果嘗試刪除一個不存在的分支。
刪除 Hub 上倉庫中的一個分支。
delete_collection
< source >( collection_slug: str missing_ok: bool = False token: Union[bool, str, None] = None )
引數
- collection_slug (
str) — 要刪除的收藏集的 slug。示例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。 - missing_ok (
bool, optional) — 如果True,則在收藏集不存在時不會引發錯誤。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
刪除 Hub 上的一個收藏集。
示例
>>> from huggingface_hub import delete_collection
>>> collection = delete_collection("username/useless-collection-64f9a55bb3115b4f513ec026", missing_ok=True)這是一個不可恢復的操作。被刪除的收藏集無法恢復。
delete_collection_item
< source >( collection_slug: str item_object_id: str missing_ok: bool = False token: Union[bool, str, None] = None )
引數
- collection_slug (
str) — 要更新的收藏集的 slug。示例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。 - item_object_id (
str) — 收藏集中文字專案的 ID。這不是 Hub 上專案的 ID(repo_id 或 paper id)。必須從 CollectionItem 物件中檢索。示例:collection.items[0].item_object_id。 - missing_ok (
bool, optional) — 如果True,則在專案不存在時不會引發錯誤。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
從收藏集中刪除一個專案。
示例
>>> from huggingface_hub import get_collection, delete_collection_item
# Get collection first
>>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
# Delete item based on its ID
>>> delete_collection_item(
... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
... item_object_id=collection.items[-1].item_object_id,
... )delete_file
< source >( path_in_repo: str repo_id: str token: Union[str, bool, None] = None repo_type: Optional[str] = None revision: Optional[str] = None commit_message: Optional[str] = None commit_description: Optional[str] = None create_pr: Optional[bool] = None parent_commit: Optional[str] = None )
引數
- path_in_repo (
str) — 倉庫中的相對檔案路徑,例如:"checkpoints/1fec34a/weights.bin" - repo_id (
str) — 要從中刪除檔案的倉庫,例如:"username/custom_transformers" - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - repo_type (
str, optional) — 如果檔案位於資料集或空間中,則設定為"dataset"或"space",如果位於模型中,則設定為None或"model"。預設為None。 - revision (
str, optional) — 要提交的 git 版本。預設為"main"分支的頭。 - commit_message (
str, optional) — 生成的提交的摘要/標題/第一行。預設為f"Delete {path_in_repo} with huggingface_hub"。 - commit_description (
stroptional) — 生成的提交的描述 - create_pr (
boolean, optional) — 是否建立拉取請求 (Pull Request) 與該提交。預設為False。如果未設定revision,則 PR 將針對"main"分支開啟。如果設定了revision且是一個分支,則 PR 將針對此分支開啟。如果設定了revision且不是分支名稱(例如,一個提交 OID),則伺服器將返回一個RevisionNotFoundError。 - parent_commit (
str, 可選) — 父提交的 OID / SHA,作為十六進位制字串。也支援簡寫(前 7 個字元)。如果指定了且create_pr為False,如果revision不指向parent_commit,則提交將失敗。如果指定了且create_pr為True,則將從parent_commit建立拉取請求。指定parent_commit可確保在提交更改之前倉庫未被修改,如果倉庫被併發更新/提交,這尤其有用。
從給定的倉庫中刪除一個檔案。
引發以下錯誤
HTTPError如果 HuggingFace API 返回錯誤ValueError如果某些引數值無效- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。- RevisionNotFoundError 如果找不到要從中下載的版本。
- EntryNotFoundError 如果找不到要下載的檔案。
delete_files
< source >( repo_id: str delete_patterns: list[str] token: Union[bool, str, None] = None repo_type: Optional[str] = None revision: Optional[str] = None commit_message: Optional[str] = None commit_description: Optional[str] = None create_pr: Optional[bool] = None parent_commit: Optional[str] = None )
引數
- repo_id (
str) — 要從中刪除檔案的倉庫,例如:"username/custom_transformers" - delete_patterns (
list[str]) — 要刪除的檔案或資料夾列表。每個字串可以是檔案路徑、資料夾路徑或萬用字元模式。模式是標準萬用字元(globbing 模式),如 此處記錄。模式匹配基於fnmatch。請注意,fnmatch會跨路徑邊界匹配*,這與傳統的 Unix shell globbing 不同。例如:["file.txt", "folder/", "data/*.parquet"] - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請將False傳遞給儲存的令牌。 - repo_type (
str, 可選) — 要從中刪除檔案的倉庫型別。可以是"model"、"dataset"或"space"。預設為"model"。 - revision (
str, 可選) — 要從中提交的 git 版本。預設為"main"分支的 HEAD。 - commit_message (
str, 可選) — 生成的提交摘要(第一行)。預設為f"Delete files using huggingface_hub"。 - commit_description (
str可選) — 生成的提交的描述。 - create_pr (
boolean, 可選) — 是否要使用該提交建立拉取請求。預設為False。如果未設定revision,則 PR 將針對"main"分支開啟。如果設定了revision並且它是一個分支,則 PR 將針對該分支開啟。如果設定了revision且不是分支名稱(例如提交 oid),伺服器將返回RevisionNotFoundError。 - parent_commit (
str, 可選) — 父提交的 OID / SHA,作為十六進位制字串。也支援簡寫(前 7 個字元)。如果指定了且create_pr為False,如果revision不指向parent_commit,則提交將失敗。如果指定了且create_pr為True,則將從parent_commit建立拉取請求。指定parent_commit可確保在提交更改之前倉庫未被修改,如果倉庫被併發更新/提交,這尤其有用。
從 Hub 上的倉庫中刪除檔案。
如果提供了資料夾路徑,則整個資料夾及其包含的所有檔案都將被刪除。
delete_folder
< source >( path_in_repo: str repo_id: str token: Union[bool, str, None] = None repo_type: Optional[str] = None revision: Optional[str] = None commit_message: Optional[str] = None commit_description: Optional[str] = None create_pr: Optional[bool] = None parent_commit: Optional[str] = None )
引數
- path_in_repo (
str) — 倉庫中的相對資料夾路徑,例如:"checkpoints/1fec34a"。 - repo_id (
str) — 要從中刪除檔案的倉庫,例如:"username/custom_transformers" - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請將False傳遞給儲存的令牌。 - repo_type (
str, 可選) — 如果資料夾在模型中,則為None或"model";如果資料夾在資料集或空間中,則設定為"dataset"或"space"。預設為None。 - revision (
str, 可選) — 要從中提交的 git 版本。預設為"main"分支的 HEAD。 - commit_message (
str, 可選) — 生成的提交的摘要/標題/第一行。預設為f"Delete folder {path_in_repo} with huggingface_hub"。 - commit_description (
str可選) — 生成的提交的描述。 - create_pr (
boolean, 可選) — 是否要使用該提交建立拉取請求。預設為False。如果未設定revision,則 PR 將針對"main"分支開啟。如果設定了revision並且它是一個分支,則 PR 將針對該分支開啟。如果設定了revision且不是分支名稱(例如提交 oid),伺服器將返回RevisionNotFoundError。 - parent_commit (
str, 可選) — 父提交的 OID / SHA,作為十六進位制字串。也支援簡寫(前 7 個字元)。如果指定了且create_pr為False,如果revision不指向parent_commit,則提交將失敗。如果指定了且create_pr為True,則將從parent_commit建立拉取請求。指定parent_commit可確保在提交更改之前倉庫未被修改,如果倉庫被併發更新/提交,這尤其有用。
從 Hub 上的倉庫中刪除資料夾。
圍繞 create_commit() 方法的簡單包裝。
delete_inference_endpoint
< source >( name: str namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- name (
str) — 要刪除的推理端點的名稱。 - namespace (
str, optional) — 推理端點所在的名稱空間。預設為當前使用者。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
刪除一個推理端點。
此操作不可逆。如果您不想為推理端點付費,最好使用 pause_inference_endpoint() 暫停它或使用 scale_to_zero_inference_endpoint() 將其規模縮減至零。
為方便起見,您也可以使用 InferenceEndpoint.delete() 刪除推理端點。
delete_repo
< source >( repo_id: str token: Union[str, bool, None] = None repo_type: Optional[str] = None missing_ok: bool = False )
引數
- repo_id (
str) — 由/分隔的名稱空間(使用者或組織)和倉庫名稱。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - repo_type (
str, optional) — 如果上傳到資料集或空間,則設定為"dataset"或"space",如果上傳到模型,則設定為None或"model"。 - missing_ok (
bool, optional, defaults toFalse) — 如果True,則在倉庫不存在時不會引發錯誤。
- RepositoryNotFoundError — 如果找不到要刪除的倉庫且
missing_ok設定為 False(預設值)。
從 HuggingFace Hub 中刪除一個倉庫。警告:此操作不可逆。
delete_scheduled_job
< source >( scheduled_job_id: str namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- scheduled_job_id (
str) — 計劃任務的 ID。 - namespace (
str, optional) — 計劃任務所在的名稱空間。預設為當前使用者的名稱空間。 - token
(Union[bool, str, None], optional) — 一個有效的使用者訪問令牌。如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。設定為False可停用身份驗證。參考: https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
刪除 Hugging Face 基礎架構上的計劃計算任務。
delete_space_secret
< source >( repo_id: str key: str token: Union[bool, str, None] = None )
引數
- repo_id (
str) — 要更新的 Space 的 ID。例如:"bigcode/in-the-stack"。 - key (
str) — 金鑰。例如:"GITHUB_API_KEY"。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
刪除 Space 中的一個金鑰。
金鑰允許在不硬編碼的情況下為 Space 設定金鑰或令牌。有關更多詳細資訊,請參見 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。
delete_space_storage
< source >( repo_id: str token: Union[bool, str, None] = None ) → SpaceRuntime
引數
- repo_id (
str) — 要更新的 Space 的 ID。例如:"open-llm-leaderboard/open_llm_leaderboard"。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Space 的執行時資訊,包括 Space 階段和硬體。
引發
BadRequestError
BadRequestError— 如果 space 沒有持久儲存。
刪除 Space 的持久儲存。
delete_space_variable
< source >( repo_id: str key: str token: Union[bool, str, None] = None )
引數
- repo_id (
str) — 要更新的 Space 的 ID。例如:"bigcode/in-the-stack"。 - key (
str) — 變數鍵。例如:"MODEL_REPO_ID" - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
從 Space 中刪除一個變數。
變數允許在不硬編碼的情況下為 Space 設定環境變數。有關更多詳細資訊,請參見 https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
delete_tag
< source >( repo_id: str tag: str token: Union[bool, str, None] = None repo_type: Optional[str] = None )
引數
- repo_id (
str) — 將要刪除標籤的倉庫。示例:"user/my-cool-model"。 - tag (
str) — 要刪除的標籤的名稱。 - token (
boolorstr, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - repo_type (
str, optional) — 如果標記資料集或空間,請設定為"dataset"或"space",如果標記模型,則設定為None或"model"。預設為None。
- RepositoryNotFoundError — 如果倉庫未找到(錯誤 404):repo_id/repo_type 錯誤,私有但未經驗證或倉庫不存在。
- RevisionNotFoundError — 如果找不到標籤。
從 Hub 上的倉庫中刪除標籤。
delete_webhook
< source >( webhook_id: str token: Union[bool, str, None] = None ) → None
引數
- webhook_id (
str) — 要刪除的 webhook 的唯一識別符號。 - token (
boolorstr, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
無
刪除 webhook。
disable_webhook
< source >( webhook_id: str token: Union[bool, str, None] = None ) → WebhookInfo
引數
- webhook_id (
str) — 要停用的 webhook 的唯一識別符號。 - token (
boolorstr, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
有關已停用的 webhook 的資訊。
停用 webhook(使其變為“已停用”)。
示例
>>> from huggingface_hub import disable_webhook
>>> disabled_webhook = disable_webhook("654bbbc16f2ec14d77f109cc")
>>> disabled_webhook
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
jon=None,
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
domains=["repo", "discussion"],
secret="my-secret",
disabled=True,
)duplicate_space
< source >( from_id: str to_id: Optional[str] = None private: Optional[bool] = None token: Union[bool, str, None] = None exist_ok: bool = False hardware: Optional[SpaceHardware] = None storage: Optional[SpaceStorage] = None sleep_time: Optional[int] = None secrets: Optional[list[dict[str, str]]] = None variables: Optional[list[dict[str, str]]] = None ) → RepoUrl
引數
- from_id (
str) — 要複製的 Space 的 ID。示例:"pharma/CLIP-Interrogator"。 - to_id (
str, optional) — 新 Space 的 ID。示例:"dog/CLIP-Interrogator"。如果未提供,新 Space 將與原始 Space 同名,但在你的賬戶下。 - private (
bool, optional) — 新 Space 是否應設為私有。預設為與原始 Space 相同的隱私設定。 - token (
boolorstr, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - exist_ok (
bool, optional, defaults toFalse) — 如果True,則如果倉庫已存在,則不引發錯誤。 - hardware (
SpaceHardwareorstr, optional) — 硬體選擇。示例:"t4-medium"。有關完整列表,請參閱 SpaceHardware。 - storage (
SpaceStorageorstr, optional) — 持久儲存層選擇。示例:"small"。有關完整列表,請參閱 SpaceStorage。 - sleep_time (
int, optional) — 在 Space 睡眠前等待的不活動秒數。如果不想讓 Space 睡眠,請設定為-1(升級硬體後的預設行為)。對於免費硬體,您無法配置睡眠時間(固定為 48 小時無活動)。有關更多詳細資訊,請參閱 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。 - secrets (
list[dict[str, str]], optional) — 要在您的 Space 中設定的一系列 secret 鍵。每個項的格式為{"key": ..., "value": ..., "description": ...},其中 description 是可選的。有關更多詳細資訊,請參閱 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。 - variables (
list[dict[str, str]], optional) — 要在您的 Space 中設定的一系列公共環境變數。每個項的格式為{"key": ..., "value": ..., "description": ...},其中 description 是可選的。有關更多詳細資訊,請參閱 https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables。
返回
新建立的倉庫的 URL。值是 str 的子類,包含 endpoint、repo_type 和 repo_id 等屬性。
引發
RepositoryNotFoundError 或 HfHubHTTPError
- RepositoryNotFoundError — 如果
from_id或to_id中的一個找不到。這可能是因為它不存在,或者因為它被設定為private而您沒有訪問許可權。 HfHubHTTPError— 如果 HuggingFace API 返回錯誤
複製 Space。
以程式設計方式複製 Space。新 Space 將在您的賬戶下建立,並且狀態將與原始 Space 相同(執行中或暫停)。您可以複製任何狀態的 Space。
示例
>>> from huggingface_hub import duplicate_space
# Duplicate a Space to your account
>>> duplicate_space("multimodalart/dreambooth-training")
RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)
# Can set custom destination id and visibility flag.
>>> duplicate_space("multimodalart/dreambooth-training", to_id="my-dreambooth", private=True)
RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...)edit_discussion_comment
< source >( repo_id: str discussion_num: int comment_id: str new_content: str token: Union[bool, str, None] = None repo_type: Optional[str] = None ) → DiscussionComment
引數
- repo_id (
str) — 一個由/分隔的使用者或組織名稱空間和倉庫名稱。 - discussion_num (
int) — 討論或拉取請求的編號。必須是嚴格正整數。 - comment_id (
str) — 要編輯的評論的 ID。 - new_content (
str) — 評論的新內容。評論支援 markdown 格式。 - repo_type (
str, optional) — 如果是上傳到資料集或空間,則設定為"dataset"或"space",如果是上傳到模型,則設定為None或"model"。預設為None。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
已編輯的評論
編輯討論/拉取請求中的評論。
引發以下錯誤
HTTPError如果 HuggingFace API 返回錯誤ValueError如果某些引數值無效- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。
enable_webhook
< source >( webhook_id: str token: Union[bool, str, None] = None ) → WebhookInfo
引數
- webhook_id (
str) — 要啟用的 Webhook 的唯一識別符號。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
有關已啟用 Webhook 的資訊。
啟用 Webhook(使其“啟用”)。
示例
>>> from huggingface_hub import enable_webhook
>>> enabled_webhook = enable_webhook("654bbbc16f2ec14d77f109cc")
>>> enabled_webhook
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
job=None,
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
domains=["repo", "discussion"],
secret="my-secret",
disabled=False,
)fetch_job_logs
< source >( job_id: str namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- job_id (
str) — Job 的 ID。 - namespace (
str, optional) — Job 執行的名稱空間。預設為當前使用者的名稱空間。 - token (
Union[bool, str, None], optional) — 一個有效的使用者訪問令牌。如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。設定為False以停用身份驗證。參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
從 Hugging Face 基礎設施上的計算 Job 中獲取所有日誌。
fetch_job_metrics
< source >( job_id: str namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- job_id (
str) — Job 的 ID。 - namespace (
str, optional) — Job 執行的名稱空間。預設為當前使用者的名稱空間。 - token (
Union[bool, str, None], optional) — 一個有效的使用者訪問令牌。如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。設定為False以停用身份驗證。參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
從 Hugging Face 基礎設施上的計算 Job 中獲取所有即時指標。
示例
>>> from huggingface_hub import fetch_job_metrics, run_job
>>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], flavor="a10g-small")
>>> for metrics in fetch_job_metrics(job_id=job.id):
... print(metrics)
{
"cpu_usage_pct": 0,
"cpu_millicores": 3500,
"memory_used_bytes": 1306624,
"memory_total_bytes": 15032385536,
"rx_bps": 0,
"tx_bps": 0,
"gpus": {
"882fa930": {
"utilization": 0,
"memory_used_bytes": 0,
"memory_total_bytes": 22836000000
}
},
"replica": "57vr7"
}file_exists
< source >( repo_id: str filename: str repo_type: Optional[str] = None revision: Optional[str] = None token: Union[str, bool, None] = None )
引數
- repo_id (
str) — 一個由/分隔的使用者或組織名稱空間和倉庫名稱。 - filename (
str) — 要檢查的檔名,例如:"config.json" - repo_type (
str, optional) — 如果是從資料集或空間獲取倉庫資訊,則設定為"dataset"或"space",如果是從模型獲取倉庫資訊,則設定為None或"model"。預設為None。 - revision (
str, optional) — 要從中獲取資訊的倉庫的修訂版本。預設為"main"分支。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
檢查檔案是否存在於 Hugging Face Hub 的倉庫中。
get_collection
< source >( collection_slug: str token: Union[bool, str, None] = None )
引數
- collection_slug (
str) — Hub 集合的 slug。示例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
獲取 Hub 上 Collection 的資訊。
返回: Collection
示例
>>> from huggingface_hub import get_collection
>>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
>>> collection.title
'Recent models'
>>> len(collection.items)
37
>>> collection.items[0]
CollectionItem(
item_object_id='651446103cd773a050bf64c2',
item_id='TheBloke/U-Amethyst-20B-AWQ',
item_type='model',
position=88,
note=None
)列出所有有效的 dataset 標籤,作為巢狀名稱空間物件。
get_discussion_details
< source >( repo_id: str discussion_num: int repo_type: Optional[str] = None token: Union[bool, str, None] = None )
引數
- repo_id (
str) — 由/分隔的使用者或組織名稱空間以及倉庫名稱。 - discussion_num (
int) — 討論或拉取請求的編號。必須是嚴格正整數。 - repo_type (
str, optional) — 設定為"dataset"或"space"以上傳到資料集或空間,如果上傳到模型,則設定為None或"model"。預設為None。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌 (字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
從 Hub 獲取討論/拉取請求的詳細資訊。
引發以下錯誤
HTTPError如果 HuggingFace API 返回錯誤ValueError如果某些引數值無效- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。
get_full_repo_name
< source >( model_id: str organization: Optional[str] = None token: Union[bool, str, None] = None ) → str
引數
- model_id (
str) — 模型的名稱。 - organization (
str, optional) — 如果傳入,倉庫名稱將位於組織名稱空間而不是使用者名稱稱空間下。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌 (字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
字串
如果在沒有傳入 organization 的情況下,則倉庫名稱為使用者名稱稱空間({username}/{model_id}),否則為組織名稱空間({organization}/{model_id})。
返回給定模型 ID 和可選組織的倉庫名稱。
get_hf_file_metadata
< source >( url: str token: Union[bool, str, None] = None timeout: Optional[float] = 10 )
引數
- url (
str) — 檔案 URL,例如由 hf_hub_url() 返回。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌 (字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - timeout (
float, optional, defaults to 10) — 在放棄之前等待伺服器傳送元資料的秒數。
為給定的 URL 獲取 Hub 上版本化檔案的元資料。
get_inference_endpoint
< source >( name: str namespace: Optional[str] = None token: Union[bool, str, None] = None ) → InferenceEndpoint
引數
- name (
str) — 要檢索資訊的推理端點的名稱。 - namespace (
str, optional) — 推理端點所在的名稱空間。預設為當前使用者。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌 (字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
有關所請求的推理端點的資訊。
獲取有關推理端點的資訊。
示例
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> endpoint = api.get_inference_endpoint("my-text-to-image")
>>> endpoint
InferenceEndpoint(name='my-text-to-image', ...)
# Get status
>>> endpoint.status
'running'
>>> endpoint.url
'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
# Run inference
>>> endpoint.client.text_to_image(...)列出所有有效的模型標籤作為巢狀名稱空間物件。
get_organization_overview
< source >( organization: str token: Union[bool, str, None] = None ) → Organization
引數
- organization (
str) — 要獲取其概述的組織的名稱。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌 (字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
組織
一個 Organization 物件,包含組織的概述。
引發
HTTPError
HTTPError— HTTP 404 如果組織在 Hub 上不存在。
獲取 Hub 上組織的概述。
get_paths_info
< source >( repo_id: str paths: Union[list[str], str] expand: bool = False revision: Optional[str] = None repo_type: Optional[str] = None token: Union[str, bool, None] = None ) → list[Union[RepoFile, RepoFolder]]
引數
- repo_id (
str) — 由/分隔的使用者或組織名稱空間以及倉庫名稱。 - paths (
Union[list[str], str], optional) — 要獲取資訊的路徑。如果路徑不存在,則會忽略該路徑而不會引發異常。 - expand (
bool, optional, defaults toFalse) — 是否獲取路徑的更多資訊(例如,上次提交和檔案的安全掃描結果)。此操作對伺服器的開銷更大,因此每頁只返回 50 個結果(而不是 1000 個)。由於分頁在huggingface_hub中已實現,因此對您來說是透明的,除了獲取結果所需的時間。 - revision (
str, optional) — 要從中獲取資訊的儲存庫修訂版本。預設為"main"分支。 - repo_type (
str, optional) — 要從中獲取資訊的儲存庫型別 ("model","dataset"或"space")。預設為"model"。 - token (
boolorstr, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是身份驗證的推薦方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
list[Union[RepoFile, RepoFolder]]
關於路徑的資訊,表示為 RepoFile 和 RepoFolder 物件列表。
- RepositoryNotFoundError — 如果倉庫未找到(錯誤 404):repo_id/repo_type 錯誤,私有但未經驗證或倉庫不存在。
- RevisionNotFoundError — 如果在儲存庫中找不到 revision(錯誤 404)。
獲取有關儲存庫路徑的資訊。
示例
>>> from huggingface_hub import get_paths_info
>>> paths_info = get_paths_info("allenai/c4", ["README.md", "en"], repo_type="dataset")
>>> paths_info
[
RepoFile(path='README.md', size=2379, blob_id='f84cb4c97182890fc1dbdeaf1a6a468fd27b4fff', lfs=None, last_commit=None, security=None),
RepoFolder(path='en', tree_id='dc943c4c40f53d02b31ced1defa7e5f438d5862e', last_commit=None)
]get_repo_discussions
< source >( repo_id: str author: Optional[str] = None discussion_type: Optional[constants.DiscussionTypeFilter] = None discussion_status: Optional[constants.DiscussionStatusFilter] = None repo_type: Optional[str] = None token: Union[bool, str, None] = None ) → Iterator[Discussion]
引數
- repo_id (
str) — 名稱空間(使用者或組織)和一個儲存庫名稱,用/分隔。 - author (
str, optional) — 傳入一個值以按討論作者進行篩選。None表示不進行篩選。預設為None。 - discussion_type (
str, optional) — 設定為"pull_request"以僅獲取拉取請求,"discussion"以僅獲取討論。設定為"all"或None以獲取兩者。預設為None。 - discussion_status (
str, optional) — 設定為"open"(或"closed")以僅獲取開啟(或關閉)的討論。設定為"all"或None以獲取兩者。預設為None。 - repo_type (
str, optional) — 設定為"dataset"或"space"以從資料集或空間獲取,None或"model"以從模型獲取。預設為None。 - token (
boolorstr, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是身份驗證的推薦方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Iterator[Discussion]
Discussion 物件的迭代器。
獲取給定儲存庫的討論和拉取請求。
示例
get_safetensors_metadata
< source >( repo_id: str repo_type: Optional[str] = None revision: Optional[str] = None token: Union[bool, str, None] = None ) → SafetensorsRepoMetadata
引數
- repo_id (
str) — 使用者或組織名稱,用/分隔的儲存庫名稱。 - repo_type (
str, optional) — 如果檔案在資料集中或空間中,則設定為"dataset"或"space",如果在模型中,則設定為None或"model"。預設為None。 - revision (
str, optional) — 要從中獲取檔案的 git 修訂版本。可以是分支名稱、標籤或提交雜湊。預設為"main"分支的頭部。 - token (
boolorstr, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是身份驗證的推薦方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
SafetensorsRepoMetadata
與 safetensors 儲存庫相關的資訊。
引發
NotASafetensorsRepoError 或 SafetensorsParsingError
NotASafetensorsRepoError— 如果儲存庫不是 safetensors 儲存庫,即不包含model.safetensors或model.safetensors.index.json檔案。SafetensorsParsingError— 如果 safetensors 檔案頭無法正確解析。
解析 Hub 上 safetensors 儲存庫的元資料。
我們首先檢查儲存庫是否包含單個 safetensors 檔案或分片 safetensors 儲存庫。如果是單個 safetensors 檔案,我們從該檔案中解析元資料。如果是分片 safetensors 儲存庫,我們從索引檔案中解析元資料,然後從每個分片解析元資料。
要從單個 safetensors 檔案解析元資料,請使用 parse_safetensors_file_metadata()。
有關 safetensors 格式的更多詳細資訊,請檢視 https://huggingface.co/docs/safetensors/index#format。
示例
# Parse repo with single weights file
>>> metadata = get_safetensors_metadata("bigscience/bloomz-560m")
>>> metadata
SafetensorsRepoMetadata(
metadata=None,
sharded=False,
weight_map={'h.0.input_layernorm.bias': 'model.safetensors', ...},
files_metadata={'model.safetensors': SafetensorsFileMetadata(...)}
)
>>> metadata.files_metadata["model.safetensors"].metadata
{'format': 'pt'}
# Parse repo with sharded model
>>> metadata = get_safetensors_metadata("bigscience/bloom")
Parse safetensors files: 100%|██████████████████████████████████████████| 72/72 [00:12<00:00, 5.78it/s]
>>> metadata
SafetensorsRepoMetadata(metadata={'total_size': 352494542848}, sharded=True, weight_map={...}, files_metadata={...})
>>> len(metadata.files_metadata)
72 # All safetensors files have been fetched
# Parse repo with sharded model
>>> get_safetensors_metadata("runwayml/stable-diffusion-v1-5")
NotASafetensorsRepoError: 'runwayml/stable-diffusion-v1-5' is not a safetensors repo. Couldn't find 'model.safetensors.index.json' or 'model.safetensors' files.get_space_runtime
< source >( repo_id: str token: Union[bool, str, None] = None ) → SpaceRuntime
引數
- repo_id (
str) — 要更新的儲存庫 ID。例如:"bigcode/in-the-stack"。 - token (
boolorstr, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是身份驗證的推薦方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Space 的執行時資訊,包括 Space 階段和硬體。
獲取 Space 的執行時資訊。
get_space_variables
< source >( repo_id: str token: Union[bool, str, None] = None )
引數
- repo_id (
str) — 要查詢的儲存庫 ID。例如:"bigcode/in-the-stack"。 - token (
boolorstr, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是身份驗證的推薦方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
獲取 Space 的所有變數。
變數允許在不硬編碼的情況下為 Space 設定環境變數。有關更多詳細資訊,請參見 https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
get_user_overview
< source >( username: str token: Union[bool, str, None] = None ) → User
引數
- username (
str) — 要獲取概覽的使用者使用者名稱。 - token (
boolorstr, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是身份驗證的推薦方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
User
一個包含使用者概覽的 User 物件。
引發
HfHubHTTPError
HfHubHTTPError— HTTP 404 如果使用者在 Hub 上不存在。
獲取使用者在 Hub 上的概覽。
get_webhook
< source >( webhook_id: str token: Union[bool, str, None] = None ) → WebhookInfo
引數
- webhook_id (
str) — 要獲取的網路鉤子的唯一識別符號。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳入False。
返回
關於此網路鉤子的資訊。
透過 ID 獲取網路鉤子。
示例
>>> from huggingface_hub import get_webhook
>>> webhook = get_webhook("654bbbc16f2ec14d77f109cc")
>>> print(webhook)
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
job=None,
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
secret="my-secret",
domains=["repo", "discussion"],
disabled=False,
)grant_access
< source >( repo_id: str user: str repo_type: Optional[str] = None token: Union[bool, str, None] = None )
引數
- repo_id (
str) — 要授予訪問許可權的倉庫 ID。 - user (
str) — 要授予訪問許可權的使用者的使用者名稱。 - repo_type (
str, optional) — 要授予訪問許可權的倉庫型別。必須是model、dataset或space之一。預設為model。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳入False。
引發
HfHubHTTPError
HfHubHTTPError— 如果倉庫未受保護,則為 HTTP 400。HfHubHTTPError— 如果使用者已擁有此倉庫的訪問許可權,則為 HTTP 400。HfHubHTTPError— 如果您只有倉庫的只讀訪問許可權,則為 HTTP 403。如果您的組織(倉庫所屬的組織)沒有write或admin角色,或者您傳遞了readtoken,則可能出現這種情況。HfHubHTTPError— 如果使用者不存在於 Hub 上,則為 HTTP 404。
為給定受限倉庫授予使用者訪問許可權。
授予訪問許可權不需要使用者自行傳送訪問請求。使用者將被自動新增到接受列表,這意味著他們可以下載檔案。您可以使用 cancel_access_request() 或 reject_access_request() 隨時撤銷已授予的訪問許可權。
有關受保護倉庫的更多資訊,請參閱 https://huggingface.co/docs/hub/models-gated。
hf_hub_download
< source >( repo_id: str filename: str subfolder: Optional[str] = None repo_type: Optional[str] = None revision: Optional[str] = None cache_dir: Union[str, Path, None] = None local_dir: Union[str, Path, None] = None force_download: bool = False etag_timeout: float = 10 token: Union[bool, str, None] = None local_files_only: bool = False tqdm_class: Optional[type[base_tqdm]] = None dry_run: bool = False ) → str 或 DryRunFileInfo
引數
- repo_id (
str) — 使用者名稱或組織名稱,後跟/,然後是倉庫名稱。 - filename (
str) — 倉庫中的檔名。 - subfolder (
str, optional) — 倉庫內某個資料夾的可選值。 - repo_type (
str, optional) — 如果從資料集或空間下載,則設定為"dataset"或"space",如果從模型下載,則設定為None或"model"。預設為None。 - revision (
str, optional) — 可以是分支名稱、標籤或提交雜湊值的 Git 修訂 ID。 - cache_dir (
str,Path, optional) — 快取檔案儲存的目錄路徑。 - local_dir (
str或Path, optional) — 如果提供了此引數,下載的檔案將放置在此目錄中。 - force_download (
bool, optional, 預設為False) — 檔案是否應被下載,即使它已存在於本地快取中。 - etag_timeout (
float, optional, 預設為10) — 獲取 ETag 時,伺服器傳送資料前的等待秒數,然後放棄,該值會傳遞給httpx.request。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳入False。 - local_files_only (
bool, optional, 預設為False) — 如果為True,則避免下載檔案,並返回本地快取檔案的路徑(如果存在)。 - tqdm_class (
tqdm, optional) — 如果提供,將覆蓋預設的進度條行為。傳入的引數必須繼承自tqdm.auto.tqdm或至少模仿其行為。預設為自定義的 HF 進度條,可以透過設定HF_HUB_DISABLE_PROGRESS_BARS環境變數來停用。 - dry_run (
bool, optional, 預設為False) — 如果為True,則執行試執行,而不實際下載檔案。返回一個 DryRunFileInfo 物件,其中包含有關將要下載的內容的資訊。
返回
str 或 DryRunFileInfo
- 如果
dry_run=False:檔案的本地路徑,或者在網路斷開的情況下,磁碟上快取的檔案的最新版本。 - 如果
dry_run=True:一個包含下載資訊的 DryRunFileInfo 物件。
引發
RepositoryNotFoundError 或 RevisionNotFoundError 或 ~utils.RemoteEntryNotFoundError 或 LocalEntryNotFoundError 或 EnvironmentError 或 OSError 或 ValueError
- RepositoryNotFoundError — 如果找不到要下載的儲存庫。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。 - RevisionNotFoundError — 如果找不到要下載的修訂版本。
~utils.RemoteEntryNotFoundError— 如果找不到要下載的檔案。- LocalEntryNotFoundError — 如果網路被停用或不可用且在快取中找不到檔案。
EnvironmentError— 如果token=True但找不到令牌。OSError— 如果無法確定 ETag。ValueError— 如果某些引數值無效。
如果檔案尚未存在於本地快取中,則下載給定檔案。
新的快取檔案佈局如下所示
- 快取目錄包含每個 repo_id 的一個子資料夾(按 repo 型別命名)
- 在每個倉庫資料夾內部
- refs 是最新已知修訂版本 => commit_hash 對的列表
- blobs 包含實際的檔案 blob(根據它們是 LFS 檔案還是非 LFS 檔案,由它們的 git-sha 或 sha256 標識)
- snapshots 包含每個 commit 的一個子資料夾,每個“commit”包含在該特定 commit 中解析的檔案子集。每個檔名都是指向該特定 commit 的 blob 的符號連結。
[ 96] .
└── [ 160] models--julien-c--EsperBERTo-small
├── [ 160] blobs
│ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
│ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e
│ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812
├── [ 96] refs
│ └── [ 40] main
└── [ 128] snapshots
├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f
│ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812
│ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd
└── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48
├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e
└── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd如果提供了 local_dir,則倉庫的檔案結構將在此位置複製。使用此選項時,cache_dir 將不會被使用,並且將在 local_dir 的根目錄建立一個 .cache/huggingface/ 資料夾來儲存與下載檔案相關的某些元資料。雖然此機制不如主快取系統健壯,但它針對定期拉取儲存庫的最新版本進行了最佳化。
hide_discussion_comment
< source >( repo_id: str discussion_num: int comment_id: str token: Union[bool, str, None] = None repo_type: Optional[str] = None ) → DiscussionComment
引數
- repo_id (
str) — 儲存庫的名稱空間(使用者或組織)以及由/分隔的儲存庫名稱。 - discussion_num (
int) — 討論或拉取請求的編號。必須是嚴格正整數。 - comment_id (
str) — 要編輯的評論 ID。 - repo_type (
str, optional) — 設定為"dataset"或"space"表示上傳到資料集或空間,設定為None或"model"表示上傳到模型。預設為None。 - token (
bool或str, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
隱藏的評論
隱藏討論/拉取請求中的評論。
隱藏的評論內容將無法再檢索。隱藏評論是不可逆的。
引發以下錯誤
HTTPError如果 HuggingFace API 返回錯誤ValueError如果某些引數值無效- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。
inspect_job
< source >( job_id: str namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- job_id (
str) — 作業 ID。 - namespace (
str, optional) — 作業執行的名稱空間。預設為當前使用者的名稱空間。 - token (
Union[bool, str, None], optional) — 一個有效的使用者訪問令牌。如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。設定為False以停用身份驗證。請參閱:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
檢查 Hugging Face 基礎架構上的計算作業。
示例
>>> from huggingface_hub import inspect_job, run_job
>>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
>>> inspect_job(job.id)
JobInfo(
id='68780d00bbe36d38803f645f',
created_at=datetime.datetime(2025, 7, 16, 20, 35, 12, 808000, tzinfo=datetime.timezone.utc),
docker_image='python:3.12',
space_id=None,
command=['python', '-c', "print('Hello from HF compute!')"],
arguments=[],
environment={},
secrets={},
flavor='cpu-basic',
status=JobStatus(stage='RUNNING', message=None)
)inspect_scheduled_job
< source >( scheduled_job_id: str namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- scheduled_job_id (
str) — 計劃作業的 ID。 - namespace (
str, optional) — 計劃作業所在的名稱空間。預設為當前使用者的名稱空間。 - token (
Union[bool, str, None], optional) — 一個有效的使用者訪問令牌。如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。設定為False以停用身份驗證。請參閱:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
檢查 Hugging Face 基礎架構上的計劃計算作業。
list_accepted_access_requests
< source >( repo_id: str repo_type: Optional[str] = None token: Union[bool, str, None] = None ) → Iterable[AccessRequest]
引數
- repo_id (
str) — 用於獲取訪問請求的儲存庫 ID。 - repo_type (
str, optional) — 要獲取訪問請求的儲存庫的型別。必須是model、dataset或space之一。預設為model。 - token (
bool或str, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Iterable[AccessRequest]
一個 AccessRequest 物件的迭代器。每個物件都包含 username、email、status 和 timestamp 屬性。如果受限制的儲存庫有自定義表單,則 fields 屬性將填充使用者的答案。
引發
HfHubHTTPError
HfHubHTTPError— 如果倉庫未受保護,則為 HTTP 400。HfHubHTTPError— 如果您只有倉庫的只讀訪問許可權,則為 HTTP 403。如果您的組織(倉庫所屬的組織)沒有write或admin角色,或者您傳遞了readtoken,則可能出現這種情況。
獲取給定受限制儲存庫的已接受訪問請求。
接受的請求意味著使用者已請求訪問該儲存庫,並且請求已被接受。使用者可以下載該儲存庫的任何檔案。如果批准模式是自動的,則此列表預設應包含所有請求。可以隨時使用 cancel_access_request() 和 reject_access_request() 取消或拒絕已接受的請求。已取消的請求將返回到待處理列表,而被拒絕的請求將轉到已拒絕列表。在這兩種情況下,使用者都將失去對儲存庫的訪問許可權。
有關受保護倉庫的更多資訊,請參閱 https://huggingface.co/docs/hub/models-gated。
示例
>>> from huggingface_hub import list_accepted_access_requests
>>> requests = list(list_accepted_access_requests("meta-llama/Llama-2-7b"))
>>> len(requests)
411
>>> requests[0]
[
AccessRequest(
username='clem',
fullname='Clem 🤗',
email='***',
timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
status='accepted',
fields=None,
),
...
]list_collections
< source >( owner: Union[list[str], str, None] = None item: Union[list[str], str, None] = None sort: Optional[CollectionSort_T] = None limit: Optional[int] = None token: Union[bool, str, None] = None ) → Iterable[Collection]
引數
- owner (
list[str]或str, optional) — 按所有者的使用者名稱進行篩選。 - item (
list[str]或str, optional) — 篩選包含特定專案的集合。例如:"models/teknium/OpenHermes-2.5-Mistral-7B"、"datasets/squad"或"papers/2311.12983"。 - sort (
Literal["lastModified", "trending", "upvotes"], optional) — 按最後修改時間、趨勢或點贊數對集合進行排序。 - limit (
int, optional) — 要返回的集合的最大數量。 - token (
bool或str, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Iterable[Collection]
一個 Collection 物件的迭代器。
根據一些過濾器列出 Huggingface Hub 上的集合。
列出集合時,每個集合的專案列表最多截斷為 4 項。要檢索集合中的所有專案,您必須使用 get_collection()。
list_daily_papers
< source >( date: Optional[str] = None token: Union[bool, str, None] = None week: Optional[str] = None month: Optional[str] = None submitter: Optional[str] = None sort: Optional[DailyPapersSort_T] = None p: Optional[int] = None limit: Optional[int] = None ) → Iterable[PaperInfo]
引數
- date (
str, optional) — Date in ISO format (YYYY-MM-DD) for which to fetch daily papers. Defaults to most recent ones. - token (Union[bool, str, None], optional) — A valid user access token (string). Defaults to the locally saved token. To disable authentication, pass
False. - week (
str, optional) — Week in ISO format (YYYY-Www) for which to fetch daily papers. Example,2025-W09. - month (
str, optional) — Month in ISO format (YYYY-MM) for which to fetch daily papers. Example,2025-02. - submitter (
str, optional) — Username of the submitter to filter daily papers. - sort (
Optional[DailyPapersSort_T], optional) — Sort order for the daily papers. Defaults to"publishedAt" - p (
int, optional) — Page number for pagination. Defaults to 0. - limit (
int, optional) — Limit of papers to fetch. Defaults to 50.
返回
Iterable[PaperInfo]
an iterable of huggingface_hub.hf_api.PaperInfo objects.
List the daily papers published on a given date on the Hugging Face Hub.
list_datasets
< source >( filter: Union[str, Iterable[str], None] = None author: Optional[str] = None benchmark: Optional[Union[Literal[True], Literal['official'], str]] = None dataset_name: Optional[str] = None gated: Optional[bool] = None language_creators: Optional[Union[str, list[str]]] = None language: Optional[Union[str, list[str]]] = None multilinguality: Optional[Union[str, list[str]]] = None size_categories: Optional[Union[str, list[str]]] = None task_categories: Optional[Union[str, list[str]]] = None task_ids: Optional[Union[str, list[str]]] = None search: Optional[str] = None sort: Optional[DatasetSort_T] = None direction: Optional[Literal[-1]] = None limit: Optional[int] = None expand: Optional[list[ExpandDatasetProperty_T]] = None full: Optional[bool] = None token: Union[bool, str, None] = None ) → Iterable[DatasetInfo]
引數
- filter (
strorIterable[str], optional) — A string or list of string to filter datasets on the hub. - author (
str, optional) — A string which identify the author of the returned datasets. - benchmark (
True,"official",str, optional) — Filter datasets by benchmark. Can beTrueor"official"to return official benchmark datasets. For future-compatibility, can also be a string representing the benchmark name (currently only “official” is supported). - dataset_name (
str, optional) — A string or list of strings that can be used to identify datasets on the Hub by its name, such asSQACorwikineural - gated (
bool, optional) — A boolean to filter datasets on the Hub that are gated or not. By default, all datasets are returned. Ifgated=Trueis passed, only gated datasets are returned. Ifgated=Falseis passed, only non-gated datasets are returned. - language_creators (
strorList, optional) — A string or list of strings that can be used to identify datasets on the Hub with how the data was curated, such ascrowdsourcedormachine_generated. - language (
strorList, optional) — A string or list of strings representing a two-character language to filter datasets by on the Hub. - multilinguality (
strorList, optional) — A string or list of strings representing a filter for datasets that contain multiple languages. - size_categories (
strorList, optional) — A string or list of strings that can be used to identify datasets on the Hub by the size of the dataset such as100K<n<1Mor1M<n<10M. - tags (
strorList, optional) — Deprecated. Pass tags infilterto filter datasets by tags. - task_categories (
strorList, optional) — A string or list of strings that can be used to identify datasets on the Hub by the designed task, such asaudio_classificationornamed_entity_recognition. - task_ids (
strorList, optional) — A string or list of strings that can be used to identify datasets on the Hub by the specific task such asspeech_emotion_recognitionorparaphrase. - search (
str, optional) — A string that will be contained in the returned datasets. - sort (
DatasetSort_T, optional) — The key with which to sort the resulting datasets. Possible values are “created_at”, “downloads”, “last_modified”, “likes” and “trending_score”. - direction (
Literal[-1]orint, optional) — Deprecated. This parameter is not used and will be removed in version 1.5. - limit (
int, optional) — The limit on the number of datasets fetched. Leaving this option toNonefetches all datasets. - expand (
list[ExpandDatasetProperty_T], optional) — List properties to return in the response. When used, only the properties in the list will be returned. This parameter cannot be used iffullis passed. Possible values are"author","cardData","citation","createdAt","disabled","description","downloads","downloadsAllTime","gated","lastModified","likes","paperswithcode_id","private","siblings","sha","tags","trendingScore","usedStorage", and"resourceGroup". - full (
bool, optional) — Whether to fetch all dataset data, including thelast_modified, thecard_dataand the files. Can contain useful information such as the PapersWithCode ID. - token (
boolorstr, optional) — A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, passFalse.
返回
Iterable[DatasetInfo]
an iterable of huggingface_hub.hf_api.DatasetInfo objects.
List datasets hosted on the Huggingface Hub, given some filters.
Example usage with the filter argument
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# List all datasets
>>> api.list_datasets()
# List only the text classification datasets
>>> api.list_datasets(filter="task_categories:text-classification")
# List only the datasets in russian for language modeling
>>> api.list_datasets(
... filter=("language:ru", "task_ids:language-modeling")
... )
# List FiftyOne datasets (identified by the tag "fiftyone" in dataset card)
>>> api.list_datasets(tags="fiftyone")list_inference_catalog
< source >( token: Union[bool, str, None] = None ) → Liststr
引數
- token (
boolorstr, optional) — A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
返回
Liststr
A list of model IDs available in the catalog.
List models available in the Hugging Face Inference Catalog.
推理目錄的目的是提供一個精選的模型列表,這些模型經過了推理最佳化,並且已經測試了預設配置。有關目錄中可用模型的列表,請參閱 https://endpoints.huggingface.co/catalog。
Use create_inference_endpoint_from_catalog() to deploy a model from the catalog.
list_inference_catalogis experimental. Its API is subject to change in the future. Please provide feedback if you have any suggestions or requests.
list_inference_endpoints
< source >( namespace: Optional[str] = None token: Union[bool, str, None] = None ) → listInferenceEndpoint
引數
- namespace (
str, optional) — The namespace to list endpoints for. Defaults to the current user. Set to"*"to list all endpoints from all namespaces (i.e. personal namespace and all orgs the user belongs to). - token (
boolorstr, optional) — A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, passFalse.
返回
A list of all inference endpoints for the given namespace.
Lists all inference endpoints for the given namespace.
list_jobs
< source >( timeout: Optional[int] = None namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- timeout (
float, optional) — Whether to set a timeout for the request to the Hub. - namespace (
str, optional) — The namespace from where it lists the jobs. Defaults to the current user’s namespace. - token
(Union[bool, str, None], optional) — A valid user access token. If not provided, the locally saved token will be used, which is the recommended authentication method. Set toFalseto disable authentication. Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication.
List compute Jobs on Hugging Face infrastructure.
list_jobs_hardware
< source >( token: Union[bool, str, None] = None ) → list[JobHardware]
返回
list[JobHardware]
A list of available hardware configurations.
List available hardware options for Jobs on Hugging Face infrastructure.
示例
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> hardware_list = api.list_jobs_hardware()
>>> hardware_list[0]
JobHardware(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', accelerator=None, unit_cost_micro_usd=167, unit_cost_usd=0.000167, unit_label='minute')
>>> hardware_list[0].name
'cpu-basic'
# Filter GPU options
>>> gpu_hardware = [hw for hw in hardware_list if hw.accelerator is not None]
>>> gpu_hardware[0].accelerator.model
'T4'list_lfs_files
< source >( repo_id: str repo_type: Optional[str] = None token: Union[bool, str, None] = None ) → Iterable[LFSFileInfo]
引數
- repo_id (
str) — The repository for which you are listing LFS files. - repo_type (
str, optional) — Type of repository. Set to"dataset"or"space"if listing from a dataset or space,Noneor"model"if listing from a model. Default isNone. - token (
boolorstr, optional) — A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, passFalse.
返回
Iterable[LFSFileInfo]
An iterator of LFSFileInfo objects.
List all LFS files in a repo on the Hub.
This is primarily useful to count how much storage a repo is using and to eventually clean up large files with permanently_delete_lfs_files(). Note that this would be a permanent action that will affect all commits referencing this deleted files and that cannot be undone.
示例
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> lfs_files = api.list_lfs_files("username/my-cool-repo")
# Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
# e.g. select only LFS files in the "checkpoints" folder
>>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
# Permanently delete LFS files
>>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)list_liked_repos
< source >( user: Optional[str] = None token: Union[bool, str, None] = None ) → UserLikes
引數
- user (
str, optional) — Name of the user for which you want to fetch the likes. - token (
boolorstr, optional) — A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, passFalse.
返回
object containing the user name and 3 lists of repo ids (1 for models, 1 for datasets and 1 for Spaces).
引發
ValueError
ValueError— Ifuseris not passed and no token found (either from argument or from machine).
List all public repos liked by a user on huggingface.co.
This list is public so token is optional. If user is not passed, it defaults to the logged in user.
See also unlike().
list_models
< source >( filter: Union[str, Iterable[str], None] = None author: Optional[str] = None apps: Optional[Union[str, list[str]]] = None gated: Optional[bool] = None inference: Optional[Literal['warm']] = None inference_provider: Optional[Union[Literal['all'], 'PROVIDER_T', list['PROVIDER_T']]] = None model_name: Optional[str] = None trained_dataset: Optional[Union[str, list[str]]] = None search: Optional[str] = None pipeline_tag: Optional[str] = None emissions_thresholds: Optional[tuple[float, float]] = None sort: Optional[ModelSort_T] = None direction: Optional[Literal[-1]] = None limit: Optional[int] = None expand: Optional[list[ExpandModelProperty_T]] = None full: Optional[bool] = None cardData: bool = False fetch_config: bool = False token: Union[bool, str, None] = None ) → Iterable[ModelInfo]
引數
- filter (
strorIterable[str], optional) — A string or list of string to filter models on the Hub. Models can be filtered by library, language, task, tags, and more. - author (
str, optional) — A string which identify the author (user or organization) of the returned models. - apps (
str或List, 可選) — 用於過濾 Hub 上支援指定應用的模型的字串或字串列表。示例值包括"ollama"或["ollama", "vllm"]。 - gated (
bool, 可選) — 用於過濾 Hub 上受限模型或非受限模型的布林值。預設返回所有模型。如果傳入gated=True,則僅返回受限模型。如果傳入gated=False,則僅返回非受限模型。 - inference (
Literal["warm"], 可選) — 如果為“warm”,則過濾 Hub 上當前由至少一個提供者服務的模型。 - inference_provider (
Literal["all"]或str, 可選) — 用於過濾 Hub 上由特定提供者服務的模型的字串。傳入"all"以獲取至少由一個提供者服務的全部模型。 - model_name (
str, 可選) — 用於在 Hub 上搜索模型名稱(完整或部分)的字串,例如“bert”或“bert-base-cased” - trained_dataset (
str或List, 可選) — 用於 Hub 上模型的訓練資料集的字串標籤或字串標籤列表。 - search (
str, 可選) — 將包含在返回的模型 ID 中的字串。 - pipeline_tag (
str, 可選) — 用於按管道標籤過濾 Hub 上模型的字串,例如summarization。 - emissions_thresholds (
Tuple, 可選) — 一個包含兩個整數或浮點數的元組,表示以克為單位的最小和最大碳足跡,用於過濾結果模型。 - sort (
ModelSort_T, 可選) — 用於對結果模型進行排序的鍵。可能的值包括“created_at”、“downloads”、“last_modified”、“likes”和“trending_score”。 - direction (
Literal[-1]或int, 可選) — 已棄用。此引數未使用,將在 1.5 版本中刪除。 - limit (
int, 可選) — 獲取的模型數量限制。將此選項留空None將獲取所有模型。 - expand (
list[ExpandModelProperty_T], 可選) — 要在響應中返回的屬性列表。使用時,將僅返回列表中的屬性。如果傳入full、cardData或fetch_config,則不能使用此引數。可能的值為"author"、"cardData"、"config"、"createdAt"、"disabled"、"downloads"、"downloadsAllTime"、"evalResults"、"gated"、"gguf"、"inference"、"inferenceProviderMapping"、"lastModified"、"library_name"、"likes"、"mask_token"、"model-index"、"pipeline_tag"、"private"、"safetensors"、"sha"、"siblings"、"spaces"、"tags"、"transformersInfo"、"trendingScore"、"widgetData"和"resourceGroup"。 - full (
bool, 可選) — 是否獲取所有模型資料,包括last_modified、sha、檔案和tags。當使用過濾器時,此項預設設定為True。 - cardData (
bool, 可選) — 是否也獲取模型的元資料。它可以包含有用的資訊,如碳排放、指標和訓練過的資料集。 - fetch_config (
bool, 可選) — 是否也獲取模型配置。由於大小原因,這不包含在full中。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是身份驗證的推薦方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Iterable[ModelInfo]
一個可迭代的 huggingface_hub.hf_api.ModelInfo 物件列表。
列出 Huggingface Hub 上託管的模型,並可進行篩選。
示例
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# List all models
>>> api.list_models()
# List text classification models
>>> api.list_models(filter="text-classification")
# List models from the KerasHub library
>>> api.list_models(filter="keras-hub")
# List models served by Cohere
>>> api.list_models(inference_provider="cohere")
# List models with "bert" in their name
>>> api.list_models(search="bert")
# List models with "bert" in their name and pushed by google
>>> api.list_models(search="bert", author="google")list_organization_followers
< source >( organization: str token: Union[bool, str, None] = None ) → Iterable[User]
引數
- organization (
str) — 要獲取其關注者的組織的名稱。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是身份驗證的推薦方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Iterable[User]
包含組織關注者資訊的 User 物件列表。
引發
HfHubHTTPError
HfHubHTTPError— HTTP 404 如果組織在 Hub 上不存在。
列出 Hub 上組織的關注者。
list_organization_members
< source >( organization: str token: Union[bool, str, None] = None ) → Iterable[User]
引數
- organization (
str) — 要獲取其成員的組織的名稱。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是身份驗證的推薦方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Iterable[User]
包含組織成員資訊的 User 物件列表。
引發
HfHubHTTPError
HfHubHTTPError— HTTP 404 如果組織在 Hub 上不存在。
列出 Hub 上組織的成員。
list_papers
< source >( query: Optional[str] = None limit: Optional[int] = None token: Union[bool, str, None] = None ) → Iterable[PaperInfo]
引數
- query (
str, 可選) — 用於搜尋論文的搜尋查詢字串。如果提供,將返回匹配查詢的論文。 - limit (
int, optional) — 要返回的 paper 的最大數量。 - token (Union[bool, str, None], optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞
False。
返回
Iterable[PaperInfo]
an iterable of huggingface_hub.hf_api.PaperInfo objects.
在 Hugging Face Hub 上根據搜尋查詢列出每日 papers。
list_pending_access_requests
< source >( repo_id: str repo_type: Optional[str] = None token: Union[bool, str, None] = None ) → Iterable[AccessRequest]
引數
- repo_id (
str) — 要獲取訪問請求的 repo 的 ID。 - repo_type (
str, optional) — 要獲取訪問請求的 repo 的型別。必須是model、dataset或space之一。預設為model。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Iterable[AccessRequest]
一個 AccessRequest 物件的迭代器。每個物件都包含 username、email、status 和 timestamp 屬性。如果受限制的儲存庫有自定義表單,則 fields 屬性將填充使用者的答案。
引發
HfHubHTTPError
HfHubHTTPError— 如果倉庫未受保護,則為 HTTP 400。HfHubHTTPError— 如果您只有倉庫的只讀訪問許可權,則為 HTTP 403。如果您的組織(倉庫所屬的組織)沒有write或admin角色,或者您傳遞了readtoken,則可能出現這種情況。
獲取給定受保護 repo 的待處理訪問請求。
待處理請求意味著使用者已請求訪問 repo,但請求尚未處理。如果審批模式是自動的,此列表應為空。可以使用 accept_access_request() 和 reject_access_request() 接受或拒絕待處理的請求。
有關受保護倉庫的更多資訊,請參閱 https://huggingface.co/docs/hub/models-gated。
示例
>>> from huggingface_hub import list_pending_access_requests, accept_access_request
# List pending requests
>>> requests = list(list_pending_access_requests("meta-llama/Llama-2-7b"))
>>> len(requests)
411
>>> requests[0]
[
AccessRequest(
username='clem',
fullname='Clem 🤗',
email='***',
timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
status='pending',
fields=None,
),
...
]
# Accept Clem's request
>>> accept_access_request("meta-llama/Llama-2-7b", "clem")list_rejected_access_requests
< source >( repo_id: str repo_type: Optional[str] = None token: Union[bool, str, None] = None ) → Iterable[AccessRequest]
引數
- repo_id (
str) — 要獲取訪問請求的 repo 的 ID。 - repo_type (
str, optional) — 要獲取訪問請求的 repo 的型別。必須是model、dataset或space之一。預設為model。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Iterable[AccessRequest]
一個 AccessRequest 物件的迭代器。每個物件都包含 username、email、status 和 timestamp 屬性。如果受限制的儲存庫有自定義表單,則 fields 屬性將填充使用者的答案。
引發
HfHubHTTPError
HfHubHTTPError— 如果倉庫未受保護,則為 HTTP 400。HfHubHTTPError— 如果您只有倉庫的只讀訪問許可權,則為 HTTP 403。如果您的組織(倉庫所屬的組織)沒有write或admin角色,或者您傳遞了readtoken,則可能出現這種情況。
獲取給定受保護 repo 的已拒絕訪問請求。
已拒絕的請求意味著使用者已請求訪問 repo,並且請求已被 repo 所有者(您或其他組織成員)明確拒絕。使用者無法下載 repo 的任何檔案。可以使用 accept_access_request() 和 cancel_access_request() 隨時接受或取消已拒絕的請求。已取消的請求將返回到待處理列表,而已接受的請求將進入已接受列表。
有關受保護倉庫的更多資訊,請參閱 https://huggingface.co/docs/hub/models-gated。
示例
>>> from huggingface_hub import list_rejected_access_requests
>>> requests = list(list_rejected_access_requests("meta-llama/Llama-2-7b"))
>>> len(requests)
411
>>> requests[0]
[
AccessRequest(
username='clem',
fullname='Clem 🤗',
email='***',
timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc),
status='rejected',
fields=None,
),
...
]list_repo_commits
< source >( repo_id: str repo_type: Optional[str] = None token: Union[bool, str, None] = None revision: Optional[str] = None formatted: bool = False ) → list[GitCommitInfo]
引數
- repo_id (
str) — 一個由/分隔的名稱空間(使用者或組織)和 repo 名稱。 - repo_type (
str, optional) — 如果列出 dataset 或 space 的提交,則設定為"dataset"或"space",如果列出 model 的提交,則設定為None或"model"。預設為None。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - revision (
str, optional) — 要從中獲取提交的 git revision。預設為"main"分支的 head。 - formatted (
bool) — 是否返回 commit 的 HTML 格式標題和描述。預設為 False。
返回
list[GitCommitInfo]
包含 repo 在 Hub 上提交資訊的物件列表。
- RepositoryNotFoundError — 如果倉庫未找到(錯誤 404):repo_id/repo_type 錯誤,私有但未經驗證或倉庫不存在。
- RevisionNotFoundError — 如果在儲存庫中找不到 revision(錯誤 404)。
獲取 Hub 上給定 repo 的給定 revision 的提交列表。
提交按日期排序(最後提交的在前)。
示例
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# Commits are sorted by date (last commit first)
>>> initial_commit = api.list_repo_commits("gpt2")[-1]
# Initial commit is always a system commit containing the `.gitattributes` file.
>>> initial_commit
GitCommitInfo(
commit_id='9b865efde13a30c13e0a33e536cf3e4a5a9d71d8',
authors=['system'],
created_at=datetime.datetime(2019, 2, 18, 10, 36, 15, tzinfo=datetime.timezone.utc),
title='initial commit',
message='',
formatted_title=None,
formatted_message=None
)
# Create an empty branch by deriving from initial commit
>>> api.create_branch("gpt2", "new_empty_branch", revision=initial_commit.commit_id)list_repo_files
< source >( repo_id: str revision: Optional[str] = None repo_type: Optional[str] = None token: Union[str, bool, None] = None ) → list[str]
引數
- repo_id (
str) — 一個由/分隔的名稱空間(使用者或組織)和 repo 名稱。 - revision (
str, optional) — 要從中獲取資訊的倉庫的 revision。 - repo_type (
str, optional) — 如果上傳到 dataset 或 space,則設定為"dataset"或"space";如果上傳到 model,則設定為None或"model"。預設為None。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
list[str]
給定 repository 中檔案的列表。
獲取給定 repo 中檔案的列表。
list_repo_likers
< source >( repo_id: str repo_type: Optional[str] = None token: Union[bool, str, None] = None ) → Iterable[User]
引數
- repo_id (
str) — 要檢索的 repository。例如:"user/my-cool-model"。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - repo_type (
str, optional) — 如果上傳到 dataset 或 space,則設定為"dataset"或"space";如果上傳到 model,則設定為None或"model"。預設為None。
返回
Iterable[User]
一個 huggingface_hub.hf_api.User 物件的 iterable。
列出在 Hugging Face Hub 上喜歡給定 repo 的所有使用者。
另請參閱 list_liked_repos()。
list_repo_refs
< source >( repo_id: str repo_type: Optional[str] = None include_pull_requests: bool = False token: Union[str, bool, None] = None ) → GitRefs
引數
- repo_id (
str) — 名稱空間(使用者或組織)和倉庫名稱,用/分隔。 - repo_type (
str, optional) — 設定為"dataset"或"space",如果列出的是資料集或 Space 的 ref;如果列出的是模型的 ref,則為None或"model"。預設為None。 - include_pull_requests (
bool, optional) — 是否包含來自 pull requests 的 ref。預設為False。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
包含 Hub 上倉庫所有分支和標籤資訊的物件。
獲取給定倉庫的 ref 列表(包括標籤和分支)。
示例
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> api.list_repo_refs("gpt2")
GitRefs(branches=[GitRefInfo(name='main', ref='refs/heads/main', target_commit='e7da7f221d5bf496a48136c0cd264e630fe9fcc8')], converts=[], tags=[])
>>> 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')
]
)list_repo_tree
< source >( repo_id: str path_in_repo: Optional[str] = None recursive: bool = False expand: bool = False revision: Optional[str] = None repo_type: Optional[str] = None token: Union[str, bool, None] = None ) → Iterable[Union[RepoFile, RepoFolder]]
引數
- repo_id (
str) — 名稱空間(使用者或組織)和倉庫名稱,用/分隔。 - path_in_repo (
str, optional) — 倉庫內的樹(資料夾)的相對路徑,例如:"checkpoints/1fec34a/results"。預設為倉庫的根樹(資料夾)。 - recursive (
bool, optional, defaults toFalse) — 是否遞迴列出樹的檔案和資料夾。 - expand (
bool, optional, defaults toFalse) — 是否獲取有關樹的檔案和資料夾的更多資訊(例如,上次提交和檔案的安全掃描結果)。此操作對伺服器來說成本更高,因此每頁只返回 50 個結果(而不是 1000 個)。儘管huggingface_hub實現了分頁,但這對您來說是透明的,除了獲取結果所需的時間。 - revision (
str, optional) — 要從中獲取樹的倉庫修訂版本。預設為"main"分支。 - repo_type (
str, optional) — 要從中獲取樹的倉庫型別("model"、"dataset"或"space")。預設為"model"。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Iterable[Union[RepoFile, RepoFolder]]
樹的檔案和資料夾資訊,作為 RepoFile 和 RepoFolder 物件的迭代器。檔案和資料夾的順序不保證。
引發
RepositoryNotFoundError 或 RevisionNotFoundError 或 ~utils.RemoteEntryNotFoundError
- RepositoryNotFoundError — 如果倉庫未找到(錯誤 404):repo_id/repo_type 錯誤,私有但未經驗證或倉庫不存在。
- RevisionNotFoundError — 如果在儲存庫中找不到 revision(錯誤 404)。
~utils.RemoteEntryNotFoundError— 如果樹(資料夾)在倉庫中不存在(錯誤 404)。
列出倉庫樹的檔案和資料夾並獲取有關它們的資訊。
示例
獲取有關倉庫樹的資訊。
>>> from huggingface_hub import list_repo_tree
>>> repo_tree = list_repo_tree("lysandre/arxiv-nlp")
>>> repo_tree
<generator object HfApi.list_repo_tree at 0x7fa4088e1ac0>
>>> list(repo_tree)
[
RepoFile(path='.gitattributes', size=391, blob_id='ae8c63daedbd4206d7d40126955d4e6ab1c80f8f', lfs=None, last_commit=None, security=None),
RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None),
RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None),
RepoFile(
path='flax_model.msgpack', size=497764107, blob_id='8095a62ccb4d806da7666fcda07467e2d150218e',
lfs={'size': 497764107, 'sha256': 'd88b0d6a6ff9c3f8151f9d3228f57092aaea997f09af009eefd7373a77b5abb9', 'pointer_size': 134}, last_commit=None, security=None
),
RepoFile(path='merges.txt', size=456318, blob_id='226b0752cac7789c48f0cb3ec53eda48b7be36cc', lfs=None, last_commit=None, security=None),
RepoFile(
path='pytorch_model.bin', size=548123560, blob_id='64eaa9c526867e404b68f2c5d66fd78e27026523',
lfs={'size': 548123560, 'sha256': '9be78edb5b928eba33aa88f431551348f7466ba9f5ef3daf1d552398722a5436', 'pointer_size': 134}, last_commit=None, security=None
),
RepoFile(path='vocab.json', size=898669, blob_id='b00361fece0387ca34b4b8b8539ed830d644dbeb', lfs=None, last_commit=None, security=None)]
]獲取有關倉庫樹的更多資訊(上次提交和檔案的安全掃描結果)
>>> from huggingface_hub import list_repo_tree
>>> repo_tree = list_repo_tree("prompthero/openjourney-v4", expand=True)
>>> list(repo_tree)
[
RepoFolder(
path='feature_extractor',
tree_id='aa536c4ea18073388b5b0bc791057a7296a00398',
last_commit={
'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
'title': 'Upload diffusers weights (#48)',
'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
}
),
RepoFolder(
path='safety_checker',
tree_id='65aef9d787e5557373fdf714d6c34d4fcdd70440',
last_commit={
'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190',
'title': 'Upload diffusers weights (#48)',
'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc)
}
),
RepoFile(
path='model_index.json',
size=582,
blob_id='d3d7c1e8c3e78eeb1640b8e2041ee256e24c9ee1',
lfs=None,
last_commit={
'oid': 'b195ed2d503f3eb29637050a886d77bd81d35f0e',
'title': 'Fix deprecation warning by changing `CLIPFeatureExtractor` to `CLIPImageProcessor`. (#54)',
'date': datetime.datetime(2023, 5, 15, 21, 41, 59, tzinfo=datetime.timezone.utc)
},
security={
'safe': True,
'av_scan': {'virusFound': False, 'virusNames': None},
'pickle_import_scan': None
}
)
...
]list_scheduled_jobs
< source >( timeout: Optional[int] = None namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- timeout (
float, optional) — 是否為到 Hub 的請求設定超時。 - namespace (
str, optional) — 列出作業的名稱空間。預設為當前使用者的名稱空間。 - token
(Union[bool, str, None], optional) — 一個有效的使用者訪問令牌。如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。設定為False以停用身份驗證。參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
列出 Hugging Face 基礎設施上計劃的計算作業。
list_spaces
< source >( filter: Union[str, Iterable[str], None] = None author: Optional[str] = None search: Optional[str] = None datasets: Union[str, Iterable[str], None] = None models: Union[str, Iterable[str], None] = None linked: bool = False sort: Optional[SpaceSort_T] = None direction: Optional[Literal[-1]] = None limit: Optional[int] = None expand: Optional[list[ExpandSpaceProperty_T]] = None full: Optional[bool] = None token: Union[bool, str, None] = None ) → Iterable[SpaceInfo]
引數
- filter (
strorIterable, optional) — 用於標識 Hub 上 Spaces 的字串標籤或標籤列表。 - author (
str, optional) — 一個用於標識返回的 Spaces 作者的字串。 - search (
str, optional) — 將包含在返回的 Spaces 中的字串。 - datasets (
strorIterable, optional) — 是否返回使用資料集的 Spaces。可以傳入特定資料集的名稱作為字串。 - models (
strorIterable, optional) — 是否返回使用模型的 Spaces。可以傳入特定模型的名稱作為字串。 - linked (
bool, optional) — 是否返回使用模型或資料集的 Spaces。 - sort (
SpaceSort_T, optional) — 用於排序結果 Spaces 的鍵。可能的值為 “created_at”, “last_modified”, “likes” 和 “trending_score”。 - direction (
Literal[-1]orint, optional) — 已棄用。此引數未使用,將在版本 1.5 中刪除。 - limit (
int, optional) — 獲取的空間數量限制。如果留空 (None),將獲取所有空間。 - expand (
list[ExpandSpaceProperty_T], optional) — 響應中要返回的列表屬性。使用時,只返回列表中的屬性。如果傳遞了full,則不能使用此引數。可能的值包括"author"、"cardData"、"datasets"、"disabled"、"lastModified"、"createdAt"、"likes"、"models"、"private"、"runtime"、"sdk"、"siblings"、"sha"、"subdomain"、"tags"、"trendingScore"、"usedStorage"和"resourceGroup"。 - full (
bool, optional) — 是否獲取所有 Space 資料,包括last_modified、siblings和card_data欄位。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Iterable[SpaceInfo]
一個 huggingface_hub.hf_api.SpaceInfo 物件的迭代器。
列出託管在 Huggingface Hub 上的 Spaces,並提供一些過濾器。
list_user_followers
< source >( username: str token: Union[bool, str, None] = None ) → Iterable[User]
引數
- username (
str) — 要獲取其關注者列表的使用者的使用者名稱。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Iterable[User]
關注該使用者的 User 物件列表。
引發
HfHubHTTPError
HfHubHTTPError— HTTP 404 如果使用者在 Hub 上不存在。
獲取 Hub 上使用者關注者的列表。
list_user_following
< source >( username: str token: Union[bool, str, None] = None ) → Iterable[User]
引數
- username (
str) — 要獲取其關注列表的使用者的使用者名稱。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Iterable[User]
關注該使用者的 User 物件列表。
引發
HfHubHTTPError
HfHubHTTPError— HTTP 404 如果使用者在 Hub 上不存在。
獲取 Hub 上使用者關注的列表。
list_webhooks
< source >( token: Union[bool, str, None] = None ) → list[WebhookInfo]
引數
- token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
list[WebhookInfo]
Webhook info 物件的列表。
列出所有已配置的 Webhook。
示例
>>> from huggingface_hub import list_webhooks
>>> webhooks = list_webhooks()
>>> len(webhooks)
2
>>> webhooks[0]
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
secret="my-secret",
domains=["repo", "discussion"],
disabled=False,
)merge_pull_request
< source >( repo_id: str discussion_num: int token: Union[bool, str, None] = None comment: Optional[str] = None repo_type: Optional[str] = None ) → DiscussionStatusChange
引數
- repo_id (
str) — 名稱空間(使用者或組織)和倉庫名稱,由/分隔。 - discussion_num (
int) — 討論或拉取請求的編號。必須是嚴格正整數。 - comment (
str, optional) — 與狀態更改一起釋出的附加評論。 - repo_type (
str, optional) — 如果上傳到資料集或空間,則設定為"dataset"或"space",如果上傳到模型,則設定為None或"model"。預設為None。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
狀態更改事件
合併拉取請求。
引發以下錯誤
HTTPError如果 HuggingFace API 返回錯誤ValueError如果某些引數值無效- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。
model_info
< source >( repo_id: str revision: Optional[str] = None timeout: Optional[float] = None securityStatus: Optional[bool] = None files_metadata: bool = False expand: Optional[list[ExpandModelProperty_T]] = None token: Union[bool, str, None] = None ) → huggingface_hub.hf_api.ModelInfo
引數
- repo_id (
str) — 名稱空間(使用者或組織)和倉庫名稱,由/分隔。 - revision (
str, optional) — 從中獲取模型資訊的模型倉庫修訂版本。 - timeout (
float, optional) — 是否為到 Hub 的請求設定超時。 - securityStatus (
bool, optional) — 是否同時從模型倉庫檢索安全狀態。安全狀態將在security_repo_status欄位中返回。 - files_metadata (
bool, optional) — 是否檢索倉庫中檔案的元資料(大小、LFS 元資料等)。預設為False。 - expand (
list[ExpandModelProperty_T], optional) — 響應中要返回的列表屬性。使用時,只返回列表中的屬性。如果傳遞了securityStatus或files_metadata,則不能使用此引數。可能的值包括"author"、"baseModels"、"cardData"、"childrenModelCount"、"config"、"createdAt"、"disabled"、"downloads"、"downloadsAllTime"、"evalResults"、"gated"、"gguf"、"inference"、"inferenceProviderMapping"、"lastModified"、"library_name"、"likes"、"mask_token"、"model-index"、"pipeline_tag"、"private"、"safetensors"、"sha"、"siblings"、"spaces"、"tags"、"transformersInfo"、"trendingScore"、"widgetData"、"usedStorage"和"resourceGroup"。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
模型倉庫資訊。
獲取 huggingface.co 上單個模型的詳細資訊
如果您傳遞了可接受的令牌或已登入,則模型可以是私有的。
引發以下錯誤
- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。- RevisionNotFoundError 如果找不到要從中下載的版本。
move_repo
< 原始碼 >( from_id: str to_id: str repo_type: Optional[str] = None token: Union[str, bool, None] = None )
引數
- from_id (
str) — 名稱空間(使用者或組織)和倉庫名稱的組合,用/分隔。原始倉庫識別符號。 - to_id (
str) — 名稱空間(使用者或組織)和倉庫名稱的組合,用/分隔。最終倉庫識別符號。 - repo_type (
str, optional) — 如果是上傳到資料集或空間,則設定為"dataset"或"space",如果是上傳到模型,則設定為None或"model"。預設為None。 - token (
bool或str, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
將倉庫從 namespace1/repo_name1 移動到 namespace2/repo_name2
請注意,存在某些限制。有關移動倉庫的更多資訊,請參閱 https://huggingface.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo。
引發以下錯誤
- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。
paper_info
< 原始碼 >( id: str ) → PaperInfo
獲取 Hub 上一篇論文的資訊。
parse_safetensors_file_metadata
< 原始碼 >( repo_id: str filename: str repo_type: Optional[str] = None revision: Optional[str] = None token: Union[bool, str, None] = None ) → SafetensorsFileMetadata
引數
- repo_id (
str) — 使用者或組織名稱和倉庫名稱的組合,用/分隔。 - filename (
str) — 倉庫中檔案的名稱。 - repo_type (
str, optional) — 如果檔案在資料集中或空間中,則設定為"dataset"或"space",如果檔案在模型中,則設定為None或"model"。預設為None。 - revision (
str, optional) — 用於從哪個 git 版本獲取檔案的版本。可以是分支名稱、標籤或提交雜湊。預設為"main"分支的頭部。 - token (
bool或str, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
SafetensorsFileMetadata
與 safetensors 檔案相關的資訊。
引發
NotASafetensorsRepoError 或 SafetensorsParsingError
NotASafetensorsRepoError— 如果儲存庫不是 safetensors 儲存庫,即不包含model.safetensors或model.safetensors.index.json檔案。SafetensorsParsingError— 如果 safetensors 檔案頭無法正確解析。
解析 Hub 上 safetensors 檔案的元資料。
要一次性解析倉庫中所有 safetensors 檔案的元資料,請使用 get_safetensors_metadata()。
有關 safetensors 格式的更多詳細資訊,請檢視 https://huggingface.co/docs/safetensors/index#format。
pause_inference_endpoint
< 原始碼 >( name: str namespace: Optional[str] = None token: Union[bool, str, None] = None ) → InferenceEndpoint
引數
- name (
str) — 要暫停的推理端點的名稱。 - namespace (
str, optional) — 推理端點所在的名稱空間。預設為當前使用者。 - token (
bool或str, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
有關已暫停的推理端點的資訊。
暫停推理端點。
已暫停的推理端點將不會被收費。它可以隨時使用 resume_inference_endpoint() 恢復。這與使用 scale_to_zero_inference_endpoint() 將推理端點縮減到零不同,後者在收到請求時會自動重啟。
為方便起見,您也可以使用 pause_inference_endpoint() 暫停推理端點。
pause_space
< 原始碼 >( repo_id: str token: Union[bool, str, None] = None ) → SpaceRuntime
引數
- repo_id (
str) — 要暫停的 Space 的 ID。例如:"Salesforce/BLIP2"。 - token (
bool或str, optional) — 有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
有關您的 Space 的執行時資訊,包括 stage=PAUSED 和請求的硬體。
- RepositoryNotFoundError — 如果找不到您的 Space(錯誤 404)。很可能是 repo_id 錯誤,或者您的 Space 是私有的,但您尚未進行身份驗證。
- HfHubHTTPError — 403 Forbidden:只有 Space 的所有者才能暫停它。如果你想管理一個不屬於你的 Space,請透過開啟討論來請求所有者或複製 Space。
- BadRequestError — 如果你的 Space 是靜態 Space。靜態 Space 始終執行且不計費。如果你想隱藏一個靜態 Space,你可以將其設定為私有。
暫停你的 Space。
暫停的 Space 會停止執行,直到其所有者手動重啟。這與空閒 48 小時後進入睡眠狀態的免費 Space 不同。無論您選擇什麼硬體,暫停時間都不會計入您的帳戶。要重啟您的 Space,請使用 restart_space() 並轉到您的 Space 設定頁面。
有關更多詳細資訊,請訪問 文件。
permanently_delete_lfs_files
< 原始碼 >( repo_id: str lfs_files: Iterable[LFSFileInfo] rewrite_history: bool = True repo_type: Optional[str] = None token: Union[bool, str, None] = None )
引數
- repo_id (
str) — 您要列出 LFS 檔案的倉庫。 - lfs_files (
Iterable[LFSFileInfo]) — 要從倉庫中永久刪除的LFSFileInfo物件的可迭代物件。使用 list_lfs_files() 列出倉庫中的所有 LFS 檔案。 - rewrite_history (
bool, 可選, 預設為True) — 是否重寫倉庫歷史以刪除引用被刪除的 LFS 檔案的檔案指標(推薦)。 - repo_type (
str, 可選) — 倉庫的型別。如果從資料集或空間中列出,則設定為"dataset"或"space",如果從模型中列出,則設定為None或"model"。預設為None。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
從 Hub 上的倉庫中永久刪除 LFS 檔案。
這是一個永久性操作,將影響所有引用被刪除的 LFS 檔案的提交,並可能破壞您的倉庫。這是一個不可恢復的操作。僅在您知道自己在做什麼時才使用它。
示例
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> lfs_files = api.list_lfs_files("username/my-cool-repo")
# Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
# e.g. select only LFS files in the "checkpoints" folder
>>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
# Permanently delete LFS files
>>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)preupload_lfs_files
< source >( repo_id: str additions: Iterable[CommitOperationAdd] token: Union[str, bool, None] = None repo_type: Optional[str] = None revision: Optional[str] = None create_pr: Optional[bool] = None num_threads: int = 5 free_memory: bool = True gitignore_content: Optional[str] = None )
引數
- repo_id (
str) — 您將在其中提交檔案的倉庫,例如:"username/custom_transformers"。 - operations (
Iterableof CommitOperationAdd) — 要上傳的檔案列表。警告:此列表中的物件將在處理過程中被修改以包含與上傳相關的資訊。請勿在多個提交中重複使用相同的物件。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - repo_type (
str, 可選) — 要上傳到的倉庫的型別(例如"model"-預設值-、"dataset"或"space")。 - revision (
str, 可選) — 用於提交的 git 版本。預設為"main"分支的 head。 - create_pr (
boolean, 可選) — 是否建立 Pull Request 與此提交。預設為False。 - num_threads (
int, 可選) — 用於上傳檔案的併發執行緒數。預設為 5。設定為 2 意味著最多同時上傳 2 個檔案。 - gitignore_content (
str, 可選) — 用於瞭解應忽略哪些檔案的.gitignore檔案內容。優先順序順序是首先檢查是否傳遞了gitignore_content,然後檢查.gitignore檔案是否存在於要提交的檔案列表中,最後預設為 Hub 上已託管的.gitignore檔案(如果存在)。
在未來提交之前,預先將 LFS 檔案上傳到 S3。
如果您的 LFS 檔案很大,此方法很有用,您可以在上傳所有檔案之前即時生成要上傳的檔案,而無需將它們全部儲存在記憶體中。
這是一個高階使用者方法。您通常不需要直接呼叫它來提交。請直接使用 create_commit()。
提交操作在處理過程中將被修改。特別是,附加的
path_or_fileobj在上傳後將被移除以節省記憶體(並替換為一個空的bytes物件)。請勿重複使用相同的物件,除非是將其傳遞給 create_commit()。如果您不想從提交操作物件中移除附加的內容,請傳遞free_memory=False。
示例
>>> from huggingface_hub import CommitOperationAdd, preupload_lfs_files, create_commit, create_repo
>>> repo_id = create_repo("test_preupload").repo_id
# Generate and preupload LFS files one by one
>>> operations = [] # List of all `CommitOperationAdd` objects that will be generated
>>> for i in range(5):
... content = ... # generate binary content
... addition = CommitOperationAdd(path_in_repo=f"shard_{i}_of_5.bin", path_or_fileobj=content)
... preupload_lfs_files(repo_id, additions=[addition]) # upload + free memory
... operations.append(addition)
# Create commit
>>> create_commit(repo_id, operations=operations, commit_message="Commit all shards")reject_access_request
< source >( repo_id: str user: str repo_type: Optional[str] = None rejection_reason: Optional[str] token: Union[bool, str, None] = None )
引數
- repo_id (
str) — 要拒絕訪問請求的倉庫 ID。 - user (
str) — 應拒絕其訪問請求的使用者名稱的使用者。 - repo_type (
str, 可選) — 要拒絕訪問請求的倉庫型別。必須是model、dataset或space之一。預設為model。 - rejection_reason (
str, 可選) — 可選的拒絕原因,使用者可見(最多 200 個字元)。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
引發
HfHubHTTPError
HfHubHTTPError— 如果倉庫未受保護,則為 HTTP 400。HfHubHTTPError— 如果您只有倉庫的只讀訪問許可權,則為 HTTP 403。如果您的組織(倉庫所屬的組織)沒有write或admin角色,或者您傳遞了readtoken,則可能出現這種情況。HfHubHTTPError— 如果使用者不存在於 Hub 上,則為 HTTP 404。HfHubHTTPError— 如果找不到使用者訪問請求,則為 HTTP 404。HfHubHTTPError— 如果使用者訪問請求已在拒絕列表中,則為 HTTP 404。
拒絕使用者對給定受保護倉庫的訪問請求。
被拒絕的請求將進入拒絕列表。使用者將無法下載該倉庫的任何檔案。被拒絕的請求可以隨時使用 accept_access_request() 和 cancel_access_request() 接受或取消。被取消的請求將返回待定列表,而接受的請求將進入接受列表。
有關受保護倉庫的更多資訊,請參閱 https://huggingface.co/docs/hub/models-gated。
rename_discussion
< source >( repo_id: str discussion_num: int new_title: str token: Union[bool, str, None] = None repo_type: Optional[str] = None ) → DiscussionTitleChange
引數
- repo_id (
str) — 名稱空間(使用者或組織)和倉庫名稱,用/分隔。 - discussion_num (
int) — 討論或拉取請求的編號。必須是一個嚴格正整數。 - new_title (
str) — 討論的新標題 - repo_type (
str, optional) — 如果是上傳到資料集或空間,則設定為"dataset"或"space",如果是上傳到模型,則設定為None或"model"。 預設為None。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
標題更改事件
重新命名討論。
示例
>>> new_title = "New title, fixing a typo"
>>> HfApi().rename_discussion(
... repo_id="username/repo_name",
... discussion_num=34
... new_title=new_title
... )
# DiscussionTitleChange(id='deadbeef0000000', type='title-change', ...)
引發以下錯誤
HTTPError如果 HuggingFace API 返回錯誤ValueError如果某些引數值無效- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。
repo_exists
< source >( repo_id: str repo_type: Optional[str] = None token: Union[str, bool, None] = None )
引數
- repo_id (
str) — 由名稱空間(使用者或組織)和倉庫名稱組成,並用/分隔的字串。 - repo_type (
str, optional) — 如果是從資料集或空間獲取倉庫資訊,則設定為"dataset"或"space",如果是從模型獲取,則設定為None或"model"。 預設為None。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
檢查 Hugging Face Hub 上是否存在倉庫。
repo_info
< source >( repo_id: str revision: Optional[str] = None repo_type: Optional[str] = None timeout: Optional[float] = None files_metadata: bool = False expand: Optional[Union[ExpandModelProperty_T, ExpandDatasetProperty_T, ExpandSpaceProperty_T]] = None token: Union[bool, str, None] = None ) → Union[SpaceInfo, DatasetInfo, ModelInfo]
引數
- repo_id (
str) — 由名稱空間(使用者或組織)和倉庫名稱組成,並用/分隔的字串。 - revision (
str, optional) — 要從中獲取資訊的倉庫版本。 - repo_type (
str, optional) — 如果是從資料集或空間獲取倉庫資訊,則設定為"dataset"或"space",如果是從模型獲取,則設定為None或"model"。 預設為None。 - timeout (
float, optional) — 是否為到 Hub 的請求設定超時。 - expand (
ExpandModelProperty_T或ExpandDatasetProperty_T或ExpandSpaceProperty_T, optional) — 要在響應中返回的屬性列表。使用時,只返回列表中的屬性。如果傳遞了files_metadata,則不能使用此引數。有關可用屬性的詳盡列表,請檢視 model_info()、dataset_info() 或 space_info()。 - files_metadata (
bool, optional) — 是否檢索倉庫中檔案的元資料(大小、LFS 元資料等)。預設為False。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Union[SpaceInfo, DatasetInfo, ModelInfo]
倉庫資訊,作為 huggingface_hub.hf_api.DatasetInfo、huggingface_hub.hf_api.ModelInfo 或 huggingface_hub.hf_api.SpaceInfo 物件。
獲取給定型別倉庫的資訊物件。
引發以下錯誤
- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。- RevisionNotFoundError 如果找不到要從中下載的版本。
request_space_hardware
< source >( repo_id: str hardware: SpaceHardware token: Union[bool, str, None] = None sleep_time: Optional[int] = None ) → SpaceRuntime
引數
- repo_id (
str) — 要更新的倉庫 ID。例如:"bigcode/in-the-stack"。 - hardware (
str或 SpaceHardware) — 執行 Space 所需的硬體。例如:"t4-medium"。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - sleep_time (
int, optional) — 在 Space 進入休眠前等待的非活動秒數。如果不想讓 Space 休眠,則設定為-1(升級硬體的預設行為)。對於免費硬體,您無法配置休眠時間(空閒 48 小時後值固定)。有關更多詳細資訊,請參見 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。
返回
Space 的執行時資訊,包括 Space 階段和硬體。
為 Space 請求新的硬體。
也可以在建立 Space 倉庫時直接請求硬體!有關詳細資訊,請參閱 create_repo()。
request_space_storage
< source >( repo_id: str storage: SpaceStorage token: Union[bool, str, None] = None ) → SpaceRuntime
引數
- repo_id (
str) — 要更新的空間 ID。例如:"open-llm-leaderboard/open_llm_leaderboard"。 - storage (
str或 SpaceStorage) — 儲存層級。可以是 'small'、'medium' 或 'large'。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
Space 的執行時資訊,包括 Space 階段和硬體。
為 Space 請求永續性儲存。
請求永續性儲存後,無法減小儲存空間。要減小儲存空間,您必須透過 delete_space_storage() 刪除它。
restart_space
< 原始碼 >( repo_id: str token: Union[bool, str, None] = None factory_reboot: bool = False ) → SpaceRuntime
引數
- repo_id (
str) — 要重啟的空間 ID。 示例:"Salesforce/BLIP2"。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。 預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。 要停用身份驗證,請傳遞False。 - factory_reboot (
bool, 可選) — 如果為True,則空間將從頭開始重建,不快取任何要求。
返回
有關您的空間的執行時資訊。
- RepositoryNotFoundError — 如果找不到您的 Space(錯誤 404)。很可能是 repo_id 錯誤,或者您的 Space 是私有的,但您尚未進行身份驗證。
- HfHubHTTPError — 403 Forbidden:只有空間的擁有者才能重啟它。 如果你想重啟一個不屬於你的空間,可以開啟一個討論區請求擁有者協助,或者複製(Duplicate)該空間。
- BadRequestError — 如果你的 Space 是靜態 Space。靜態 Space 始終執行且不計費。如果你想隱藏一個靜態 Space,你可以將其設定為私有。
重啟你的空間。
這是以程式設計方式重啟空間的唯一方法,前提是您已將其置於暫停狀態(參見 pause_space())。 您必須是空間的擁有者才能重啟它。 如果您使用的是升級後的硬體,您的賬戶將在空間重啟後開始計費。 無論空間的當前狀態如何,您都可以觸發重啟。
有關更多詳細資訊,請訪問 文件。
resume_inference_endpoint
< 原始碼 >( name: str namespace: Optional[str] = None running_ok: bool = True token: Union[bool, str, None] = None ) → InferenceEndpoint
引數
- name (
str) — 要恢復的推理端點 (Inference Endpoint) 的名稱。 - namespace (
str, 可選) — 推理端點所在的名稱空間。 預設為當前使用者。 - running_ok (
bool, 可選) — 如果為True,當推理端點已經在執行時,該方法不會引發錯誤。 預設為True。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。 預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。 要停用身份驗證,請傳遞False。
有關已恢復的推理端點的資訊。
恢復推理端點。
為方便起見,您也可以使用 InferenceEndpoint.resume() 來恢復推理端點。
resume_scheduled_job
< 原始碼 >( scheduled_job_id: str namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- scheduled_job_id (
str) — 要恢復的計劃任務 (Job) 的 ID。 - namespace (
str, 可選) — 計劃任務所在的名稱空間。 預設為當前使用者的名稱空間。 - token
(Union[bool, str, None], 可選) — 一個有效的使用者訪問令牌。 如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。 設定為False以停用身份驗證。 參考: https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
在 Hugging Face 基礎設施上恢復(取消暫停)計劃的計算任務 (Job)。
revision_exists
< 原始碼 >( repo_id: str revision: str repo_type: Optional[str] = None token: Union[str, bool, None] = None )
引數
- repo_id (
str) — 名稱空間(使用者或組織)和倉庫名稱,以/分隔。 - revision (
str) — 要檢查的倉庫的修訂版本。 - repo_type (
str, 可選) — 如果從資料集或空間獲取倉庫資訊,請設定為"dataset"或"space",如果從模型獲取,則設定為None或"model"。 預設為None。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。 預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。 要停用身份驗證,請傳遞False。
檢查 Hugging Face Hub 上的倉庫中是否存在特定的修訂版本。
run_as_future
< 原始碼 >( fn: Callable[..., R] *args **kwargs ) → Future
在後臺執行一個方法並返回一個 Future 例項。
主要目標是在不阻塞主執行緒的情況下執行方法(例如,在訓練期間推送資料)。後臺作業被排隊以保持順序,但不會並行執行。如果您需要透過並行呼叫大量 API 來加速指令碼,則必須設定並使用您自己的 ThreadPoolExecutor。
注意:最常用的方法,如 upload_file()、upload_folder() 和 create_commit(),都有一個 run_as_future: bool 引數可以直接在後臺呼叫它們。這等同於在它們上面呼叫 api.run_as_future(...),但更簡潔。
run_job
< 原始碼 >( image: str command: list[str] env: Optional[dict[str, Any]] = None secrets: Optional[dict[str, Any]] = None flavor: Optional[SpaceHardware] = None timeout: Optional[Union[int, float, str]] = None labels: Optional[dict[str, str]] = None namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- image (
str) — 要使用的 Docker 映象。 示例:"ubuntu","python:3.12","pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"。來自 Space 的映象示例:"hf.co/spaces/lhoestq/duckdb"。 - command (
list[str]) — 要執行的命令。 示例:["echo", "hello"]。 - env (
dict[str, Any], optional) — 定義 Job 的環境變數。 - secrets (
dict[str, Any], optional) — 定義 Job 的秘密環境變數。 - flavor (
str, optional) — 硬體的配置,如 Hugging Face Spaces。有關可能的值,請參閱 SpaceHardware。預設為"cpu-basic"。 - timeout (
Union[int, float, str], optional) — Job 的最長持續時間:整數/浮點數後跟 s(秒,預設)、m(分鐘)、h(小時)或 d(天)。示例:300或"5m"表示 5 分鐘。 - labels (
dict[str, str], optional) — 要附加到作業的標籤(鍵值對)。 - namespace (
str, optional) — 將在其中建立 Job 的名稱空間。預設為當前使用者的名稱空間。 - token
(Union[bool, str, None], optional) — 一個有效的使用者訪問令牌。如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。設定為False以停用身份驗證。參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
在 Hugging Face 基礎設施上執行計算作業。
示例
run_uv_job
< 原始碼 >( script: str script_args: Optional[list[str]] = None dependencies: Optional[list[str]] = None python: Optional[str] = None image: Optional[str] = None env: Optional[dict[str, Any]] = None secrets: Optional[dict[str, Any]] = None flavor: Optional[SpaceHardware] = None timeout: Optional[Union[int, float, str]] = None labels: Optional[dict[str, str]] = None namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- script (
str) — UV 指令碼的路徑或 URL,或一個命令。 - script_args (
list[str], optional) — 要傳遞給指令碼或命令的引數。 - dependencies (
list[str], optional) — 用於執行 UV 指令碼所需的依賴項。 - python (
str, optional) — 使用特定的 Python 版本。預設為 3.12。 - image (
str, optional, defaults to “ghcr.io/astral-sh/uv —python3.12-bookworm”): 使用自定義的uv已安裝的 Docker 映象。 - env (
dict[str, Any], optional) — 定義 Job 的環境變數。 - secrets (
dict[str, Any], optional) — 定義 Job 的秘密環境變數。 - flavor (
str, optional) — 硬體的配置,如 Hugging Face Spaces。有關可能的值,請參閱 SpaceHardware。預設為"cpu-basic"。 - timeout (
Union[int, float, str], optional) — Job 的最長持續時間:整數/浮點數後跟 s(秒,預設)、m(分鐘)、h(小時)或 d(天)。示例:300或"5m"表示 5 分鐘。 - labels (
dict[str, str], optional) — 要附加到作業的標籤(鍵值對)。 - namespace (
str, optional) — 將在其中建立 Job 的名稱空間。預設為當前使用者的名稱空間。 - token
(Union[bool, str, None], optional) — 一個有效的使用者訪問令牌。如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。設定為False以停用身份驗證。參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
在 Hugging Face 基礎設施上執行一個 UV 指令碼 Job。
示例
執行一個 URL 中的指令碼
>>> from huggingface_hub import run_uv_job
>>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py"
>>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"]
>>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small")scale_to_zero_inference_endpoint
< 原始碼 >( name: str namespace: Optional[str] = None token: Union[bool, str, None] = None ) → InferenceEndpoint
引數
- name (
str) — 要縮減到零的推理端點的名稱。 - namespace (
str, optional) — The namespace in which the Inference Endpoint is located. Defaults to the current user. - token (
boolorstr, optional) — A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, passFalse.
有關已縮放至零的推理終結點的資訊。
將推理終結點縮放至零。
縮放至零的推理終結點將不會產生費用。它將在收到下一個請求時恢復,並帶有冷啟動延遲。這與使用 pause_inference_endpoint() 暫停推理終結點不同,後者需要使用 resume_inference_endpoint() 進行手動恢復。
為方便起見,您也可以使用 InferenceEndpoint.scale_to_zero() 將推理終結點縮放至零。
set_space_sleep_time
< source >( repo_id: str sleep_time: int token: Union[bool, str, None] = None ) → SpaceRuntime
引數
- repo_id (
str) — ID of the repo to update. Example:"bigcode/in-the-stack". - sleep_time (
int, optional) — Number of seconds of inactivity to wait before a Space is put to sleep. Set to-1if you don’t want your Space to pause (default behavior for upgraded hardware). For free hardware, you can’t configure the sleep time (value is fixed to 48 hours of inactivity). See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. - token (
boolorstr, optional) — A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, passFalse.
返回
Space 的執行時資訊,包括 Space 階段和硬體。
為正在升級硬體上執行的 Space 設定自定義休眠時間。
您的 Space 在 X 秒不活動後將進入休眠狀態。當您的 Space 處於“休眠”模式時,您不會被計費。如果新的訪問者訪問您的 Space,它將被“喚醒”。只有升級後的硬體才能配置休眠時間。要了解有關休眠階段的更多資訊,請參閱 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。
在請求硬體時,也可以使用 request_space_hardware() 設定自定義休眠時間。
snapshot_download
< source >( repo_id: str repo_type: Optional[str] = None revision: Optional[str] = None cache_dir: Union[str, Path, None] = None local_dir: Union[str, Path, None] = None etag_timeout: float = 10 force_download: bool = False token: Union[bool, str, None] = None local_files_only: bool = False allow_patterns: Optional[Union[list[str], str]] = None ignore_patterns: Optional[Union[list[str], str]] = None max_workers: int = 8 tqdm_class: Optional[type[base_tqdm]] = None dry_run: bool = False ) → str or list of DryRunFileInfo
引數
- repo_id (
str) — A user or an organization name and a repo name separated by a/. - repo_type (
str, optional) — Set to"dataset"or"space"if downloading from a dataset or space,Noneor"model"if downloading from a model. Default isNone. - revision (
str, optional) — An optional Git revision id which can be a branch name, a tag, or a commit hash. - cache_dir (
str,Path, optional) — Path to the folder where cached files are stored. - local_dir (
strorPath, optional) — If provided, the downloaded files will be placed under this directory. - etag_timeout (
float, optional, defaults to10) — When fetching ETag, how many seconds to wait for the server to send data before giving up which is passed tohttpx.request. - force_download (
bool, optional, defaults toFalse) — Whether the file should be downloaded even if it already exists in the local cache. - token (
boolorstr, optional) — A valid user access token (string). Defaults to the locally saved token, which is the recommended method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). To disable authentication, passFalse. - local_files_only (
bool, optional, defaults toFalse) — IfTrue, avoid downloading the file and return the path to the local cached file if it exists. - allow_patterns (
list[str]orstr, optional) — If provided, only files matching at least one pattern are downloaded. - ignore_patterns (
list[str]orstr, optional) — If provided, files matching any of the patterns are not downloaded. - max_workers (
int, optional) — Number of concurrent threads to download files (1 thread = 1 file download). Defaults to 8. - tqdm_class (
tqdm, optional) — If provided, overwrites the default behavior for the progress bar. Passed argument must inherit fromtqdm.auto.tqdmor at least mimic its behavior. Note that thetqdm_classis not passed to each individual download. Defaults to the custom HF progress bar that can be disabled by settingHF_HUB_DISABLE_PROGRESS_BARSenvironment variable. - dry_run (
bool, optional, defaults toFalse) — IfTrue, perform a dry run without actually downloading the files. Returns a list of DryRunFileInfo objects containing information about what would be downloaded.
返回
str 或 DryRunFileInfo 列表
- 如果
dry_run=False:倉庫快照的資料夾路徑。 - 如果
dry_run=True:一個包含下載資訊的 DryRunFileInfo 物件列表。
引發
RepositoryNotFoundError 或 RevisionNotFoundError 或 EnvironmentError 或 OSError 或 ValueError
- RepositoryNotFoundError — 如果找不到要下載的儲存庫。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。 - RevisionNotFoundError — 如果找不到要下載的修訂版本。
EnvironmentError— 如果token=True且找不到令牌。OSError— 如果無法確定 ETag。ValueError— 如果某些引數值無效。
下載倉庫檔案。
下載指定修訂版本的整個倉庫檔案快照。當您需要倉庫中的所有檔案時,因為您事先不知道需要哪些檔案,這會很有用。所有檔案都巢狀在資料夾內,以保持其相對於該資料夾的實際檔名。您還可以使用 allow_patterns 和 ignore_patterns 過濾要下載的檔案。
如果提供了 local_dir,則倉庫中的檔案結構將在此位置複製。使用此選項時,將不使用 cache_dir,並且將在 local_dir 的根目錄中建立 .cache/huggingface/ 資料夾以儲存與下載檔案相關的某些元資料。雖然此機制不如主快取系統穩健,但它針對定期拉取儲存庫的最新版本進行了最佳化。
另一種方法是克隆儲存庫,但這需要安裝並正確配置 git 和 git-lfs。此外,使用 git 克隆儲存庫時無法過濾要下載的檔案。
space_info
< source >( repo_id: str revision: Optional[str] = None timeout: Optional[float] = None files_metadata: bool = False expand: Optional[list[ExpandSpaceProperty_T]] = None token: Union[bool, str, None] = None ) → SpaceInfo
引數
- repo_id (
str) — 一個由/分隔的使用者或組織名以及倉庫名。 - revision (
str, optional) — 要從中獲取資訊的空間儲存庫的版本。 - timeout (
float, optional) — 設定與 Hub 請求的超時時間。 - files_metadata (
bool, optional) — 是否檢索倉庫中檔案的元資料(大小、LFS 元資料等)。預設為False。 - expand (
list[ExpandSpaceProperty_T], optional) — 要在響應中返回的屬性列表。如果使用,則只返回列表中的屬性。如果傳遞了full,則無法使用此引數。可能的值為"author"、"cardData"、"createdAt"、"datasets"、"disabled"、"lastModified"、"likes"、"models"、"private"、"runtime"、"sdk"、"siblings"、"sha"、"subdomain"、"tags"、"trendingScore"、"usedStorage"和"resourceGroup"。 - token (
bool或str, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
返回
空間儲存庫資訊。
獲取 huggingface.co 上單個空間的具體資訊。
如果傳遞可接受的令牌,空間可以是私有的。
引發以下錯誤
- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。- RevisionNotFoundError 如果找不到要從中下載的版本。
super_squash_history
< source >( repo_id: str branch: Optional[str] = None commit_message: Optional[str] = None repo_type: Optional[str] = None token: Union[str, bool, None] = None )
引數
- repo_id (
str) — 一個由/分隔的使用者或組織名以及倉庫名。 - branch (
str, optional) — 要壓縮的分支。預設為"main"分支的頭部。 - commit_message (
str, optional) — 用於壓縮提交的提交訊息。 - repo_type (
str, optional) — 如果列出資料集或空間的提交,則設定為"dataset"或"space";如果列出模型的提交,則設定為None或"model"。預設為None。 - token (
bool或str, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
- RepositoryNotFoundError — 如果倉庫未找到(錯誤 404):repo_id/repo_type 錯誤,私有但未經驗證或倉庫不存在。
- RevisionNotFoundError — 如果找不到要壓縮的分支。
- BadRequestError — 如果分支的引用無效。您不能壓縮標籤的歷史記錄。
壓縮 Hub 上儲存庫分支的提交歷史。
當您知道將進行數百次提交且不想混亂歷史記錄時,壓縮提交歷史記錄非常有用。只能從分支的頭部執行壓縮提交。
壓縮後,無法恢復提交歷史。這是一個不可逆的操作。
一旦分支的歷史記錄被壓縮,就無法將其合併回另一個分支,因為它們的歷史記錄將發生分歧。
示例
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# Create repo
>>> repo_id = api.create_repo("test-squash").repo_id
# Make a lot of commits.
>>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"content")
>>> api.upload_file(repo_id=repo_id, path_in_repo="lfs.bin", path_or_fileobj=b"content")
>>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"another_content")
# Squash history
>>> api.super_squash_history(repo_id=repo_id)suspend_scheduled_job
< source >( scheduled_job_id: str namespace: Optional[str] = None token: Union[bool, str, None] = None )
引數
- scheduled_job_id (
str) — 計劃任務的 ID。 - namespace (
str, optional) — 計劃任務所在名稱空間。預設為當前使用者的名稱空間。 - token (
Union[bool, str, None], optional) — 一個有效的使用者訪問令牌。如果未提供,將使用本地儲存的令牌,這是推薦的身份驗證方法。設定為False以停用身份驗證。參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
暫停(掛起)Hugging Face 基礎結構上的計劃計算任務。
unlike
< source >( repo_id: str token: Union[bool, str, None] = None repo_type: Optional[str] = None )
引數
- repo_id (
str) — 要取消喜歡的儲存庫。例如:"user/my-cool-model"。 - token (
bool或str, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - repo_type (
str, optional) — 如果取消喜歡資料集或空間,則設定為"dataset"或"space";如果取消喜歡模型,則設定為None或"model"。預設為None。
- RepositoryNotFoundError — 如果倉庫未找到(錯誤 404):repo_id/repo_type 錯誤,私有但未經驗證或倉庫不存在。
取消 Hub 上給定儲存庫的喜歡(例如,從收藏夾列表中刪除)。
為防止濫用,無法透過指令碼 like 儲存庫。
另請參閱 list_liked_repos()。
update_collection_item
< source >( collection_slug: str item_object_id: str note: Optional[str] = None position: Optional[int] = None token: Union[bool, str, None] = None )
引數
- collection_slug (
str) — 要更新的集合的 slug。例如:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。 - item_object_id (
str) — 集合中專案的 ID。這不是 Hub 上的專案 ID(repo_id 或 paper id)。必須從 CollectionItem 物件中檢索。例如:collection.items[0].item_object_id。 - note (
str, optional) — 要附加到集合中項的註釋。註釋的最大長度為 500 個字元。 - position (
int, optional) — 集合中項的新位置。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
更新集合中的一個項。
示例
>>> from huggingface_hub import get_collection, update_collection_item
# Get collection first
>>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026")
# Update item based on its ID (add note + update position)
>>> update_collection_item(
... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026",
... item_object_id=collection.items[-1].item_object_id,
... note="Newly updated model!"
... position=0,
... )update_collection_metadata
< source >( collection_slug: str title: Optional[str] = None description: Optional[str] = None position: Optional[int] = None private: Optional[bool] = None theme: Optional[str] = None token: Union[bool, str, None] = None )
引數
- collection_slug (
str) — 要更新的集合的 slug。示例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。 - title (
str) — 要更新的集合的標題。 - description (
str, optional) — 要更新的集合的描述。 - position (
int, optional) — 新的集合在使用者集合列表中的位置。 - private (
bool, optional) — 集合應該是私有的還是非私有的。 - theme (
str, optional) — 集合在 Hub 上的主題。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。
更新集合在 Hub 上的元資料。
所有引數都是可選的。僅更新提供的元資料。
返回: Collection
示例
>>> from huggingface_hub import update_collection_metadata
>>> collection = update_collection_metadata(
... collection_slug="username/iccv-2023-64f9a55bb3115b4f513ec026",
... title="ICCV Oct. 2023"
... description="Portfolio of models, datasets, papers and demos I presented at ICCV Oct. 2023",
... private=False,
... theme="pink",
... )
>>> collection.slug
"username/iccv-oct-2023-64f9a55bb3115b4f513ec026"
# ^collection slug got updated but not the trailing IDupdate_inference_endpoint
< source >( name: str accelerator: Optional[str] = None instance_size: Optional[str] = None instance_type: Optional[str] = None min_replica: Optional[int] = None max_replica: Optional[int] = None scale_to_zero_timeout: Optional[int] = None scaling_metric: Optional[InferenceEndpointScalingMetric] = None scaling_threshold: Optional[float] = None repository: Optional[str] = None framework: Optional[str] = None revision: Optional[str] = None task: Optional[str] = None custom_image: Optional[dict] = None env: Optional[dict[str, str]] = None secrets: Optional[dict[str, str]] = None domain: Optional[str] = None path: Optional[str] = None cache_http_responses: Optional[bool] = None tags: Optional[list[str]] = None namespace: Optional[str] = None token: Union[bool, str, None] = None ) → InferenceEndpoint
引數
- name (
str) — 要更新的推理端點的名稱。 - accelerator (
str, optional) — 要用於推理的硬體加速器(例如"cpu")。 - instance_size (
str, optional) — 用於託管模型的例項的大小或型別(例如"x4")。 - instance_type (
str, optional) — 部署推理端點的雲實例型別(例如"intel-icl")。 - min_replica (
int, optional) — 保持推理端點執行的最小副本(例項)數量。 - max_replica (
int, optional) — 推理端點可以擴充套件到的最大副本(例項)數量。 - scale_to_zero_timeout (
int, optional) — 不活躍端點縮減為零之前的持續時間(以分鐘為單位)。 - scaling_metric (
strorInferenceEndpointScalingMetric, optional) — 用於縮放的指標引用。提供時為 “pendingRequests” 或 “hardwareUsage”。預設為 None。 - scaling_threshold (
float, optional) — 用於觸發向上擴充套件的縮放指標閾值。如果未提供縮放指標,則忽略此項。預設為 None。 - repository (
str, optional) — 與推理端點關聯的模型倉庫名稱(例如"gpt2")。 - framework (
str, optional) — 用於模型的機器學習框架(例如"custom")。 - revision (
str, optional) — 要在推理端點上部署的模型特定版本(例如"6c0e6080953db56375760c0471a8c5f2929baf11")。 - task (
str, optional) — 部署模型的任務(例如"text-classification")。 - custom_image (
dict, optional) — 用於推理端點的自定義 Docker 映像。如果你想部署一個執行在text-generation-inference(TGI) 框架上的推理端點,這將很有用(參見示例)。 - env (
dict[str, str], optional) — 注入到容器環境中的非金鑰環境變數 - secrets (
dict[str, str], optional) — 注入到容器環境中的機密值。 - domain (
str, optional) — 推理端點的自定義域名,如果設定了該域名,推理端點將在此域名可用(例如"my-new-domain.cool-website.woof")。 - path (
str, optional) — 已部署模型的自定義路徑,應以/開頭(例如"/models/google-bert/bert-base-uncased")。 - cache_http_responses (
bool, optional) — 是否快取來自推理端點的 HTTP 響應。 - tags (
list[str], optional) — 與推理端點關聯的標籤列表。 - namespace (
str, optional) — 將更新推理端點的名稱空間。預設為當前使用者的名稱空間。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的認證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用認證,請傳遞False。
已更新的推理端點資訊。
更新推理端點。
此方法允許更新計算配置、部署的模型、路由或它們的任意組合。所有引數都是可選的,但至少需要提供一個。
為了方便起見,您還可以使用 InferenceEndpoint.update() 來更新推理端點。
update_repo_settings
< source >( repo_id: str gated: Optional[Literal['auto', 'manual', False]] = None private: Optional[bool] = None token: Union[str, bool, None] = None repo_type: Optional[str] = None )
引數
- repo_id (
str) — 倉庫的名稱空間(使用者或組織)和倉庫名稱,用/分隔。 - gated (
Literal["auto", "manual", False], optional) — 倉庫的受限狀態。如果設定為None(預設),則不會更新倉庫的gated設定。- “auto”:倉庫是受限的,並且訪問請求會根據預定義標準自動批准或拒絕。
- “manual”:倉庫是受限的,並且訪問請求需要手動批准。
- False:倉庫不受限,任何人都可以訪問。
- private (
bool, optional) — 倉庫是否應設為私有。 - token (
Union[str, bool, None], optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的認證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用認證,請傳遞 False。 - repo_type (
str, optional) — 要更新其設定的倉庫型別("model"、"dataset"或"space")。預設為"model"。
引發
ValueError 或 HfHubHTTPError 或 RepositoryNotFoundError
ValueError— 如果 gated 不是 "auto"、"manual" 或 False 之一。ValueError— 如果 repo_type 不是 constants.REPO_TYPES 中的值之一。- HfHubHTTPError — 如果對 Hugging Face Hub API 的請求失敗。
- RepositoryNotFoundError — 如果找不到要下載的儲存庫。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。
更新倉庫的設定,包括受限訪問和可見性。
為了更好地控制倉庫的使用方式,Hub 允許倉庫作者為其倉庫啟用訪問請求,並設定倉庫的可見性為私有。
update_webhook
< source >( webhook_id: str url: Optional[str] = None watched: Optional[list[Union[dict, WebhookWatchedItem]]] = None domains: Optional[list[constants.WEBHOOK_DOMAIN_T]] = None secret: Optional[str] = None token: Union[bool, str, None] = None ) → WebhookInfo
引數
- webhook_id (
str) — 要更新的 webhook 的唯一識別符號。 - url (
str, optional) — 有效載荷將被髮送到的 URL。 - watched (
list[WebhookWatchedItem], optional) — 要監視的專案列表。可以是使用者、組織、模型、資料集或空間。有關更多詳細資訊,請參閱 WebhookWatchedItem。要監視的專案也可以作為普通字典提供。 - domains (
list[Literal["repo", "discussion"]], optional) — 要監視的域。這可以包括“repo”、“discussion”或兩者。 - secret (
str, optional) — 用於簽名有效載荷的金鑰,提供額外的安全層。 - token (
boolorstr, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的認證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用認證,請傳遞False。
返回
已更新 webhook 的資訊。
更新現有 webhook。
示例
>>> from huggingface_hub import update_webhook
>>> updated_payload = update_webhook(
... webhook_id="654bbbc16f2ec14d77f109cc",
... url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}],
... domains=["repo"],
... secret="my-secret",
... )
>>> print(updated_payload)
WebhookInfo(
id="654bbbc16f2ec14d77f109cc",
job=None,
url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548",
watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")],
domains=["repo"],
secret="my-secret",
disabled=False,upload_file
< source >( path_or_fileobj: Union[str, Path, bytes, BinaryIO] path_in_repo: str repo_id: str token: Union[str, bool, None] = None repo_type: Optional[str] = None revision: Optional[str] = None commit_message: Optional[str] = None commit_description: Optional[str] = None create_pr: Optional[bool] = None parent_commit: Optional[str] = None run_as_future: bool = False ) → CommitInfo or Future
引數
- path_or_fileobj (
str,Path,bytes, orIO) — 本地檔案的路徑或二進位制資料流/fileobj/buffer。 - path_in_repo (
str) — 倉庫中的相對檔案路徑,例如:"checkpoints/1fec34a/weights.bin" - repo_id (
str) — 將上傳檔案的倉庫,例如:"username/custom_transformers" - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - repo_type (
str, 可選) — 如果上傳到資料集或空間,則設定為"dataset"或"space",如果上傳到模型,則設定為None或"model"。預設為None。 - revision (
str, 可選) — 要提交的 git 版本。預設為"main"分支的最新提交。 - commit_message (
str, 可選) — 生成的提交的摘要/標題/第一行 - commit_description (
str, 可選) — 生成的提交的描述 - create_pr (
boolean, 可選) — 是否為此提交建立拉取請求。預設為False。如果未設定revision,則 PR 將針對"main"分支開啟。如果設定了revision並且它是一個分支,則 PR 將針對該分支開啟。如果設定了revision並且它不是分支名稱(例如:提交 OID),則伺服器將返回RevisionNotFoundError。 - parent_commit (
str, 可選) — 父提交的 OID/SHA,作為十六進位制字串。也支援縮寫(前 7 個字元)。如果指定了parent_commit並且create_pr為False,如果revision未指向parent_commit,則提交將失敗。如果指定了parent_commit並且create_pr為True,則將從parent_commit建立拉取請求。指定parent_commit可確保在提交更改之前倉庫沒有發生變化,並且如果倉庫被併發更新/提交,這一點尤其有用。 - run_as_future (
bool, 可選) — 是否在後臺執行此方法。後臺作業按順序執行,不會阻塞主執行緒。傳遞run_as_future=True將返回一個 Future 物件。預設為False。
返回
CommitInfo 或 Future
包含新建立 commit 資訊(commit hash, commit url, pr url, commit message 等)的 CommitInfo 例項。如果傳入 run_as_future=True,則返回一個 Future 物件,執行時將包含結果。
將本地檔案(最多 50 GB)上傳到指定的倉庫。上傳透過 HTTP POST 請求完成,無需安裝 git 或 git-lfs。
引發以下錯誤
HTTPError如果 HuggingFace API 返回錯誤ValueError如果某些引數值無效- RepositoryNotFoundError 如果要下載的倉庫找不到。這可能是因為它不存在,或者因為它被設定為
private且您沒有訪問許可權。- RevisionNotFoundError 如果找不到要從中下載的版本。
upload_file假定倉庫已存在於 Hub 上。如果您收到 Client error 404,請確保您已進行身份驗證,並且repo_id和repo_type設定正確。如果倉庫不存在,請先使用 create_repo() 建立它。
示例
>>> from huggingface_hub import upload_file
>>> with open("./local/filepath", "rb") as fobj:
... upload_file(
... path_or_fileobj=fileobj,
... path_in_repo="remote/file/path.h5",
... repo_id="username/my-dataset",
... repo_type="dataset",
... token="my_token",
... )
>>> upload_file(
... path_or_fileobj=".\\local\\file\\path",
... path_in_repo="remote/file/path.h5",
... repo_id="username/my-model",
... token="my_token",
... )
>>> upload_file(
... path_or_fileobj=".\\local\\file\\path",
... path_in_repo="remote/file/path.h5",
... repo_id="username/my-model",
... token="my_token",
... create_pr=True,
... )upload_folder
< source >( repo_id: str folder_path: Union[str, Path] path_in_repo: Optional[str] = None commit_message: Optional[str] = None commit_description: Optional[str] = None token: Union[str, bool, None] = None repo_type: Optional[str] = None revision: Optional[str] = None create_pr: Optional[bool] = None parent_commit: Optional[str] = None allow_patterns: Optional[Union[list[str], str]] = None ignore_patterns: Optional[Union[list[str], str]] = None delete_patterns: Optional[Union[list[str], str]] = None run_as_future: bool = False ) → CommitInfo 或 Future
引數
- repo_id (
str) — 要上傳檔案的倉庫,例如:"username/custom_transformers" - folder_path (
str或Path) — 要上傳到本地檔案系統的資料夾路徑 - path_in_repo (
str, 可選) — 倉庫中目錄的相對路徑,例如:"checkpoints/1fec34a/results"。將預設為倉庫的根目錄。 - token (
bool或str, 可選) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(參見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - repo_type (
str, 可選) — 如果上傳到資料集或空間,則設定為"dataset"或"space",如果上傳到模型,則設定為None或"model"。預設為None。 - revision (
str, 可選) — 要提交的 git 版本。預設為"main"分支的最新提交。 - commit_message (
str, 可選) — 生成的提交的摘要/標題/第一行。預設為:f"Upload {path_in_repo} with huggingface_hub" - commit_description (
str, 可選) — 生成的提交的描述 - create_pr (
boolean, 可選) — 是否為此提交建立拉取請求。預設為False。如果未設定revision,則 PR 將針對"main"分支開啟。如果設定了revision並且它是一個分支,則 PR 將針對該分支開啟。如果設定了revision並且它不是分支名稱(例如:提交 OID),則伺服器將返回RevisionNotFoundError。 - parent_commit (
str, 可選) — 父提交的 OID/SHA,作為十六進位制字串。也支援縮寫(前 7 個字元)。如果指定了parent_commit並且create_pr為False,如果revision未指向parent_commit,則提交將失敗。如果指定了parent_commit並且create_pr為True,則將從parent_commit建立拉取請求。指定parent_commit可確保在提交更改之前倉庫沒有發生變化,並且如果倉庫被併發更新/提交,這一點尤其有用。 - allow_patterns (
list[str]或str, 可選) — 如果提供,則只上傳匹配至少一個模式的檔案。 - ignore_patterns (
list[str]或str, 可選) — 如果提供,則忽略匹配任何模式的檔案。 - delete_patterns (
list[str]或str, 可選) — 如果提供,則將從倉庫中刪除匹配任何模式的遠端檔案,同時提交新檔案。如果您不知道哪些檔案已被上傳,這很有用。注意:為避免歧義,即使.gitattributes檔案匹配模式,也不會被刪除。 - run_as_future (
bool, 可選) — 是否在後臺執行此方法。後臺作業按順序執行,不會阻塞主執行緒。傳遞run_as_future=True將返回一個 Future 物件。預設為False。
返回
CommitInfo 或 Future
包含新建立 commit 資訊(commit hash, commit url, pr url, commit message 等)的 CommitInfo 例項。如果傳入 run_as_future=True,則返回一個 Future 物件,執行時將包含結果。
將本地資料夾上傳到指定的倉庫。上傳透過 HTTP 請求完成,無需安裝 git 或 git-lfs。
資料夾的結構將被保留。同名檔案如果已存在於倉庫中,將被覆蓋。其他檔案將保持不變。
使用 allow_patterns 和 ignore_patterns 引數來指定要上傳的檔案。這些引數可以接受單個模式或模式列表。模式是標準萬用字元(globbing patterns),如 此處 記錄。如果同時提供了 allow_patterns 和 ignore_patterns,則兩個約束都適用。預設情況下,資料夾中的所有檔案都會被上傳。
使用 delete_patterns 引數指定要刪除的遠端檔案。輸入型別與 allow_patterns 相同(見上文)。如果還提供了 path_in_repo,則模式將相對於該資料夾進行匹配。例如,upload_folder(..., path_in_repo="experiment", delete_patterns="logs/*") 將刪除 ./experiment/logs/ 下的任何遠端檔案。請注意,即使 .gitattributes 檔案匹配模式,也不會被刪除。
任何子目錄中存在的 .git/ 資料夾都將被忽略。但是,請注意,.gitignore 檔案不會被考慮在內。
內部使用了 HfApi.create_commit。
引發以下錯誤
HTTPError如果 HuggingFace API 返回錯誤ValueError如果某些引數值無效
upload_folder假定倉庫已存在於 Hub 上。如果您收到 Client error 404,請確保您已進行身份驗證,並且repo_id和repo_type設定正確。如果倉庫不存在,請先使用 create_repo() 建立它。
當處理大型資料夾(數千個檔案或數百 GB)時,建議使用 upload_large_folder() 代替。
示例
# Upload checkpoints folder except the log files
>>> upload_folder(
... folder_path="local/checkpoints",
... path_in_repo="remote/experiment/checkpoints",
... repo_id="username/my-dataset",
... repo_type="datasets",
... token="my_token",
... ignore_patterns="**/logs/*.txt",
... )
# Upload checkpoints folder including logs while deleting existing logs from the repo
# Useful if you don't know exactly which log files have already being pushed
>>> upload_folder(
... folder_path="local/checkpoints",
... path_in_repo="remote/experiment/checkpoints",
... repo_id="username/my-dataset",
... repo_type="datasets",
... token="my_token",
... delete_patterns="**/logs/*.txt",
... )
# Upload checkpoints folder while creating a PR
>>> upload_folder(
... folder_path="local/checkpoints",
... path_in_repo="remote/experiment/checkpoints",
... repo_id="username/my-dataset",
... repo_type="datasets",
... token="my_token",
... create_pr=True,
... )upload_large_folder
< source >( repo_id: str folder_path: Union[str, Path] repo_type: str revision: Optional[str] = None private: Optional[bool] = None allow_patterns: Optional[Union[list[str], str]] = None ignore_patterns: Optional[Union[list[str], str]] = None num_workers: Optional[int] = None print_report: bool = True print_report_every: int = 60 )
引數
- repo_id (
str) — 要上傳檔案的儲存庫。例如"HuggingFaceTB/smollm-corpus"。 - folder_path (
str或Path) — 要上傳到本地檔案系統的資料夾路徑。 - repo_type (
str) — 儲存庫的型別。必須是"model"、"dataset"或"space"之一。與所有其他HfApi方法不同,此處顯式需要repo_type。這是為了避免在上傳大型資料夾到 Hub 時出現任何錯誤,從而防止需要重新上傳所有內容。 - revision (
str, optional) — 要提交到的分支。如果未提供,則使用main分支。 - private (
bool, optional) — 儲存庫是否應為私有。如果為None(預設值),則儲存庫將公開,除非組織的預設設定是私有的。 - allow_patterns (
list[str]或str, optional) — 如果提供,則只上傳匹配至少一個模式的檔案。 - ignore_patterns (
list[str]或str, optional) — 如果提供,則不上傳匹配任何模式的檔案。 - num_workers (
int, optional) — 要啟動的工作執行緒數。預設為 CPU 核心數的一半(最少 1)。如果您的機器允許,更多的執行緒數可能會加快程序。但是,在連線速度較慢的機器上,建議將執行緒數保持較低以確保更好的可恢復性。事實上,如果程序中斷,部分上傳的檔案將被迫完全重新上傳。 - print_report (
bool, optional) — 是否列印上傳進度的報告。預設為 True。報告會列印到sys.stdout,每 X 秒(預設為 60 秒)會覆蓋之前的報告。 - print_report_every (
int, optional) — 列印報告的頻率。預設為 60 秒。
以儘可能可靠的方式將大型資料夾上傳到 Hub。
啟動多個工作執行緒以最佳化檔案上傳。在提交到儲存庫之前,檔案必須進行雜湊處理,並且 LFS 檔案需要預先上傳。工作執行緒將為資料夾中的每個檔案執行這些任務。在每個步驟中,有關上傳過程的一些元資料資訊儲存在資料夾中的 .cache/.huggingface/ 下,以便在程序中斷時能夠恢復。整個過程可能導致多次提交。
需要注意的幾點
- 儲存庫限制仍然適用: https://huggingface.co/docs/hub/repositories-recommendations
- 不要並行啟動多個程序。
- 您可以隨時中斷和恢復程序。
- 請勿將同一個資料夾上傳到多個儲存庫。如果需要這樣做,必須首先刪除本地的
.cache/.huggingface/資料夾。
雖然
upload_large_folder在上傳大型資料夾方面更加健壯,但在功能上比 upload_folder() 更有限。實際上
- 您無法設定自定義的
path_in_repo。如果您想上傳到子資料夾,則需要將正確的結構設定在本地。- 由於會建立多個提交,因此您無法設定自定義的
commit_message和commit_description。- 上傳過程中無法從儲存庫中刪除。請先進行單獨的提交。
- 無法直接建立 PR。請先建立 PR(透過 UI 或使用 create_pull_request()),然後透過傳遞
revision來提交到該 PR。
技術細節
upload_large_folder 程序如下:
- (檢查引數並進行設定。)
- 如果缺少,則建立儲存庫。
- 列出要上傳的本地檔案。
- 執行驗證檢查,並在可能超過儲存庫限制時顯示警告。
- 如果檔案總數超過 100k(建議限制),則發出警告。
- 如果任何資料夾包含超過 10k 個檔案(建議限制),則發出警告。
- 警告檔案大小超過 20GB(建議)或 50GB(硬限制)。
- 啟動工作執行緒。工作執行緒可以執行以下任務:
- 雜湊檔案。
- 獲取一系列檔案的上傳模式(普通或 LFS)。
- 預先上傳 LFS 檔案。
- 提交一組檔案。一個工作執行緒完成一項任務後,它將根據優先順序列表(如下文所示)繼續執行下一項任務,直到所有檔案都上傳並提交。
- 在工作執行緒執行時,定期向 sys.stdout 列印報告。
優先順序順序
- 如果距離上次提交嘗試超過 5 分鐘(且至少有 1 個檔案),則提交。
- 如果至少有 150 個檔案準備好提交,則提交。
- 如果至少有 10 個檔案已雜湊,則獲取上傳模式。
- 如果至少有 1 個檔案且沒有工作執行緒在預先上傳,則預先上傳 LFS 檔案。
- 如果至少有 1 個檔案且沒有工作執行緒在雜湊,則雜湊檔案。
- 如果至少有 1 個檔案需要獲取上傳模式,則獲取上傳模式。
- 如果至少有 1 個檔案需要預先上傳 LFS,則預先上傳 LFS 檔案。
- 如果至少有 1 個檔案需要雜湊,則雜湊檔案。
- 如果至少有 1 個檔案需要獲取上傳模式,則獲取上傳模式。
- 如果至少有 1 個檔案需要提交且距離上次提交嘗試至少有 1 分鐘,則提交。
- 如果至少有 1 個檔案需要提交且所有其他佇列都為空,則提交。
特殊規則
- 一次只能有一個工作執行緒進行提交。
- 如果沒有可用任務,工作執行緒將等待 10 秒後再檢查。
verify_repo_checksums
< source >( repo_id: str repo_type: Optional[str] = None revision: Optional[str] = None local_dir: Optional[Union[str, Path]] = None cache_dir: Optional[Union[str, Path]] = None token: Union[str, bool, None] = None ) → FolderVerification
引數
- repo_id (
str) — 由/分隔的名稱空間(使用者或組織)和儲存庫名稱。 - repo_type (
str, optional) — 要從中獲取樹的儲存庫型別("model"、"dataset"或"space")。預設為"model"。 - revision (
str, optional) — 要從中獲取樹的儲存庫修訂版本。預設為"main"分支。 - local_dir (
str或Path, optional) — 要驗證的本地目錄。 - cache_dir (
str或Path, optional) — 要驗證的快取目錄。 - token (Union[bool, str, None], optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞
False。
返回
FolderVerification
一個包含驗證詳情的結構化結果。
- RepositoryNotFoundError — 如果倉庫未找到(錯誤 404):repo_id/repo_type 錯誤,私有但未經驗證或倉庫不存在。
- RevisionNotFoundError — 如果在儲存庫中找不到 revision(錯誤 404)。
驗證儲存庫的本地檔案與 Hub 的校驗和。
whoami
< source >( token: Union[bool, str, None] = None cache: bool = False )
引數
- token (
bool或str, optional) — 一個有效的使用者訪問令牌(字串)。預設為本地儲存的令牌,這是推薦的身份驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。要停用身份驗證,請傳遞False。 - cache (
bool, optional) — 是否快取whoami呼叫結果以供後續呼叫。如果第一次呼叫時發生錯誤,則不會快取。預設為False。
呼叫 HF API 以瞭解“我是誰”。
如果傳遞 cache=True,則該結果將在 Python 程序的整個生命週期內被快取以供後續呼叫。如果您計劃多次呼叫 whoami,這會很有用,因為出於安全原因,此端點會受到嚴格的速率限制。
API 資料類
AccessRequest
class huggingface_hub.hf_api.AccessRequest
< source >( username: str fullname: str email: Optional[str] timestamp: datetime status: Literal['pending', 'accepted', 'rejected'] fields: Optional[dict[str, Any]] = None )
引數
- username (
str) — 使用者請求訪問的使用者名稱。 - fullname (
str) — 使用者請求訪問的全名。 - email (
Optional[str]) — 使用者請求訪問的電子郵件。當用戶被手動授予訪問許可權時,在 `/accepted` 列表中可能為None。 - timestamp (
datetime) — 請求的時間戳。 - status (
Literal["pending", "accepted", "rejected"]) — 請求的狀態。可以是["pending", "accepted", "rejected"]中的一個。 - fields (
Optional[dict[str, Any]] = None) — 使用者在門禁表格中填寫的附加欄位。
包含使用者訪問請求資訊的結構體。
DatasetInfo
class huggingface_hub.CommitInfo
< source >( *args commit_url: str **kwargs )
引數
- commit_url (
str) — 找到提交的 URL。 - commit_message (
str) — 已建立提交的摘要(第一行)。 - commit_description (
str) — 已建立提交的描述。可以為空。 - oid (
str) — Commit hash ID。例如:"91c54ad1727ee830252e457677f467be0bfd8a57"。 - pr_url (
str, optional) — 已建立 PR 的 URL,如果有的話。當傳遞create_pr=True時填充。 - pr_revision (
str, optional) — 已建立 PR 的修訂版本,如果有的話。當傳遞create_pr=True時填充。例如:"refs/pr/1"。 - pr_num (
int, optional) — 已建立 PR 的編號,如果有的話。當傳遞create_pr=True時填充。可以作為discussion_num傳遞到 get_discussion_details()。例如:1。 - repo_url (
RepoUrl) — 包含 repo_id、repo_type 等資訊的提交倉庫 URL。
包含新建立提交資訊的結構體。
由任何在 Hub 上建立提交的方法返回: create_commit()、 upload_file()、 upload_folder()、 delete_file()、 delete_folder()。為向後相容而繼承自 str,但使用 str 特有的方法已棄用。
DatasetInfo
class huggingface_hub.DatasetInfo
< source >( **kwargs )
引數
- id (
str) — 資料集的 ID。 - author (
str) — 資料集的作者。 - sha (
str) — 在此特定修訂版本下的倉庫 SHA。 - created_at (
datetime, optional) — 倉庫在 Hub 上建立的日期。注意,最低值是2022-03-02T23:29:04.000Z,對應於我們開始儲存建立日期的日期。 - last_modified (
datetime, optional) — 倉庫最後一次提交的日期。 - private (
bool) — 倉庫是否私有。 - disabled (
bool, optional) — 倉庫是否被停用。 - gated (
Literal["auto", "manual", False], optional) — 倉庫是否被門控。如果是,是手動還是自動批准。 - downloads (
int) — 資料集在過去 30 天內的下載次數。 - downloads_all_time (
int) — 模型自建立以來的累計下載次數。 - likes (
int) — 資料集的點贊數。 - tags (
list[str]) — 資料集的標籤列表。 - card_data (
DatasetCardData, 可選) — 模型卡元資料,作為 huggingface_hub.repocard_data.DatasetCardData 物件。 - siblings (
list[RepoSibling]) — 構成資料集的 huggingface_hub.hf_api.RepoSibling 物件列表。 - paperswithcode_id (
str, 可選) — 資料集的 Papers with code ID。 - trending_score (
int, 可選) — 資料集的 trending score。
包含有關 Hub 上資料集的資訊。此物件由 dataset_info() 和 list_datasets() 返回。
此類的大多數屬性都是可選的。這是因為 Hub 返回的資料取決於查詢。通常,查詢越具體,返回的資訊就越多。相反,在使用 list_datasets() 列出資料集時,只返回一部分屬性。
DryRunFileInfo
class huggingface_hub.DryRunFileInfo
< source >( commit_hash: str file_size: int filename: str local_path: str is_cached: bool will_download: bool )
在執行檔案下載的 dry run 時返回的資訊。
當 dry_run=True 時,由 hf_hub_download() 返回。
GitRefInfo
class huggingface_hub.GitRefInfo
< source >( name: str ref: str target_commit: str )
包含有關 Hub 上倉庫的 git 引用的資訊。
GitCommitInfo
class huggingface_hub.GitCommitInfo
< source >( commit_id: str authors: list[str] created_at: datetime title: str message: str formatted_title: Optional[str] formatted_message: Optional[str] )
引數
- commit_id (
str) — commit 的 OID (例如"e7da7f221d5bf496a48136c0cd264e630fe9fcc8") - authors (
list[str]) — commit 的作者列表。 - created_at (
datetime) — commit 建立的時間。 - title (
str) — commit 的標題。這是作者輸入的自由文字。 - message (
str) — commit 的描述。這是作者輸入的自由文字。 - formatted_title (
str) — 格式化為 HTML 的 commit 標題。僅當設定了formatted=True時返回。 - formatted_message (
str) — 格式化為 HTML 的 commit 描述。僅當設定了formatted=True時返回。
包含有關 Hub 上倉庫的 git commit 的資訊。有關更多詳細資訊,請檢視 list_repo_commits()。
GitRefs
class huggingface_hub.GitRefs
< source >( branches: list[GitRefInfo] converts: list[GitRefInfo] tags: list[GitRefInfo] pull_requests: Optional[list[GitRefInfo]] = None )
引數
- branches (
list[GitRefInfo]) — 包含有關儲存庫中分支資訊的 GitRefInfo 列表。 - converts (
list[GitRefInfo]) — 包含有關儲存庫中“convert”引用的 GitRefInfo 列表。Convert 是(內部)用於在 Dataset 儲存庫中推送預處理資料的引用。 - tags (
list[GitRefInfo]) — 包含有關儲存庫中標籤資訊的 GitRefInfo 列表。 - pull_requests (
list[GitRefInfo], optional) — 包含有關儲存庫中拉取請求資訊的 GitRefInfo 列表。僅當設定了include_prs=True時返回。
包含有關 Hub 上儲存庫的所有 git 引用的資訊。
由 list_repo_refs() 返回的物件。
InferenceProviderMapping
LFSFileInfo
class huggingface_hub.hf_api.LFSFileInfo
< source >( **kwargs )
包含有關 Hub 上儲存為 LFS 的檔案的資訊。
在列出和永久刪除儲存庫中的 LFS 檔案以釋放空間時使用。有關更多詳細資訊,請參閱 list_lfs_files() 和 permanently_delete_lfs_files()。
Git LFS 檔案使用 SHA-256 物件 ID 進行跟蹤,而不是檔案路徑,以最佳化效能。此方法是必需的,因為單個物件可以被不同提交中的多個路徑引用,因此搜尋和解析這些引用很不方便。請檢視 我們的文件,瞭解如何知道與每個 SHA 關聯的檔名。
示例
>>> from huggingface_hub import HfApi
>>> api = HfApi()
>>> lfs_files = api.list_lfs_files("username/my-cool-repo")
# Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`.
# e.g. select only LFS files in the "checkpoints" folder
>>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/"))
# Permanently delete LFS files
>>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete)ModelInfo
class huggingface_hub.ModelInfo
< source >( **kwargs )
引數
- id (
str) — 模型的 ID。 - author (
str, optional) — 模型的作者。 - sha (
str, optional) — 該版本庫在此特定修訂版的 SHA。 - created_at (
datetime, optional) — 儲存庫在 Hub 上建立的日期。請注意,最小值是2022-03-02T23:29:04.000Z,對應於我們開始儲存建立日期的日期。 - last_modified (
datetime, optional) — 儲存庫的最後一次提交日期。 - private (
bool) — 儲存庫是否為私有。 - disabled (
bool, optional) — 儲存庫是否已停用。 - downloads (
int) — 模型在過去 30 天內的下載次數。 - downloads_all_time (
int) — 模型自建立以來的累計下載次數。 - gated (
Literal["auto", "manual", False], optional) — 儲存庫是否受限制。如果是,是手動還是自動批准。 - gguf (
dict, optional) — 模型的 GGUF 資訊。 - inference (
Literal["warm"], optional) — 模型在推理提供商上的狀態。如果模型由至少一個提供商提供服務,則為 Warm。 - inference_provider_mapping (
list[InferenceProviderMapping], 可選) — 使用者提供者順序之後的InferenceProviderMapping列表。 - likes (
int) — 模型的點贊數。 - library_name (
str, 可選) — 與模型關聯的庫。 - tags (
list[str]) — 模型的標籤列表。與card_data.tags相比,包含 Hub 計算出的額外標籤(例如,支援的庫、模型的 arXiv 連結)。 - pipeline_tag (
str, 可選) — 與模型關聯的 Pipeline 標籤。 - mask_token (
str, 可選) — 模型使用的 Mask 標記。 - widget_data (
Any, 可選) — 與模型關聯的小部件資料。 - model_index (
dict, 可選) — 用於評估的模型索引。 - config (
dict, 可選) — 模型配置。 - transformers_info (
TransformersInfo, 可選) — 與模型關聯的特定於 Transformers 的資訊(自動類、處理器等)。 - trending_score (
int, 可選) — 模型的趨勢得分。 - card_data (
ModelCardData, 可選) — 模型卡元資料,是一個 huggingface_hub.repocard_data.ModelCardData 物件。 - siblings (
list[RepoSibling]) — 構成模型的 huggingface_hub.hf_api.RepoSibling 物件列表。 - spaces (
list[str], 可選) — 使用該模型的空間列表。 - safetensors (
SafeTensorsInfo, 可選) — 模型的 safetensors 資訊。 - security_repo_status (
dict, 可選) — 模型的安全掃描狀態。 - eval_results (
list[EvalResultEntry], 可選) — 模型的評估結果。
包含有關 Hub 上模型的 M資訊。
此類的大多數屬性都是可選的。這是因為 Hub 返回的資料取決於所進行的查詢。一般來說,查詢越具體,返回的資訊就越多。相反,當使用 list_models() 列出模型時,只返回屬性的一個子集。
RepoSibling
class huggingface_hub.hf_api.RepoSibling
< source >( rfilename: str size: Optional[int] = None blob_id: Optional[str] = None lfs: Optional[BlobLfsInfo] = None )
引數
- rfilename (str) — 倉庫根目錄下的檔名。
- size (
int, 可選) — 檔案的大小(以位元組為單位)。當 repo_info() 的files_metadata引數設定為True時定義此屬性。否則為None。 - blob_id (
str, 可選) — 檔案的 git OID。當 repo_info() 的files_metadata引數設定為True時定義此屬性。否則為None。 - lfs (
BlobLfsInfo, 可選) — 檔案的 LFS 元資料。當 repo_info() 的files_metadata引數設定為True並且檔案使用 Git LFS 儲存時定義此屬性。否則為None。
包含有關 Hub 上倉庫中單個檔案的基本資訊。
此類所有屬性都是可選的,除了
rfilename。當在 Hub 上列出倉庫時(使用 list_models()、list_datasets() 或 list_spaces()),只返回檔名。如果你需要更多資訊,如檔案大小、blob ID 或 lfs 詳細資訊,你必須從一次一個倉庫中專門請求它們(使用 model_info()、dataset_info() 或 space_info()),因為這會增加從後端伺服器檢索這些資訊的限制。
RepoFile
class huggingface_hub.RepoFile
< source >( **kwargs )
引數
- path (str) — 檔案在倉庫根目錄下的路徑。
- size (
int) — 檔案的大小(以位元組為單位)。 - blob_id (
str) — 檔案的 git OID。 - lfs (
BlobLfsInfo, 可選) — 檔案的 LFS 元資料。 - last_commit (
LastCommitInfo, 可選) — 檔案的最後一次提交元資料。僅當使用 list_repo_tree() 和 get_paths_info() 且expand=True時才定義。 - security (
BlobSecurityInfo, optional) — 檔案的安全掃描元資料。僅當 list_repo_tree() 和 get_paths_info() 呼叫時傳入expand=True時才定義。
包含有關 Hub 上檔案的資訊。
RepoUrl
class huggingface_hub.RepoUrl
< source >( url: Any endpoint: Optional[str] = None )
引數
- url (
Any) — 倉庫 URL 的字串值。 - endpoint (
str, optional) — Hub 的端點。預設為 https://huggingface.co。
引發
ValueError
ValueError— 如果 URL 無法解析。ValueError— 如果repo_type未知。
繼承自 str,描述 Hub 上的倉庫 URL。
RepoUrl 由 HfApi.create_repo 返回。為向後相容,它繼承自 str。在初始化時,URL 會被解析以填充屬性。
- endpoint (
str) - namespace (
Optional[str]) - repo_name (
str) - repo_id (
str) - repo_type (
Literal["model", "dataset", "space"]) - url (
str)
示例
>>> RepoUrl('https://huggingface.co/gpt2')
RepoUrl('https://huggingface.co/gpt2', endpoint='https://huggingface.co', repo_type='model', repo_id='gpt2')
>>> RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co')
RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co', repo_type='dataset', repo_id='dummy_user/dummy_dataset')
>>> RepoUrl('hf://datasets/my-user/my-dataset')
RepoUrl('hf://datasets/my-user/my-dataset', endpoint='https://huggingface.co', repo_type='dataset', repo_id='user/dataset')
>>> HfApi.create_repo("dummy_model")
RepoUrl('https://huggingface.co/Wauplin/dummy_model', endpoint='https://huggingface.co', repo_type='model', repo_id='Wauplin/dummy_model')SafetensorsRepoMetadata
class huggingface_hub.utils.SafetensorsRepoMetadata
< source >( metadata: typing.Optional[dict] sharded: bool weight_map: dict files_metadata: dict )
引數
- metadata (
dict, optional) — 如果存在“model.safetensors.index.json”檔案,則其中包含的元資料。僅為分片模型填充。 - sharded (
bool) — 倉庫是否包含分片模型。 - weight_map (
dict[str, str]) — 所有權重的對映。鍵是張量名稱,值是包含張量的檔名。 - files_metadata (
dict[str, SafetensorsFileMetadata]) — 所有檔案元資料的對映。鍵是檔名,值是相應檔案的元資料,形式為SafetensorsFileMetadata物件。 - parameter_count (
dict[str, int]) — 每個資料型別的引數數量的對映。鍵是資料型別,值是該資料型別的引數數量。
Safetensors 倉庫的元資料。
如果倉庫在其根目錄包含“model.safetensors”權重檔案(非分片模型)或“model.safetensors.index.json”索引檔案(分片模型),則該倉庫被視為 Safetensors 倉庫。
該類由 get_safetensors_metadata() 返回。
有關 safetensors 格式的更多詳細資訊,請檢視 https://huggingface.co/docs/safetensors/index#format。
SafetensorsFileMetadata
class huggingface_hub.utils.SafetensorsFileMetadata
< source >( metadata: dict tensors: dict )
Hub 上的 Safetensors 檔案的元資料。
該類由 parse_safetensors_file_metadata() 返回。
有關 safetensors 格式的更多詳細資訊,請檢視 https://huggingface.co/docs/safetensors/index#format。
SpaceInfo
class huggingface_hub.SpaceInfo
< source >( **kwargs )
引數
- id (
str) — Space 的 ID。 - author (
str, optional) — Space 的作者。 - sha (
str, optional) — 在此特定修訂版本下的倉庫 SHA。 - created_at (
datetime, optional) — 倉庫在 Hub 上建立的日期。注意,最小值為2022-03-02T23:29:04.000Z,對應於我們開始儲存建立日期的日期。 - last_modified (
datetime, optional) — 倉庫最後一次提交的日期。 - private (
bool) — 倉庫是否為私有。 - gated (
Literal["auto", "manual", False], optional) — 倉庫是否受保護。如果是,則為手動或自動批准。 - disabled (
bool, optional) — Space 是否被停用。 - host (
str, optional) — Space 的主機 URL。 - subdomain (
str, optional) — Space 的子域。 - likes (
int) — Space 的點贊數。 - tags (
list[str]) — Space 的標籤列表。 - siblings (
list[RepoSibling]) — 構成 Space 的 huggingface_hub.hf_api.RepoSibling 物件列表。 - card_data (
SpaceCardData, optional) — Space 卡的元資料,作為 huggingface_hub.repocard_data.SpaceCardData 物件。 - runtime (
SpaceRuntime, optional) — Space 執行時資訊,作為 huggingface_hub.hf_api.SpaceRuntime 物件。 - sdk (
str, optional) — Space 使用的 SDK。 - models (
list[str], optional) — Space 使用的模型列表。 - datasets (
list[str], optional) — Space 使用的資料集列表。 - trending_score (
int, optional) — Space 的熱門程度得分。
包含有關 Hub 上 Space 的資訊。此物件由 space_info() 和 list_spaces() 返回。
此類的大多數屬性都是可選的。這是因為 Hub 返回的資料取決於查詢。通常,查詢越具體,返回的資訊就越多。相反,在使用 list_spaces() 列出 Spaces 時,只返回一部分屬性。
TensorInfo
class huggingface_hub.utils.TensorInfo
< source >( dtype: typing.Literal['F64', 'F32', 'F16', 'BF16', 'I64', 'I32', 'I16', 'I8', 'U8', 'BOOL'] shape: list data_offsets: tuple )
張量資訊。
有關 safetensors 格式的更多詳細資訊,請檢視 https://huggingface.co/docs/safetensors/index#format。
User
class huggingface_hub.User
< source >( **kwargs )
引數
- username (
str) — 使用者在 Hub 上的名稱(唯一)。 - fullname (
str) — 使用者的全名。 - avatar_url (
str) — 使用者頭像的 URL。 - details (
str, optional) — 使用者的詳細資訊。 - is_following (
bool, optional) — 認證使用者是否關注此使用者。 - is_pro (
bool, optional) — 使用者是否是 pro 使用者。 - num_models (
int, optional) — 使用者建立的模型數量。 - num_datasets (
int, optional) — 使用者建立的資料集數量。 - num_spaces (
int, optional) — 使用者建立的 Space 數量。 - num_discussions (
int, optional) — 使用者發起的討論數量。 - num_papers (
int, optional) — 使用者撰寫的論文數量。 - num_upvotes (
int, optional) — 使用者收到的點贊數。 - num_likes (
int, optional) — 使用者給的讚的數量。 - num_following (
int, optional) — 該使用者正在關注的使用者數量。 - num_followers (
int, optional) — 關注此使用者的使用者數量。 - orgs (list of
Organization) — 使用者所屬的組織列表。
包含有關 Hub 上使用者的資訊。
UserLikes
class huggingface_hub.UserLikes
< source >( user: str total: int datasets: list[str] models: list[str] spaces: list[str] )
包含有關 Hub 上使用者點讚的資訊。
WebhookInfo
class huggingface_hub.WebhookInfo
< source >( id: str url: Optional[str] job: Optional[JobSpec] watched: list[WebhookWatchedItem] domains: list[constants.WEBHOOK_DOMAIN_T] secret: Optional[str] disabled: bool )
引數
- id (
str) — Webhook 的 ID。 - url (
str, optional) — Webhook 的 URL。 - job (
JobSpec, optional) — 要觸發的 Job 的規格。 - watched (
list[WebhookWatchedItem]) — Webhook 正在監視的項列表,請參閱 WebhookWatchedItem。 - domains (
list[WEBHOOK_DOMAIN_T]) — Webhook 正在監視的域列表。可以是["repo", "discussions"]中的一個。 - secret (
str, optional) — Webhook 的 secret。 - disabled (
bool) — Webhook 是否已停用。
包含有關 webhook 的資訊的 DTA。
指定了 url 或 job,但不能同時指定兩者。
WebhookWatchedItem
class huggingface_hub.WebhookWatchedItem
< source >( type: Literal['dataset', 'model', 'org', 'space', 'user'] name: str )
包含有關 webhook 監視項資訊的 DTA。
CommitOperation
以下是 CommitOperation() 支援的值
class huggingface_hub.CommitOperationAdd
< source >( path_in_repo: str path_or_fileobj: typing.Union[str, pathlib.Path, bytes, typing.BinaryIO] )
引數
- path_in_repo (
str) — 倉庫中的相對檔案路徑,例如:"checkpoints/1fec34a/weights.bin" - path_or_fileobj (
str,Path,bytes, orBinaryIO) — 要上傳的:- 本地檔案的路徑(
str或pathlib.Path) - 包含要上傳檔案的內容的位元組緩衝區(
bytes) - 一個“檔案物件”(
io.BufferedIOBase的子類),通常透過open(path, "rb")獲取。它必須支援seek()和tell()方法。
- 本地檔案的路徑(
引發
ValueError
ValueError— 如果path_or_fileobj不是str、Path、bytes或io.BufferedIOBase之一。ValueError— 如果path_or_fileobj是str或Path,但不是現有檔案的路徑。ValueError— 如果path_or_fileobj是io.BufferedIOBase,但它不支援seek()和tell()方法。
用於將檔案上傳到 Hub 倉庫所需資訊的結構。
as_file
< source >( with_tqdm: bool = False )
一個上下文管理器,它生成一個類檔案物件,允許讀取 path_or_fileobj 後面的底層資料。
示例
>>> operation = CommitOperationAdd(
... path_in_repo="remote/dir/weights.h5",
... path_or_fileobj="./local/weights.h5",
... )
CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5')
>>> with operation.as_file() as file:
... content = file.read()
>>> with operation.as_file(with_tqdm=True) as file:
... while True:
... data = file.read(1024)
... if not data:
... break
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
>>> with operation.as_file(with_tqdm=True) as file:
... httpx.put(..., data=file)
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]class huggingface_hub.CommitOperationDelete
< source >( path_in_repo: str is_folder: typing.Union[bool, typing.Literal['auto']] = 'auto' )
用於將檔案或資料夾從 Hub 倉庫刪除所需資訊的結構。
class huggingface_hub.CommitOperationCopy
< source >( src_path_in_repo: str path_in_repo: str src_revision: typing.Optional[str] = None _src_oid: typing.Optional[str] = None _dest_oid: typing.Optional[str] = None )
用於將檔案複製到 Hub 倉庫所需資訊的結構。
侷限性
- 只能複製 LFS 檔案。要複製普通檔案,需要先將其下載到本地然後重新上傳。
- 不支援跨倉庫複製。
注意:可以組合使用 CommitOperationCopy 和 CommitOperationDelete 來重新命名 Hub 上的 LFS 檔案。
CommitScheduler
class huggingface_hub.CommitScheduler
< source >( repo_id: str folder_path: typing.Union[str, pathlib.Path] every: typing.Union[int, float] = 5 path_in_repo: typing.Optional[str] = None repo_type: typing.Optional[str] = None revision: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Optional[str] = None allow_patterns: typing.Union[list[str], str, NoneType] = None ignore_patterns: typing.Union[list[str], str, NoneType] = None squash_history: bool = False hf_api: typing.Optional[ForwardRef('HfApi')] = None )
引數
- repo_id (
str) — 要提交到的倉庫 ID。 - folder_path (
str或Path) — 要定期上傳的本地資料夾路徑。 - every (
int或float, optional) — 每次提交之間的分鐘數。預設為 5 分鐘。 - path_in_repo (
str, optional) — 倉庫中目錄的相對路徑,例如:"checkpoints/"。預設為倉庫的根目錄。 - repo_type (
str, optional) — 要提交到的倉庫型別。預設為model。 - revision (
str, optional) — 要提交到的倉庫修訂版本。預設為main。 - private (
bool, optional) — 是否將倉庫設為私有。如果為None(預設值),則倉庫將為公共的,除非組織預設設定為私有。如果倉庫已存在,則忽略此值。 - token (
str, optional) — 用於提交到倉庫的 token。預設為儲存在機器上的 token。 - allow_patterns (
list[str]或str, optional) — 如果提供,則只上傳匹配至少一個模式的檔案。 - ignore_patterns (
list[str]或str, optional) — 如果提供,則不上傳匹配任何模式的檔案。 - squash_history (
bool, optional) — 是否在每次提交後壓縮倉庫歷史記錄。預設為False。壓縮提交有助於避免倉庫在增大後效能下降。 - hf_api (
HfApi, optional) — 用於提交到 Hub 的 HfApi 客戶端。可以設定自定義設定(使用者代理、token 等)。
定期將本地資料夾上傳到 Hub 的排程器(例如,每 5 分鐘推送一次)。
推薦使用排程器的方式是將其作為上下文管理器使用。這確保了排程器在指令碼結束時被正確停止並觸發最後一次提交。排程器也可以透過 stop 方法手動停止。請檢視 上傳指南 瞭解更多關於如何使用它的資訊。
示例
>>> from pathlib import Path
>>> from huggingface_hub import CommitScheduler
# Scheduler uploads every 10 minutes
>>> csv_path = Path("watched_folder/data.csv")
>>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)
>>> with csv_path.open("a") as f:
... f.write("first line")
# Some time later (...)
>>> with csv_path.open("a") as f:
... f.write("second line")使用上下文管理器的示例
>>> from pathlib import Path
>>> from huggingface_hub import CommitScheduler
>>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler:
... csv_path = Path("watched_folder/data.csv")
... with csv_path.open("a") as f:
... f.write("first line")
... (...)
... with csv_path.open("a") as f:
... f.write("second line")
# Scheduler is now stopped and last commit have been triggered將資料夾推送到 Hub 並返回提交資訊。
此方法不應直接呼叫。它在後臺由排程器執行,並遵循佇列機制以避免併發提交。直接呼叫此方法可能會導致併發問題。
push_to_hub 的預設行為是假定一個追加式資料夾。它會列出資料夾中的所有檔案,並僅上傳已更改的檔案。如果未找到更改,則該方法將返回而不進行任何提交。如果您想更改此行為,可以繼承自 CommitScheduler 並覆蓋此方法。例如,這對於在提交之前將資料壓縮到單個檔案中很有用。有關更多詳細資訊和示例,請參閱我們的 整合指南。
觸發一個 push_to_hub 操作並返回一個 future。
此方法每 every 分鐘自動呼叫一次。您也可以手動呼叫它以立即觸發一次提交,而無需等待下一次計劃的提交。