Hub Python 函式庫文件
HfApi 用戶端
並獲得增強的文件體驗
開始使用
HfApi 用戶端
以下是 HfApi 類別的說明文件,該類別作為 Hugging Face Hub API 的 Python 封裝程式。
HfApi 中的所有方法也可以直接從該套件的根目錄存取。兩種方法詳述如下。
使用根方法更為直接,但 HfApi 類別能為您提供更大的靈活性。特別是,您可以傳入一個權杖 (token),該權杖將在所有 HTTP 呼叫中重複使用。這與 hf auth login 或 login() 不同,因為權杖不會儲存在本機機器上。您也可以提供不同的端點或設定自訂的 user-agent。
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: str | None = None token: str | bool | None = None library_name: str | None = None library_version: str | None = None user_agent: dict | str | None = None headers: dict[str, str] | None = None )
參數
- endpoint (
str, 選填) — Hub 的端點。預設為 https://huggingface.co。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - library_name (
str, 選填) — 發起 HTTP 請求的函式庫名稱。將會新增至 user-agent 標頭中。範例:"transformers"。 - library_version (
str, 選填) — 發起 HTTP 請求的函式庫版本。將會新增至 user-agent 標頭中。範例:"4.24.0"。 - user_agent (
str,dict, 選填) — 以字典或單一字串形式呈現的 user-agent 資訊。它將會補全關於已安裝套件的資訊。 - headers (
dict, 選填) — 隨每次請求發送的額外標頭。範例:{"X-My-Header": "value"}。在此處傳入的標頭優先於預設標頭。
透過 HTTP 與 Hugging Face Hub 互動的用戶端。
該用戶端在初始化時會設定用於所有發送至 Hub 請求的高階設定(HF 端點、驗證、user agents 等)。使用 HfApi 用戶端是推薦的做法,但並非強制,因為其所有公開方法都會直接暴露在 huggingface_hub 的根目錄下。
accept_access_request
< 原始碼 >( repo_id: str user: str repo_type: str | None = None token: bool | str | None = None )
參數
- repo_id (
str) — 要接受存取請求的儲存庫識別碼。 - user (
str) — 要接受其存取請求的使用者名稱。 - repo_type (
str, 選填) — 要接受存取請求的儲存庫類型。必須是model、dataset或space其中之一。預設為model。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
引發
HfHubHTTPError
HfHubHTTPError— 若儲存庫未設為閘控 (gated),則回應 HTTP 400。HfHubHTTPError— 若您對儲存庫僅有唯讀權限,則回應 HTTP 403。如果您在該儲存庫所屬的組織中沒有write或admin角色,或如果您傳入的是read權杖,就會發生此情況。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: str | None = None exists_ok: bool = False token: bool | str | None = None )
參數
- collection_slug (
str) — 要更新的集合 slug。範例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。 - item_id (
str) — 要新增至集合的項目識別碼。對於儲存庫/空間/資料集,請使用 repo_id;對於論文,請使用論文 ID;對於另一個集合,請使用其 slug(例如"moonshotai/kimi-k2");或使用儲存桶 ID(例如"namespace/bucket-name")。 - item_type (
str) — 要新增的項目類型。可以是"model"、"dataset"、"space"、"paper"、"collection"或"bucket"其中之一。 - 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角色,或如果您傳入的是read權杖,就會發生此情況。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
< 原始碼 >( repo_id: str key: str value: str description: str | None = None token: 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。
在 Space 中新增或更新祕密。
祕密允許將祕密金鑰或權杖設定至 Space 中,而無需將其寫死在程式碼中。欲知詳情,請參閱 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。
add_space_variable
< 原始碼 >( repo_id: str key: str value: str description: str | None = None token: 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
< 原始碼 >( repo_id: str repo_type: str | None = None token: bool | str | None = None write: bool = False )
參數
- 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。 - write (
bool, 選填) — 若為True,則檢查使用者是否對該儲存庫具有寫入權限。若為False(預設),則僅檢查讀取權限。
-
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.")在此範例中
- 如果使用者具有存取權,該方法將成功完成。
- 如果儲存庫設為閘控或不存在,將會引發適當的例外狀況,使用者可據此進行處理。
batch_bucket_files
< 原始碼 >( bucket_id: str add: list[tuple[str | Path | bytes, str]] | None = None copy: list[tuple[str, str, str, str]] | None = None delete: list[str] | None = None token: str | bool | None = None )
參數
- bucket_id (
str) — 儲存桶 ID(例如"username/my-bucket")。 - add (
listoftuple, 選填) — 要上傳的檔案。每個元素為一個(source, destination)元組,其中source為本地檔案路徑(str或Path)或原始bytes內容,destination為儲存桶中的路徑。 - copy (
listoftuple, 選填) — 透過 xet hash 複製的檔案。每個元素為一個(source_repo_type, source_repo_id, xet_hash, destination)元組:source_repo_type為來源儲存庫類型:"model"、"dataset"、"space"或"bucket"。source_repo_id為來源儲存庫或儲存桶的 ID(例如"username/my-model")。xet_hash為要複製的檔案之 xet hash。destination為儲存桶中的目標路徑。這是一項伺服器端操作 — 不會下載或重新上傳任何資料。
- delete (
listofstr, 選填) — 要從儲存桶中刪除的檔案路徑。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
在儲存桶中新增、複製及/或刪除檔案。
這是一項非交易式操作。如果過程中發生錯誤,部分檔案可能已經上傳、複製或刪除,而其他檔案則未完成。
範例
>>> from huggingface_hub import batch_bucket_files
# Upload files
>>> batch_bucket_files(
... "username/my-bucket",
... add=[
... ("./model.safetensors", "models/model.safetensors"),
... (b'{{"key": "value"}}', "config.json"),
... ],
... )
# Copy xet files from another bucket or repo (server-side, no data transfer)
>>> batch_bucket_files(
... "username/my-bucket",
... copy=[
... ("bucket", "username/source-bucket", "<xethash_1>", "models/model.safetensors"),
... ("model", "username/my-model", "<xethash_2>", "models/config.safetensors"),
... ],
... )
# Delete files
>>> batch_bucket_files("username/my-bucket", delete=["old-model.bin"])
# Upload and delete in one batch
>>> batch_bucket_files(
... "username/my-bucket",
... add=[("./new.txt", "new.txt")],
... delete=["old.txt"],
... )bucket_info
< 原始碼 >( bucket_id: str token: bool | str | None = None ) → BucketInfo
參數
- bucket_id (
str) — 儲存桶 ID(例如"username/my-bucket")。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
儲存桶資訊。
引發
BucketNotFoundError 或 or
BucketNotFoundError— 若找不到儲存桶。這可能是因為它不存在,or— 或者因為它被設定為private(私人)且您沒有存取權限。
獲取 Hub 上特定儲存桶的資訊。
範例
>>> from huggingface_hub import bucket_info
>>> info = bucket_info(bucket_id="Wauplin/first-bucket")
>>> info.id
'Wauplin/first-bucket'
>>> info.private
False
>>> info.created_at
datetime.datetime(2026, 2, 6, 17, 37, 57, tzinfo=datetime.timezone.utc)
>>> info.size
551879671
>>> info.total_files
12cancel_access_request
< 原始碼 >( repo_id: str user: str repo_type: str | None = None token: bool | str | None = None )
參數
- repo_id (
str) — 要取消存取請求的儲存庫識別碼。 - 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— 若儲存庫未設為閘控 (gated),則回應 HTTP 400。HfHubHTTPError— 若您對儲存庫僅有唯讀權限,則回應 HTTP 403。如果您在該儲存庫所屬的組織中沒有write或admin角色,或如果您傳入的是read權杖,就會發生此情況。HfHubHTTPError— 若 Hub 上不存在該使用者,則回應 HTTP 404。HfHubHTTPError— 若找不到該使用者的存取請求,則回應 HTTP 404。HfHubHTTPError— 如果該使用者存取請求已在待處理清單中,則會出現 HTTP 404 錯誤。
取消使用者對特定門禁(gated)儲存庫的存取請求。
已取消的請求將會返回至待處理清單,且使用者將失去對該儲存庫的存取權限。
關於閘控儲存庫的更多資訊,請參閱 https://huggingface.co/docs/hub/models-gated。
cancel_job
< 原始碼 >( job_id: str namespace: str | None = None token: bool | str | None = None )
參數
- job_id (
str) — 作業 (Job) 的 ID。 - namespace (
str, optional) — 作業正在執行所在的命名空間。預設為目前使用者的命名空間。 - token
(Union[bool, str, None], optional) — 有效的使用者存取權杖。若未提供,將使用本機儲存的權杖,這是建議的驗證方式。設定為False以停用驗證。請參閱:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
取消在 Hugging Face 基礎設施上執行的運算作業 (Compute Job)。
change_discussion_status
< 原始碼 >( repo_id: str discussion_num: int new_status: Literal['open', 'closed'] token: bool | str | None = None comment: str | None = None repo_type: str | None = None ) → DiscussionStatusChange
參數
- repo_id (
str) — 命名空間(使用者或組織)加上以/分隔的儲存庫名稱。 - discussion_num (
int) — 討論或提取請求 (Pull Request) 的編號。必須為嚴格的正整數。 - new_status (
str) — 討論的新狀態,為"open"或"closed"。 - 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。
狀態變更事件
關閉或重新開啟討論或提取請求。
範例
>>> 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
< 原始碼 >( repo_id: str discussion_num: int comment: str token: bool | str | None = None repo_type: str | None = None ) → DiscussionComment
參數
- repo_id (
str) — 命名空間(使用者或組織)加上以/分隔的儲存庫名稱。 - discussion_num (
int) — 討論或提取請求的編號。必須為嚴格的正整數。 - comment (
str) — 要建立的註解內容。註解支援 Markdown 格式。 - repo_type (
str, optional) — 若上傳至資料集或空間,請設為"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(私人)且您沒有存取權限。
copy_files
< 原始碼 >( source: str destination: str token: str | bool | None = None )
參數
- source (
str) — 來源位置,格式為hf://URI。可以是儲存貯體 (bucket) 路徑(例如"hf://buckets/my-bucket/path/to/file")或是儲存庫路徑(例如"hf://username/my-model/weights.bin"、"hf://datasets/username/my-dataset/data/")。 - destination (
str) — 目的地位置,格式為指向儲存貯體的hf://URI(例如"hf://buckets/my-bucket/target/path")。 - token (
boolorstr, optional) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
引發
ValueError
ValueError— 如果目的地不是儲存貯體,或是來源/目的地 URI 無效。
在 Hub 上的位置之間複製檔案。
從儲存貯體或儲存庫(模型、資料集、空間)複製檔案至儲存貯體。支援複製個別檔案及整個資料夾。
目前僅支援將儲存貯體作為目的地。不支援複製到儲存庫。
複製資料夾時,若來源路徑結尾含有 /,則會使用 rsync 風格的語法:將資料夾的「內容」複製到目的地,而不會巢狀化來源資料夾本身。若無結尾的 /,則來源資料夾會被置於目的地內部(類似 cp -r)。
從儲存庫複製時,.gitattributes 檔案會自動排除,因為它們是 Git 特定的詮釋資料,在儲存貯體環境中沒有相關性。
範例
>>> from huggingface_hub import copy_files
# Copy a single file between buckets
>>> copy_files("hf://buckets/my-bucket/data.bin", "hf://buckets/other-bucket/data.bin")
# Copy a folder into another bucket (nests: backup/models/...)
>>> copy_files("hf://buckets/my-bucket/models", "hf://buckets/other-bucket/backup/")
# Copy folder contents (trailing /): files go directly into backup/
>>> copy_files("hf://buckets/my-bucket/models/", "hf://buckets/other-bucket/backup/")
# Copy a file from a model repo to a bucket
>>> copy_files("hf://username/my-model/model.safetensors", "hf://buckets/my-bucket/")
# Copy an entire dataset to a bucket
>>> copy_files("hf://datasets/username/my-dataset/", "hf://buckets/my-bucket/datasets/")create_branch
< 原始碼 >( repo_id: str branch: str revision: str | None = None token: bool | str | None = None repo_type: str | None = 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) — 若在資料集或空間上建立分支,請設為"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_bucket
< 原始碼 >( bucket_id: str private: bool | None = None resource_group_id: str | None = None region: REPO_REGIONS | None = None exist_ok: bool = False token: bool | str | None = None ) → BucketUrl
參數
- bucket_id (
str) — 命名空間(使用者或組織)加上以/分隔的儲存貯體名稱。若未提供命名空間,儲存貯體將建立在目前使用者的命名空間中。 - private (
bool, optional) — 是否將儲存貯體設為私人。若為None(預設值),則儲存貯體將為公開,除非該組織的預設設定為私人。 - resource_group_id (
str, optional) — 用於建立儲存貯體的資源群組。資源群組僅適用於 Enterprise Hub 組織,並允許定義組織中哪些成員可以存取該資源。資源群組的 ID 可在 Hub 上的資源頁面網址中找到(例如"66670e5163145ca562cb1988")。若要了解有關資源群組的更多資訊,請參閱 https://huggingface.co/docs/hub/en/security-resource-groups。 - region (
Literal["us", "eu"], optional) — 用於建立儲存貯體的雲端區域。可以是"us"或"eu"之一。如果未指定,儲存貯體將在預設區域建立。需要 Team 計畫或更高級別。 - exist_ok (
bool, optional, defaults toFalse) — 如果為True,則當儲存貯體已經存在時不會引發錯誤。 - token (
boolorstr, optional) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
指向新建立的儲存貯體的 URL,其中包含如 endpoint、namespace 和 bucket_id 等屬性。
在 Hub 上建立一個儲存貯體。
範例
>>> from huggingface_hub import create_bucket
>>> url = create_bucket(bucket_id="my-bucket")
>>> url.bucket_id
'user/my-bucket'
>>> url.url
'https://huggingface.co/buckets/user/my-bucket'
>>> url.uri.to_uri()
'hf://buckets/user/my-bucket'
>>> create_bucket(bucket_id="my-bucket", private=True, exist_ok=True)
BucketUrl(...)
>>> create_bucket(bucket_id="my-bucket", region="us")
BucketUrl(...)create_collection
< 原始碼 >( title: str namespace: str | None = None description: str | None = None private: bool = False exists_ok: bool = False token: bool | str | None = None )
參數
- title (
str) — 要建立的收藏集標題。範例:"Recent models"。 - namespace (
str, optional) — 要建立的收藏集命名空間(使用者名稱或組織名稱)。將預設為擁有者名稱。 - description (
str, optional) — 要建立的收藏集描述。 - private (
bool, optional) — 收藏集是否應為私人。預設為False(即公開收藏集)。 - exists_ok (
bool, optional) — 如果為True,則當收藏集已經存在時不會引發錯誤。 - token (
boolorstr, optional) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
在 Hub 上建立一個新收藏集。
回傳: Collection
create_commit
< 原始碼 >( repo_id: str operations: Iterable[CommitOperation] commit_message: str commit_description: str | None = None token: str | bool | None = None repo_type: str | None = None revision: str | None = None create_pr: bool | None = None num_threads: int = 5 parent_commit: str | None = None run_as_future: bool = False _hot_reload: bool | None = None ) → CommitInfo or Future
參數
- repo_id (
str) — 將建立提交的儲存庫,例如:"username/custom_transformers" - operations (
CommitOperation()的Iterable) — 要包含在 commit 中的操作迭代器,可以是:- CommitOperationAdd:用於上傳檔案
- CommitOperationDelete:用於刪除檔案
- CommitOperationCopy:用於複製檔案
操作物件將會被變更以包含與上傳相關的資訊。請勿對多個 commit 重複使用相同的物件。
- commit_message (
str) — 將建立的 commit 摘要(第一行)。 - commit_description (
str, 選填) — 將建立的 commit 描述。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設使用本機儲存的權杖,這是推薦的身份驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。 - repo_type (
str, 選填) — 若要上傳至資料集或 Space,請設為"dataset"或"space";若要上傳至模型,則設為None或"model"。預設值為None。 - revision (
str, 選填) — 要從哪個 git 版本進行 commit。預設為"main"分支的 HEAD。 - create_pr (
boolean, 選填) — 是否要用此 commit 建立一個 Pull Request。預設值為False。若未設定revision,則 PR 將會針對"main"分支開啟。若已設定revision且為一個分支,則 PR 將會針對該分支開啟。若已設定revision但並非分支名稱(例如:commit oid),伺服器將會回傳RevisionNotFoundError。 - num_threads (
int, 選填) — 用於上傳檔案的並行執行緒數量。預設為 5。將其設為 2 意味著最多同時上傳 2 個檔案。 - parent_commit (
str, 選填) — 父 commit 的 OID / SHA,以十六進位字串表示。也支援簡寫(前 7 個字元)。如果指定且create_pr為False,則若revision未指向parent_commit,commit 將會失敗。如果指定且create_pr為True,則將會從parent_commit建立 Pull Request。指定parent_commit可確保在提交變更前儲存庫未被變更,這在儲存庫同時被更新/提交時特別有用。 - run_as_future (
bool, 選填) — 是否在背景執行此方法。背景任務會依序執行,不會阻塞主執行緒。傳入run_as_future=True將回傳一個 Future 物件。預設值為False。
返回
CommitInfo 或 Future
包含新建立 commit 相關資訊(commit 雜湊、commit url、pr url、commit 訊息等)的 CommitInfo 實例。若傳入 run_as_future=True,則回傳一個 Future 物件,執行時將包含結果。
引發
ValueError 或 RepositoryNotFoundError
ValueError— 若 commit 訊息為空。ValueError— 若父 commit 不是有效的 commit OID。ValueError— 若提交了含有無效元資料區段的 README.md 檔案。在這種情況下,commit 會提前失敗,不會嘗試上傳任何檔案。ValueError— 若create_pr為True且 revision 既不是None也不是"main"。- RepositoryNotFoundError — 如果找不到儲存庫(錯誤 404):repo_id/repo_type 錯誤、儲存庫為私人且未經驗證,或是儲存庫不存在。
在指定儲存庫中建立一個 commit,視需要刪除與上傳檔案。
傳入的
CommitOperation列表在 commit 過程中將會被變更。請勿對多個 commit 重複使用相同的物件。
create_commit預設儲存庫已存在於 Hub 上。若收到 404 用戶端錯誤,請確保您已進行身份驗證、權杖具有所需的權限,且repo_id與repo_type設定正確。若儲存庫不存在,請先使用 create_repo() 建立它。
create_commit限制為 25k 個 LFS 檔案,一般檔案的有效負載限制為 1GB。
create_discussion
< 原始碼 >( repo_id: str title: str token: bool | str | None = None description: str | None = None repo_type: str | None = None pull_request: bool = False )
參數
- repo_id (
str) — 命名空間(使用者或組織)加上儲存庫名稱,中間以/分隔。 - title (
str) — 討論的標題。長度可達 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" - pull_request (
bool, 選填) — 是否要建立 Pull Request 或討論。若為True,則建立 Pull Request。若為False,則建立討論。預設值為False。 - repo_type (
str, 選填) — 若要上傳至資料集或 Space,請設為"dataset"或"space";若要上傳至模型,則設為None或"model"。預設值為None。
建立討論或 Pull Request。
透過程式建立的 Pull Request 將會處於 "draft"(草稿)狀態。
若要同時建立附帶變更的 Pull Request,也可使用 HfApi.create_commit()。
可能會引發下列錯誤
HTTPError如果 HuggingFace API 回傳錯誤ValueError如果某些參數值無效- RepositoryNotFoundError 如果找不到要下載的儲存庫。這可能是因為它不存在,或者它被設為
private(私人)且您沒有存取權限。
create_inference_endpoint
< 原始碼 >( name: str repository: str framework: str accelerator: str instance_size: str instance_type: str region: str vendor: str account_id: str | None = None min_replica: int = 1 max_replica: int = 1 scaling_metric: InferenceEndpointScalingMetric | None = None scaling_threshold: float | None = None scale_to_zero_timeout: int | None = None revision: str | None = None task: str | None = None custom_image: dict | None = None env: dict[str, str] | None = None secrets: dict[str, str] | None = None type: InferenceEndpointType = <InferenceEndpointType.PROTECTED: 'protected'> domain: str | None = None path: str | None = None cache_http_responses: bool | None = None tags: list[str] | None = None namespace: str | None = None token: bool | str | None = None ) → InferenceEndpoint
參數
- name (
str) — 新 Inference Endpoint 的唯一名稱。 - repository (
str) — 與 Inference Endpoint 關聯的模型儲存庫名稱(例如"gpt2")。 - framework (
str) — 模型使用的機器學習框架(例如"custom")。 - accelerator (
str) — 用於推理的硬體加速器(例如"cpu")。 - instance_size (
str) — 用於託管模型的執行個體大小或類型(例如"x4")。 - instance_type (
str) — 部署 Inference Endpoint 的雲端執行個體類型(例如"intel-icl")。 - region (
str) — 建立 Inference Endpoint 的雲端區域(例如"us-east-1")。 - vendor (
str) — 託管 Inference Endpoint 的雲端提供商或廠商(例如"aws")。 - account_id (
str, 選填) — 用於將 VPC 連結至私有 Inference Endpoint 的帳號 ID(若適用)。 - min_replica (
int, 選填) — Inference Endpoint 維持運行的最少副本(執行個體)數量。若要啟用自動擴展至零,請將此值設為 0 並相應調整scale_to_zero_timeout。預設值為 1。 - max_replica (
int, 選填) — Inference Endpoint 最多可擴展的副本(執行個體)數量。預設值為 1。 - scaling_metric (
str或InferenceEndpointScalingMetric, 選填) — 用於擴展的指標參考。提供時,可為“pendingRequests”或“hardwareUsage”。預設為 None(意即:讓 HF Endpoints 服務指定指標)。 - scaling_threshold (
float, 選填) — 用於觸發擴展的指標閾值。若未提供擴展指標,此值會被忽略。預設為 None(意即:讓 HF Endpoints 服務指定閾值)。 - scale_to_zero_timeout (
int, 選填) — 不活動端點擴展至零之前的持續時間(分鐘),若設為 None 且min_replica不為 0,則不會擴展至零。預設為 None。 - revision (
str, 選填) — 在 Inference Endpoint 上部署的特定模型版本(例如"6c0e6080953db56375760c0471a8c5f2929baf11")。 - task (
str, 選填) — 模型要執行的任務(例如"text-classification")。 - custom_image (
dict, 選填) — 用於 Inference Endpoint 的自訂 Docker 映像檔。若您想部署執行在text-generation-inference(TGI) 框架上的 Inference Endpoint,這非常有用(請參閱範例)。 - env (
dict[str, str], 選填) — 要注入容器環境中的非機密環境變數。 - secrets (
dict[str, str], 選填) — 要注入容器環境中的機密值。 - type ([`InferenceEndpointType], 選填) -- Inference Endpoint 的類型,可以是
"protected"(預設)、"public"或"private"。 - domain (
str, 選填) — Inference Endpoint 部署的自訂網域。若已設定,推理端點將可在該網域存取(例如"my-new-domain.cool-website.woof")。 - path (
str, 選填) — 部署模型的自訂路徑,應以/開頭(例如"/models/google-bert/bert-base-uncased")。 - cache_http_responses (
bool, 選填) — 是否快取來自 Inference Endpoint 的 HTTP 回應。預設值為False。 - tags (
list[str], 選填) — 與 Inference Endpoint 關聯的標籤列表。 - namespace (
str, 選填) — 建立 Inference Endpoint 的命名空間。預設為當前使用者的命名空間。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設使用本機儲存的權杖,這是推薦的身份驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。
有關更新後的 Inference Endpoint 的資訊。
建立一個新的 Inference Endpoint。
範例
>>> 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
< 原始碼 >( repo_id: str name: str | None = None accelerator: Literal['cpu', 'gpu', 'neuron'] | str | None = None token: bool | str | None = None namespace: str | None = None ) → InferenceEndpoint
參數
- repo_id (
str) — 目錄中要部署為 Inference Endpoint 的模型 ID。 - name (
str, 選填) — 新 Inference Endpoint 的唯一名稱。若未提供,將會自動生成一個隨機名稱。 - accelerator (
str, 選填) — 用於推論的硬體加速器。可選值包括"cpu"、"gpu"和"neuron"。若未提供,伺服器將使用該模型適用的預設值。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地端儲存的權杖,這是推薦的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。 - namespace (
str, 選填) — 建立 Inference Endpoint 的命名空間。預設為當前使用者的命名空間。
關於新 Inference Endpoint 的資訊。
從 Hugging Face Inference Catalog 中的模型建立新的 Inference Endpoint。
Inference Catalog 的目標是提供一份經過篩選的模型清單,這些模型皆針對推論進行過優化,並已測試其預設配置。請參閱 https://endpoints.huggingface.co/catalog 查看目錄中可用的模型清單。
create_inference_endpoint_from_catalog目前為實驗性質,其 API 未來可能會有所變動。若您有任何建議或需求,歡迎提供回饋。
create_pull_request
< 原始碼 >( repo_id: str title: str token: bool | str | None = None description: str | None = None repo_type: str | None = None )
參數
- repo_id (
str) — 以/分隔的命名空間(使用者或組織)與儲存庫名稱。 - title (
str) — 討論的標題。長度上限為 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"(草稿)狀態。
若要同時建立包含變更的 Pull Request,也可使用 HfApi.create_commit();
這是 HfApi.create_discussion() 的封裝函式。
可能會引發下列錯誤
HTTPError如果 HuggingFace API 回傳錯誤ValueError如果某些參數值無效- RepositoryNotFoundError 如果找不到要下載的儲存庫。這可能是因為它不存在,或者它被設為
private(私人)且您沒有存取權限。
create_repo
< 原始碼 >( repo_id: str token: str | bool | None = None private: bool | None = None visibility: RepoVisibility_T | None = None repo_type: str | None = None exist_ok: bool = False resource_group_id: str | None = None region: REPO_REGIONS | None = None space_sdk: str | None = None space_hardware: SpaceHardware | None = None space_storage: SpaceStorage | None = None space_sleep_time: int | None = None space_secrets: list[dict[str, str]] | None = None space_variables: list[dict[str, str]] | None = None space_volumes: list[Volume] | None = None ) → RepoUrl
參數
- repo_id (
str) — 以/分隔的命名空間(使用者或組織)與儲存庫名稱。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地端儲存的權杖,這是推薦的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - private (
bool, 選填) — 是否將儲存庫設為私有。若為None(預設值),除非組織的預設值為私有,否則儲存庫將設為公開。若儲存庫已存在,此值將被忽略。不可與visibility同時傳入。 - visibility (
Literal["public", "private", "protected"], 選填) — 儲存庫的可見度。可設為"public"、"private",或是用於 Spaces 的"protected"。若為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。 - region (
Literal["us", "eu"], 選填) — 建立儲存庫的雲端區域。可設為"us"或"eu"。若未指定,儲存庫將在預設區域中建立。需要 Team 方案或以上等級。 - space_sdk (
str, 選填) — 若 repo_type 為 “space”,請選擇使用的 SDK。可為 “streamlit”、“gradio”、“docker” 或 “static”。 - space_hardware (
SpaceHardware或str, 選填) — 若 repo_type 為 “space”,請選擇使用的硬體。完整清單請參閱 SpaceHardware。 - space_storage (
SpaceStorage或str, 選填) — <已棄用,請使用set_space_volumes代替> 選擇持久化儲存層級。範例:"small"。完整清單請參閱 SpaceStorage。 - space_sleep_time (
int, 選填) — 空間進入休眠前等待的不活動秒數。若您不希望空間休眠(升級版硬體的預設行為),請設為-1。若為免費硬體,則無法設定休眠時間(固定為 48 小時不活動後進入休眠)。詳細資訊請參閱 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。 - space_secrets (
list[dict[str, str]], 選填) — 要在您的空間中設定的秘密金鑰清單。每個項目格式為{"key": ..., "value": ..., "description": ...},其中 description 為選填。詳細資訊請參閱 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。 - space_variables (
list[dict[str, str]], 選填) — 要在您的空間中設定的公開環境變數清單。每個項目格式為{"key": ..., "value": ..., "description": ...},其中 description 為選填。詳細資訊請參閱 https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables。 - space_volumes (
list[Volume], 選填) — 在空間建立時掛載的 Volume 物件清單。每個 Volume 包含type("bucket"、"model"、"dataset"或"space")、source(儲存庫或 bucket ID)、mount_path(容器內的掛載路徑),以及選填的revision、read_only和path欄位。僅在 repo_type 為 “space” 時適用。
返回
新建立的儲存庫 URL。其值為 str 的子類別,包含如 endpoint、repo_type 和 repo_id 等屬性。
在 HuggingFace Hub 上建立一個空儲存庫。
create_scheduled_job
< 原始碼 >( image: str command: list[str] schedule: str suspend: bool | None = None concurrency: bool | None = None env: dict[str, Any] | None = None secrets: dict[str, Any] | None = None flavor: SpaceHardware | None = None timeout: int | float | str | None = None labels: dict[str, str] | None = None volumes: list[Volume] | None = None namespace: str | None = None token: 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,則排程的工作將會被暫停。預設為 False。 - concurrency (
bool, 選填) — 若為 True,此工作可同時執行多個實例。預設為 False。 - env (
dict[str, Any], 選填) — 定義工作的環境變數。 - secrets (
dict[str, Any], 選填) — 定義工作的秘密環境變數。 - flavor (
str, 選填) — 硬體類型,如同 Hugging Face Spaces。請參閱 SpaceHardware 查看可用的值。預設為"cpu-basic"。 - timeout (
Union[int, float, str], 選填) — 工作的最大持續時間:可為整數/浮點數(單位為 s 秒,預設值)、m(分鐘)、h(小時)或 d(天)。範例:300或"5m"表示 5 分鐘。 - labels (
dict[str, str], 選填) — 附加至工作的標籤(鍵值對)。 - volumes (
list[Volume], 選填) — 作為 Volume 掛載到工作容器中的 Hugging Face Buckets 或儲存庫。每個 Volume 包含type("bucket"、"model"、"dataset"或"space")、source(例如"username/my-bucket")以及mount_path(例如"/data")。 - namespace (
str, 選填) — 建立工作的命名空間。預設為當前使用者的命名空間。 - token
(Union[bool, str, None], 選填) — 有效的使用者存取權杖。若未提供,將使用本地端儲存的權杖,這是推薦的驗證方法。若要停用驗證,請設為False。請參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
在 Hugging Face 基礎設施上建立定時計算工作(Jobs)。
範例
建立您的第一個定時工作
>>> 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 工作
>>> 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
< 原始碼 >( script: str script_args: list[str] | None = None schedule: str suspend: bool | None = None concurrency: bool | None = None dependencies: list[str] | None = None python: str | None = None image: str | None = None env: dict[str, Any] | None = None secrets: dict[str, Any] | None = None flavor: SpaceHardware | None = None timeout: int | float | str | None = None labels: dict[str, str] | None = None volumes: list[Volume] | None = None namespace: str | None = None token: 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,則排程的工作將會被暫停。預設為 False。 - concurrency (
bool, 選填) — 若為 True,此工作可同時執行多個實例。預設為 False。 - dependencies (
list[str], 選填) — 執行 UV 指令稿所需的相依套件。 - python (
str, 選填) — 使用特定的 Python 版本。預設為 3.12。 - image (
str, 選填, 預設為 “ghcr.io/astral-sh/uv —python3.12-bookworm”):使用安裝了uv的自訂 Docker 映像檔。 - env (
dict[str, Any], 選填) — 定義作業 (Job) 的環境變數。 - secrets (
dict[str, Any], 選填) — 定義作業的機密環境變數。 - flavor (
str, 選填) — 硬體的規格(Flavor),與 Hugging Face Spaces 相同。請參閱 SpaceHardware 以取得可用值。預設值為"cpu-basic"。 - timeout (
Union[int, float, str], 選填) — 作業的最大持續時間:可使用整數/浮點數(單位為秒,預設值)、或字串搭配 s(秒)、m(分)、h(小時)或 d(天)。範例:300或"5m"表示 5 分鐘。 - labels (
dict[str, str], 選填) — 要附加至作業的標籤(鍵值對)。 - volumes (
list[Volume], 選填) — 掛載至作業容器中的 Hugging Face Buckets 或 Repos。每個 volume 皆為 Volume 物件,包含type("bucket","model","dataset"或"space")、source(例如"username/my-bucket") 以及mount_path(例如"/data")。 - namespace (
str, 選填) — 建立作業的命名空間 (namespace)。預設為當前使用者的命名空間。 - token
(Union[bool, str, None], 選填) — 有效的使用者存取權杖 (access token)。若未提供,將使用本機儲存的權杖,這是建議的驗證方法。設定為False可停用驗證。參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
在 Hugging Face 基礎架構上執行 UV 指令碼作業。
範例
排程來自 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
< 來源 >( repo_id: str tag: str tag_message: str | None = None revision: str | None = None token: bool | str | None = None repo_type: str | None = None exist_ok: bool = False )
參數
- repo_id (
str) — 將被建立標籤的儲存庫。範例:"user/my-cool-model"。 - tag (
str) — 要建立的標籤名稱。 - tag_message (
str, 選填) — 要建立的標籤描述。 - revision (
str, 選填) — 要標記的 git 版本 (revision)。可以是分支名稱或提交的 OID/SHA(十六進位字串)。也支援簡寫(前 7 個字元)。預設為"main"分支的最新內容。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - repo_type (
str, 選填) — 若要標記資料集 (dataset) 或空間 (space),請設定為"dataset"或"space";若標記模型 (model),請設為None或"model"。預設為None。 - exist_ok (
bool, 選填, 預設值為False) — 若設為True,當標籤已存在時不會引發錯誤。
- RepositoryNotFoundError — 如果找不到儲存庫(錯誤 404):repo_id/repo_type 錯誤、儲存庫為私人且未經驗證,或是儲存庫不存在。
- RevisionNotFoundError — 如果在儲存庫中找不到該版本(錯誤 404)。
- HfHubHTTPError — 如果該分支已存在於儲存庫中(錯誤 409)且
exist_ok設為False。
標記 Hub 上儲存庫的特定提交。
create_webhook
< 來源 >( url: str | None = None job_id: str | None = None watched: list[dict | WebhookWatchedItem] domains: list[constants.WEBHOOK_DOMAIN_T] | None = None secret: str | None = None token: bool | str | None = None ) → WebhookInfo
參數
- url (
str) — 發送酬載 (payload) 的目標 URL。 - job_id (
str) — 觸發 webhook 時的來源作業 ID,酬載將位於環境變數 WEBHOOK_PAYLOAD 中。額外的環境變數包括:WEBHOOK_REPO_ID、WEBHOOK_REPO_TYPE 和 WEBHOOK_SECRET。 - watched (
list[WebhookWatchedItem]) — Webhook 要監控的 WebhookWatchedItem 列表。可以是使用者、組織、模型、資料集或空間。監控項目也可以用純字典格式提供。 - domains (
list[Literal["repo", "discussion"]], 選填) — 要監控的領域列表。可以是 “repo”、“discussion” 或兩者皆是。 - secret (
str, 選填) — 用於簽署酬載的機密 (secret)。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
關於新建立的 webhook 的資訊。
建立一個新的 webhook。
Webhook 可以將酬載發送至 URL,或者觸發在 Hugging Face 基礎架構上執行的作業。呼叫此函式時應提供 url 或 job_id,但不可同時提供兩者。
範例
建立一個將酬載發送至 URL 的 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,
)執行作業並建立一個觸發此作業的 webhook
>>> from huggingface_hub import create_webhook, run_job
>>> job = run_job(
... image="ubuntu",
... command=["bash", "-c", r"echo An event occurred 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 occurred 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
< 來源 >( repo_id: str revision: str | None = None timeout: float | None = None files_metadata: bool = False expand: list[ExpandDatasetProperty_T] | None = None token: bool | str | None = None ) → hf_api.DatasetInfo
參數
- repo_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,中間以/分隔。 - revision (
str, 選填) — 要取得資訊的資料集儲存庫版本。 - timeout (
float, 選填) — 是否為 Hub 的請求設定逾時。 - files_metadata (
bool, 選填) — 是否取得儲存庫中檔案的詮釋資料(大小、LFS 詮釋資料等)。預設為False。 - expand (
list[ExpandDatasetProperty_T], 選填) — 要在回應中傳回的屬性列表。若使用此參數,將僅傳回列表中的屬性。如果傳遞了files_metadata,則無法使用此參數。可用值包括:"author","cardData","citation","createdAt","disabled","description","downloads","downloadsAllTime","gated","lastModified","likes","mainSize","paperswithcode_id","private","siblings","sha","tags","trendingScore","usedStorage"和"resourceGroup"。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
資料集儲存庫資訊。
取得 huggingface.co 上特定資料集的資訊。
若您傳入有效的權杖,可以存取私有資料集。
可能會引發下列錯誤
- RepositoryNotFoundError 如果找不到要下載的儲存庫。這可能是因為它不存在,或者它被設為
private(私人)且您沒有存取權限。- RevisionNotFoundError 如果找不到要下載的版本。
delete_branch
< 來源 >( repo_id: str branch: str token: bool | str | None = None repo_type: str | None = None )
參數
- repo_id (
str) — 將被刪除分支的儲存庫。範例:"user/my-cool-model"。 - branch (
str) — 要刪除的分支名稱。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - repo_type (
str, 選填) — 若要在資料集或空間上建立分支,請設定為"dataset"或"space";若標記模型,請設為None或"model"。預設為None。
- RepositoryNotFoundError — 如果找不到儲存庫(錯誤 404):repo_id/repo_type 錯誤、儲存庫為私人且未經驗證,或是儲存庫不存在。
- HfHubHTTPError — 若嘗試刪除保護的分支。例如:
main無法刪除。 - HfHubHTTPError — 若嘗試刪除不存在的分支。
從 Hub 的儲存庫中刪除分支。
delete_bucket
< 來源 >( bucket_id: str missing_ok: bool = False token: bool | str | None = None )
參數
- bucket_id (
str) — Bucket 的 ID(例如"username/my-bucket")。 - missing_ok (
bool, 選填, 預設值為False) — 若設為True,當 bucket 不存在時不會引發錯誤。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
引發
BucketNotFoundError
BucketNotFoundError— 如果找不到 bucket 且missing_ok設定為False(預設)。
從 Hub 刪除一個 bucket。
delete_collection
< 來源 >( collection_slug: str missing_ok: bool = False token: bool | str | None = None )
參數
- collection_slug (
str) — 要刪除的集合 (collection) 的 slug。範例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。 - missing_ok (
bool, 選填) — 若設為True,當集合不存在時不會引發錯誤。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 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
< 來源 >( collection_slug: str item_object_id: str missing_ok: bool = False token: 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, 選填) — 若設為True,當項目不存在時不會引發錯誤。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 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
< 來源 >( path_in_repo: str repo_id: str token: str | bool | None = None repo_type: str | None = None revision: str | None = None commit_message: str | None = None commit_description: str | None = None create_pr: bool | None = None parent_commit: str | None = None )
參數
- 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, optional) — 若檔案位於資料集或 Space 中,請設為"dataset"或"space";若位於模型中則設為None或"model"。預設為None。 - revision (
str, optional) — 要從中提交的 Git 版本。預設為"main"分支的最新節點(head)。 - commit_message (
str, optional) — 所生成提交的摘要/標題/第一行。預設為f"Delete {path_in_repo} with huggingface_hub"。 - commit_description (
str, optional) — 所生成提交的說明。 - create_pr (
boolean, optional) — 是否為該提交建立提取請求(Pull Request)。預設為False。若未設定revision,則 PR 將針對"main"分支開啟。若已設定revision且該值為分支名稱,則 PR 將針對該分支開啟。若已設定revision但非分支名稱(例如:提交 OID),伺服器將回傳RevisionNotFoundError。 - parent_commit (
str, optional) — 父提交的 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: bool | str | None = None repo_type: str | None = None revision: str | None = None commit_message: str | None = None commit_description: str | None = None create_pr: bool | None = None parent_commit: str | None = None )
參數
- repo_id (
str) — 將從中刪除資料夾的儲存庫,例如:"username/custom_transformers" - delete_patterns (
list[str]) — 要刪除的檔案或資料夾清單。每個字串可以是檔案路徑、資料夾路徑或萬用字元(wildcard)模式。模式為標準萬用字元(globbing patterns),記錄於此處。模式比對基於fnmatch。請注意,與傳統的 Unix shell globbing 不同,fnmatch的*可以跨越路徑邊界。例如["file.txt", "folder/", "data/*.parquet"] - token (
boolorstr, optional) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的驗證方式(參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - repo_type (
str, optional) — 要刪除檔案的儲存庫類型。可為"model"、"dataset"或"space"。預設為"model"。 - revision (
str, optional) — 要從中提交的 Git 版本。預設為"main"分支的最新節點(head)。 - commit_message (
str, optional) — 所生成提交的摘要(第一行)。預設為f"Delete files using huggingface_hub"。 - commit_description (
str, optional) — 所生成提交的說明。 - create_pr (
boolean, optional) — 是否為該提交建立提取請求(Pull Request)。預設為False。若未設定revision,則 PR 將針對"main"分支開啟。若已設定revision且該值為分支名稱,則 PR 將針對該分支開啟。若已設定revision但非分支名稱(例如:提交 OID),伺服器將回傳RevisionNotFoundError。 - parent_commit (
str, optional) — 父提交的 OID / SHA,以十六進位字串表示。亦支援簡寫(前 7 個字元)。若指定且create_pr為False,且revision未指向parent_commit,則提交將失敗。若指定且create_pr為True,則提取請求將從parent_commit建立。指定parent_commit可確保在提交變更前儲存庫未發生變更,這在儲存庫有並行更新/提交時特別有用。
從 Hugging Face Hub 的儲存庫中刪除檔案。
若提供資料夾路徑,則整個資料夾及其包含的所有檔案都將被刪除。
delete_folder
< source >( path_in_repo: str repo_id: str token: bool | str | None = None repo_type: str | None = None revision: str | None = None commit_message: str | None = None commit_description: str | None = None create_pr: bool | None = None parent_commit: str | None = None )
參數
- path_in_repo (
str) — 儲存庫中的相對資料夾路徑,例如:"checkpoints/1fec34a"。 - repo_id (
str) — 將從中刪除資料夾的儲存庫,例如:"username/custom_transformers" - token (
boolorstr, optional) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的驗證方式(參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - repo_type (
str, optional) — 若資料夾位於資料集或 Space 中,請設為"dataset"或"space";若位於模型中則設為None或"model"。預設為None。 - revision (
str, optional) — 要從中提交的 Git 版本。預設為"main"分支的最新節點(head)。 - commit_message (
str, optional) — 所生成提交的摘要/標題/第一行。預設為f"Delete folder {path_in_repo} with huggingface_hub"。 - commit_description (
str, optional) — 所生成提交的說明。 - create_pr (
boolean, optional) — 是否為該提交建立提取請求(Pull Request)。預設為False。若未設定revision,則 PR 將針對"main"分支開啟。若已設定revision且該值為分支名稱,則 PR 將針對該分支開啟。若已設定revision但非分支名稱(例如:提交 OID),伺服器將回傳RevisionNotFoundError。 - parent_commit (
str, optional) — 父提交的 OID / SHA,以十六進位字串表示。亦支援簡寫(前 7 個字元)。若指定且create_pr為False,且revision未指向parent_commit,則提交將失敗。若指定且create_pr為True,則提取請求將從parent_commit建立。指定parent_commit可確保在提交變更前儲存庫未發生變更,這在儲存庫有並行更新/提交時特別有用。
刪除給定儲存庫中的資料夾。
為 create_commit() 方法的簡易封裝。
delete_inference_endpoint
< source >( name: str namespace: str | None = None token: bool | str | None = None )
參數
- name (
str) — 要刪除的 Inference Endpoint 名稱。 - namespace (
str, optional) — Inference Endpoint 所在的命名空間。預設為當前使用者。 - token (
boolorstr, optional) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的驗證方式(參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
刪除 Inference Endpoint。
此操作不可逆。若您不想為 Inference Endpoint 付費,建議使用 pause_inference_endpoint() 將其暫停,或使用 scale_to_zero_inference_endpoint() 將其縮減為零。
為方便起見,您也可以使用 InferenceEndpoint.delete() 來刪除 Inference Endpoint。
delete_repo
< source >( repo_id: str token: str | bool | None = None repo_type: str | None = 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) — 若上傳至資料集或 Space,請設為"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: str | None = None token: bool | str | None = None )
參數
- scheduled_job_id (
str) — 排程任務(Scheduled Job)的 ID。 - namespace (
str, optional) — 排程任務所在的命名空間。預設為當前使用者的命名空間。 - token
(Union[bool, str, None], optional) — 有效的使用者存取權杖。若未提供,將使用本地儲存的權杖,這是建議的驗證方式。若要停用驗證,請設為False。請參閱:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
刪除 Hugging Face 基礎設施上的排程計算任務(Scheduled Compute Job)。
delete_space_secret
< source >( repo_id: str key: str token: bool | str | None = None )
參數
- repo_id (
str) — 要更新的儲存庫 ID。例如:"bigcode/in-the-stack"。 - key (
str) — 秘密金鑰(Secret key)。例如:"GITHUB_API_KEY"。 - token (
boolorstr, optional) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的驗證方式(參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
從 Space 中刪除秘密(Secret)。
祕密允許將祕密金鑰或權杖設定至 Space 中,而無需將其寫死在程式碼中。欲知詳情,請參閱 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。
delete_space_storage
< source >( repo_id: str token: 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 沒有永久儲存空間(persistent storage)。
刪除 Space 的永久儲存空間。
delete_space_storage已棄用,將於 2.0 版本中移除。請改用 delete_space_volumes()。
delete_space_variable
< source >( repo_id: str key: str token: bool | str | None = None )
參數
- repo_id (
str) — 要更新的儲存庫 ID。例如:"bigcode/in-the-stack"。 - key (
str) — 變數鍵(Variable key)。例如:"MODEL_REPO_ID" - 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
delete_space_volumes
< 原始碼 >( repo_id: str token: bool | str | None = None )
參數
- repo_id (
str) — 要更新的 Space 的 ID。範例:"username/my-space"。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的身份驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。
引發
BadRequestError
BadRequestError— 若該 Space 沒有掛載儲存卷。
移除 Space 中的所有儲存卷。
delete_tag
< 原始碼 >( repo_id: str tag: str token: bool | str | None = None repo_type: str | None = None )
參數
- repo_id (
str) — 要刪除標籤的儲存庫。範例:"user/my-cool-model"。 - tag (
str) — 要刪除的標籤名稱。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的身份驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。 - repo_type (
str, 選填) — 如果要標記資料集或 Space,請設為"dataset"或"space";如果標記模型,請設為None或"model"。預設值為None。
- RepositoryNotFoundError — 如果找不到儲存庫(錯誤 404):repo_id/repo_type 錯誤、儲存庫為私人且未經驗證,或是儲存庫不存在。
- RevisionNotFoundError — 若找不到該標籤。
從 Hub 上的儲存庫中刪除標籤。
delete_webhook
< 原始碼 >( webhook_id: str token: bool | str | None = None ) → None
參數
- webhook_id (
str) — 要刪除的 webhook 唯一識別碼。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的身份驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。
返回
None
刪除 webhook。
disable_space_dev_mode
< 原始碼 >( repo_id: str token: bool | str | None = None ) → SpaceRuntime
參數
- repo_id (
str) — 要停用開發模式的 Space ID。範例:"Salesforce/BLIP2"。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的身份驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。
返回
關於您 Space 的執行階段資訊。
- RepositoryNotFoundError — 若找不到您的 Space(錯誤 404)。很可能是 repo_id 錯誤,或是您的 Space 為私人狀態但您未經驗證。
- HfHubHTTPError — 403 Forbidden:只有 Space 的擁有者才能設定開發模式。若您想管理非自己擁有的 Space,請透過開啟討論(Discussion)詢問擁有者,或是複製該 Space。
- BadRequestError — 若您的 Space 是靜態 Space。靜態 Space 始終在執行中且不計費。若您想隱藏靜態 Space,可以將其設為私人。
停用 Space 上的開發模式。
Spaces 開發模式(Dev Mode)旨在簡化應用程式的除錯流程,並透過允許您在不停止 Space 容器本身的情況下重新啟動應用程式,來加快在 Spaces 上的疊代速度。此功能為 PRO 或 Team & Enterprise 方案的一部分。詳細資訊請參閱 https://huggingface.co/docs/hub/spaces-dev-mode。
disable_webhook
< 原始碼 >( webhook_id: str token: bool | str | None = None ) → WebhookInfo
參數
- webhook_id (
str) — 要停用的 webhook 唯一識別碼。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的身份驗證方式(請參閱 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,
)download_bucket_files
< 原始碼 >( bucket_id: str files: list[tuple[str | BucketFile, str | Path]] raise_on_missing_files: bool = False token: str | bool | None = None )
參數
- bucket_id (
str) — Bucket 的 ID(例如"username/my-bucket")。 - files (
list[tuple[Union[str, BucketFile], Union[str, Path]]]) — 要下載的檔案清單,為元組(來源,目的地)列表。詳細格式請參閱上述說明。 - raise_on_missing_files (
bool, 選填) — 若為True,當請求的檔案在 bucket 中不存在時,會拋出EntryNotFoundError。若為False(預設),缺失的檔案將會被跳過並顯示警告。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的身份驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。
從 bucket 下載檔案。
檔案輸入為一組 (遠端檔案, 本地檔案) 的元組列表,其中 遠端檔案 可以是 bucket 中的檔案路徑或 BucketFile 物件,而 本地檔案 是本地檔案系統上的目的地路徑。當傳入 BucketFile 物件(透過 list_bucket_tree() 取得)時,該方法將跳過中繼資料擷取步驟並直接下載檔案。
範例
>>> from huggingface_hub import download_bucket_files
>>> download_bucket_files(
... bucket_id="username/my-bucket",
... files=[
... ("models/model.safetensors", "./local/model.safetensors"),
... ("config.json", "./local/config.json"),
... ],
... )>>> from huggingface_hub import download_bucket_files
>>> parquet_files = [file for file in list_bucket_tree(bucket_id="username/my-bucket") if file.path.endswith(".parquet")]
>>> download_bucket_files(
... bucket_id="username/my-bucket",
... files=[(file, f"./local/{file.path}") for file in parquet_files],
... )duplicate_repo
< 原始碼 >( from_id: str to_id: str | None = None repo_type: str | None = None private: bool | None = None visibility: RepoVisibility_T | None = None token: bool | str | None = None exist_ok: bool = False space_hardware: SpaceHardware | None = None space_storage: SpaceStorage | None = None space_sleep_time: int | None = None space_secrets: list[dict[str, str]] | None = None space_variables: list[dict[str, str]] | None = None space_volumes: list[Volume] | None = None ) → RepoUrl
參數
- from_id (
str) — 要複製的儲存庫 ID。範例:"openai/gdpval"。 - to_id (
str, 選填) — 新儲存庫的 ID。範例:"myorg/my-gdpval"。若未提供,新儲存庫將與原始儲存庫名稱相同,但建立在您的帳戶下。 - repo_type (
str, 選填) — 如果要複製資料集或 Space,請設為"dataset"或"space";如果要複製模型,請設為None或"model"。預設值為None。 - private (
bool, 選填) — 新儲存庫是否應為私人。預設與原始儲存庫的隱私設定相同。不可與visibility同時傳入。 - visibility (
Literal["public", "private", "protected"], 選填) — 新儲存庫的可見性。可以是"public"、"private",或針對 Space 的"protected"。預設與原始儲存庫的可見性相同。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的身份驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。 - exist_ok (
bool, 選填, 預設為False) — 若為True,當儲存庫已存在時不會拋出錯誤。 - space_hardware (
SpaceHardware或str, 選填) — 如果 repo_type 為 “space”,可選擇硬體。範例:"t4-medium"。完整清單請參閱 SpaceHardware。 - space_storage (
SpaceStorage或str, 選填) — <已棄用,請改用set_space_volumes> 如果 repo_type 為 “space”,可選擇永久儲存層級。範例:"small"。完整清單請參閱 SpaceStorage。 - space_sleep_time (
int, 選填) — Space 在進入睡眠前需等待的閒置秒數。若您不希望 Space 進入睡眠,請設為-1(升級硬體的預設行為)。對於免費硬體,您無法設定睡眠時間(固定為 48 小時閒置)。僅在 repo_type 為 “space” 時適用。詳細資訊請參閱 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。 - space_secrets (
list[dict[str, str]], 選填) — 要在 Space 中設定的密鑰(secret keys)列表。每個項目的格式為{"key": ..., "value": ..., "description": ...},其中描述(description)為選填。僅在 repo_type 為 “space” 時適用。詳細資訊請參閱 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。 - space_variables (
list[dict[str, str]], 選填) — 要在 Space 中設定的公開環境變數列表。每個項目的格式為{"key": ..., "value": ..., "description": ...},其中描述(description)為選填。僅在 repo_type 為 “space” 時適用。詳細資訊請參閱 https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables。 - space_volumes (
list[Volume], 選填) — 在複製時掛載到 Space 的 Volume 物件列表。每個儲存卷都有一個type("bucket"、"model"、"dataset"或"space")、一個source(儲存庫或 bucket ID)、一個mount_path(容器內路徑),以及選填的revision、read_only和path欄位。僅在 repo_type 為 “space” 時適用。
返回
新建立的儲存庫 URL。其值為 str 的子類別,包含如 endpoint、repo_type 和 repo_id 等屬性。
引發
RepositoryNotFoundError 或 HfHubHTTPError
- RepositoryNotFoundError — 若找不到
from_id或to_id其中之一。原因可能是該 ID 不存在,或是設定為private且您沒有存取權限。 HfHubHTTPError— 若 HuggingFace API 回傳錯誤。
複製 Hub 上的儲存庫(模型、資料集或 Space)。
此操作執行伺服器端的複製,保留完整的 git 歷史記錄和 LFS 物件,無需進行本地下載/上傳的來回傳輸。
範例
>>> from huggingface_hub import duplicate_repo
# Duplicate a model to your account
>>> duplicate_repo("google/gemma-7b")
RepoUrl('https://huggingface.co/nateraw/gemma-7b',...)
# Duplicate a dataset with a custom name
>>> duplicate_repo("openai/gdpval", to_id="myorg/my-gdpval", repo_type="dataset")
RepoUrl('https://huggingface.co/datasets/myorg/my-gdpval',...)
# Duplicate a Space with custom hardware
>>> duplicate_repo("multimodalart/dreambooth-training", repo_type="space", space_hardware="t4-medium")
RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...)duplicate_space
< 原始碼 >( from_id: str to_id: str | None = None private: bool | None = None visibility: RepoVisibility_T | None = None token: bool | str | None = None exist_ok: bool = False hardware: SpaceHardware | None = None storage: SpaceStorage | None = None sleep_time: int | None = None secrets: list[dict[str, str]] | None = None variables: list[dict[str, str]] | None = None ) → RepoUrl
參數
- from_id (
str) — 要複製的 Space ID。範例:"pharma/CLIP-Interrogator"。 - to_id (
str, 選填) — 新 Space 的 ID。範例:"dog/CLIP-Interrogator"。若未提供,新 Space 將與原始 Space 名稱相同,但建立在您的帳戶下。 - private (
bool, 選填) — 新 Space 是否應為私人。預設與原始 Space 的隱私設定相同。不可與visibility同時傳入。 - visibility (
Literal["public", "private", "protected"], 選填) — 新 Space 的可見性。可以是"public"、"private"或"protected"。預設與原始 Space 的可見性相同。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的身份驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。 - exist_ok (
bool, 選填, 預設為False) — 若為True,當儲存庫已存在時不會拋出錯誤。 - hardware (
SpaceHardware或str, 選填) — 硬體選擇。範例:"t4-medium"。完整清單請參閱 SpaceHardware。 - storage (
SpaceStorage或str, 選填) — 永久儲存層級選擇。範例:"small"。完整清單請參閱 SpaceStorage。 - sleep_time (
int, 選填) — Space 在進入睡眠前需等待的閒置秒數。若您不希望 Space 進入睡眠,請設為-1(升級硬體的預設行為)。對於免費硬體,您無法設定睡眠時間(固定為 48 小時閒置)。詳細資訊請參閱 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。 - secrets (
list[dict[str, str]], 選填) — 要在 Space 中設定的密鑰列表。每個項目的格式為{"key": ..., "value": ..., "description": ...},其中描述(description)為選填。詳細資訊請參閱 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。 - 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 等屬性。
引發
RepositoryNotFoundError 或 HfHubHTTPError
- RepositoryNotFoundError — 若找不到
from_id或to_id其中之一。原因可能是該 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", visibility="private")
RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...)
duplicate_space已棄用,將在 2.0 版本中移除。請改用 duplicate_repo()。
edit_discussion_comment
< 原始碼 >( repo_id: str discussion_num: int comment_id: str new_content: str token: bool | str | None = None repo_type: str | None = None ) → DiscussionComment
參數
- repo_id (
str) — 命名空間(使用者或組織名稱)與儲存庫名稱,中間以/分隔。 - discussion_num (
int) — 討論 (Discussion) 或合併請求 (Pull Request) 的編號。必須為嚴格的正整數。 - comment_id (
str) — 要編輯的留言 ID。 - new_content (
str) — 留言的新內容。留言支援 Markdown 格式。 - repo_type (
str, 選填) — 若上傳至資料集 (dataset) 或空間 (space),請設為"dataset"或"space";若上傳至模型 (model),請設為None或"model"。預設為None。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
編輯後的留言
編輯討論 / 合併請求中的留言。
可能會引發下列錯誤
HTTPError如果 HuggingFace API 回傳錯誤ValueError如果某些參數值無效- RepositoryNotFoundError 如果找不到要下載的儲存庫。這可能是因為它不存在,或者它被設為
private(私人)且您沒有存取權限。
enable_space_dev_mode
< 原始碼 >( repo_id: str token: bool | str | None = None ) → SpaceRuntime
參數
- repo_id (
str) — 要啟用開發模式的 Space ID。範例:"Salesforce/BLIP2"。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
關於您 Space 的執行階段資訊。
- RepositoryNotFoundError — 若找不到您的 Space(錯誤 404)。很可能是 repo_id 錯誤,或是您的 Space 為私人狀態但您未經驗證。
- HfHubHTTPError — 403 Forbidden:只有 Space 的擁有者才能設定開發模式。若您想管理非自己擁有的 Space,請透過開啟討論(Discussion)詢問擁有者,或是複製該 Space。
- BadRequestError — 若您的 Space 是靜態 Space。靜態 Space 始終在執行中且不計費。若您想隱藏靜態 Space,可以將其設為私人。
在 Space 上啟用開發模式。
Spaces 開發模式(Dev Mode)旨在簡化應用程式的除錯流程,並透過允許您在不停止 Space 容器本身的情況下重新啟動應用程式,來加快在 Spaces 上的疊代速度。此功能為 PRO 或 Team & Enterprise 方案的一部分。詳細資訊請參閱 https://huggingface.co/docs/hub/spaces-dev-mode。
enable_webhook
< 原始碼 >( webhook_id: str token: bool | str | None = None ) → WebhookInfo
參數
- webhook_id (
str) — 要啟用的 webhook 之唯一識別碼。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 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
< 原始碼 >( job_id: str namespace: str | None = None follow: bool = False tail: int | None = None token: bool | str | None = None )
參數
- job_id (
str) — 作業 (Job) 的 ID。 - namespace (
str, 選填) — 作業執行所在的命名空間。預設為當前使用者的命名空間。 - follow (
bool, 選填) — 若為True,將即時串流顯示日誌直到作業完成(阻塞式)。若為False(預設),則僅抓取當前可用的日誌並立即回傳(非阻塞式)。 - tail (
int, 選填) — 要回傳的日誌最大行數。與follow=True搭配使用時,會從最後 N 行開始並繼續串流後續產生的新日誌。若為follow=False,則僅回傳當前可用日誌的最後 N 行。 - token
(Union[bool, str, None], 選填) — 有效的使用者存取權杖。若未提供,將使用本地端儲存的權杖,這是建議的驗證方法。若要停用驗證,請設為False。請參考: https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
抓取 Hugging Face 基礎設施上某個運算作業的所有日誌。
範例
>>> from huggingface_hub import fetch_job_logs, run_job
>>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])
>>> for log in fetch_job_logs(job_id=job.id):
... print(log)
Hello from HF compute!
>>> # Non-blocking: fetch only currently available logs
>>> for log in fetch_job_logs(job_id=job.id, follow=False):
... print(log)
>>> # Stream logs starting from the last 100 lines
>>> for log in fetch_job_logs(job_id=job.id, follow=True, tail=100):
... print(log)fetch_job_metrics
< 原始碼 >( job_id: str namespace: str | None = None token: bool | str | None = None )
參數
- job_id (
str) — 作業 (Job) 的 ID。 - namespace (
str, 選填) — 作業執行所在的命名空間。預設為當前使用者的命名空間。 - token
(Union[bool, str, None], 選填) — 有效的使用者存取權杖。若未提供,將使用本地端儲存的權杖,這是建議的驗證方法。若要停用驗證,請設為False。請參考: https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
抓取 Hugging Face 基礎設施上某個運算作業的所有即時指標。
範例
>>> 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"
}fetch_space_logs
< 原始碼 >( repo_id: str build: bool = False follow: bool = False token: bool | str | None = None ) → Iterable[str]
參數
- repo_id (
str) — Space 的 ID。範例:"bigcode/in-the-stack"。 - build (
bool, 選填,預設為False) — 若為True,將抓取容器構建 (container build) 日誌(當 Space 卡在BUILD_ERROR時很有用)。若為False(預設),將抓取執行 (run) 日誌,即正在執行的應用程式之 stdout/stderr。 - follow (
bool, 選填,預設為False) — 若為True,將即時串流顯示日誌(阻塞式),直到伺服器關閉串流或發出KeyboardInterrupt為止。若為False(預設),則僅抓取當前緩衝的日誌並立即回傳(非阻塞式,類似docker logs)。 - token (
bool或str, 選填) — 有效的使用者存取權杖。預設為本地端儲存的權杖,這是建議的驗證方法。若要停用驗證,請設為False。請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
返回
Iterable[str]
一個產生器,會在日誌行可用時產生並輸出。
在 Hub 上抓取 Space 的執行或構建日誌。
適用於除錯構建失敗或在執行時崩潰的 Space,特別是在無法從瀏覽器讀取日誌的指令碼或代理工作流程中特別有用。
範例
>>> from huggingface_hub import fetch_space_logs
>>> # Non-blocking: print currently available run logs and exit.
>>> for line in fetch_space_logs("username/my-space"):
... print(line, end="")
>>> # Debug a build failure:
>>> for line in fetch_space_logs("username/my-space", build=True):
... print(line, end="")
>>> # Stream run logs until the server closes the stream.
>>> for line in fetch_space_logs("username/my-space", follow=True):
... print(line, end="")file_exists
< 原始碼 >( repo_id: str filename: str repo_type: str | None = None revision: str | None = None token: str | bool | None = None )
參數
- repo_id (
str) — 命名空間(使用者或組織名稱)與儲存庫名稱,中間以/分隔。 - filename (
str) — 要檢查的檔案名稱,例如:"config.json" - repo_type (
str, 選填) — 若從資料集 (dataset) 或空間 (space) 取得儲存庫資訊,請設為"dataset"或"space";若從模型 (model) 取得,請設為None或"model"。預設為None。 - revision (
str, 選填) — 要從中取得資訊的儲存庫修訂版本。預設為"main"分支。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
檢查 Hugging Face Hub 上的儲存庫中是否存在特定檔案。
get_bucket_file_metadata
< 原始碼 >( bucket_id: str remote_path: str token: str | bool | None = None ) → BucketFileMetadata
參數
- bucket_id (
str) — Bucket 的 ID(例如"username/my-bucket")。 - remote_path (
str) — Bucket 中的檔案路徑。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
包含大小和 Xet 資訊的檔案中繼資料。
抓取 Bucket 中檔案的中繼資料。
get_bucket_paths_info
< 原始碼 >( bucket_id: str paths: Iterable[str] token: str | bool | None = None ) → Iterable[BucketFile]
參數
- bucket_id (
str) — Bucket 的 ID(例如"username/my-bucket")。 - paths (
Iterable[str]) — 要取得資訊的路徑。如果路徑不存在,將會被忽略且不會引發例外。僅支援檔案路徑。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Iterable[BucketFile]
關於這些路徑的資訊,以 BucketFile 物件的可迭代形式呈現。
取得關於 Bucket 路徑的資訊。
呼叫會以 1000 個路徑為一批次進行。結果會在收到時立即產生並輸出。
範例
>>> from huggingface_hub import get_bucket_paths_info
>>> paths_info = get_bucket_paths_info("username/my-bucket", ["file.txt", "checkpoints/model.safetensors"])
>>> for info in paths_info:
... print(info)
BucketFile(type='file', path='file.txt', size=2379, xet_hash='96e637d9665bd35477b1908a23f2e254edfba0618dbd2d62f90a6baee7d139cf', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc))
BucketFile(type='file', path='checkpoints/model.safetensors', size=2408828, xet_hash='3ed0e9fefe788ddd61d1e26eba67057e9740a064b009256fbafadf6bb95785ca', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc))get_collection
< 原始碼 >( collection_slug: str token: bool | str | None = None )
參數
- collection_slug (
str) — Hub 上集合的別名 (slug)。範例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (字串)。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 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
)get_dataset_leaderboard
< 原始碼 >( repo_id: str token: bool | str | None = None timeout: float | None = None ) → list[DatasetLeaderboardEntry]
參數
- repo_id (
str) — 命名空間(使用者或組織名稱)與儲存庫名稱,中間以/分隔。例如:"allenai/olmOCR-bench"。 - token (
bool或str, 選填) — 有效的使用者存取權杖。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - timeout (
float, 選填) — 是否為對 Hub 的請求設定逾時時間。
返回
list[DatasetLeaderboardEntry]
一個 DatasetLeaderboardEntry 物件清單,代表排行榜項目,並按排名排序。
取得 Hub 上某個資料集的排行榜。
排行榜根據模型在指定基準測試資料集上的評估分數進行排名。並非所有資料集都有排行榜——只有提交了評估結果的基準測試資料集才有。這提供了以資料集為中心的評估分數視角;若要以模型為中心檢視,請使用 expand=["evalResults"] 的 model_info()。
可能會引發下列錯誤
- RepositoryNotFoundError 如果找不到該儲存庫。這可能是因為它不存在,或者它被設為
private(私人)且您沒有存取權限。- HfHubHTTPError 如果該資料集沒有排行榜。
列出所有有效的資料集標籤,並以巢狀命名空間物件形式呈現。
get_discussion_details
< 原始碼 >( repo_id: str discussion_num: int repo_type: str | None = None token: bool | str | None = None )
參數
- repo_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,中間以/分隔。 - discussion_num (
int) — 討論 (Discussion) 或合併請求 (Pull Request) 的編號。必須是嚴格的正整數。 - repo_type (
str, 選填) — 若上傳至資料集 (dataset) 或空間 (space),請設為"dataset"或"space";若上傳至模型,則設為None或"model"。預設為None。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (string)。預設為本機儲存的權杖,這是推薦的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
從 Hub 取得討論或合併請求的詳細資訊。
可能會引發下列錯誤
HTTPError如果 HuggingFace API 回傳錯誤ValueError如果某些參數值無效- RepositoryNotFoundError 如果找不到要下載的儲存庫。這可能是因為它不存在,或者它被設為
private(私人)且您沒有存取權限。
get_full_repo_name
< 原始碼 >( model_id: str organization: str | None = None token: bool | str | None = None ) → str
參數
- model_id (
str) — 模型的名稱。 - organization (
str, 選填) — 若有傳入,儲存庫名稱將位於該組織命名空間下,而非使用者命名空間下。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (string)。預設為本機儲存的權杖,這是推薦的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
str
若未傳入組織名稱,則為使用者命名空間下的儲存庫名稱 ({username}/{model_id});否則為組織命名空間下的儲存庫名稱 ({organization}/{model_id})。
傳回給定模型 ID 和選填組織名稱的儲存庫名稱。
get_hf_file_metadata
< 原始碼 >( url: str token: bool | str | None = None timeout: float | None = 10 )
參數
- url (
str) — 檔案連結,例如由 hf_hub_url() 傳回。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (string)。預設為本機儲存的權杖,這是推薦的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - timeout (
float, 選填, 預設為 10) — 等候伺服器傳送詮釋資料的秒數,超過後將放棄請求。
針對給定的 URL,獲取 Hub 上已版本化檔案的詮釋資料。
get_inference_endpoint
< 原始碼 >( name: str namespace: str | None = None token: bool | str | None = None ) → InferenceEndpoint
參數
- name (
str) — 要取得相關資訊的推論端點名稱。 - namespace (
str, 選填) — 推論端點所在的命名空間。預設為目前的使用者。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (string)。預設為本機儲存的權杖,這是推薦的驗證方式(請參閱 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
< 原始碼 >( organization: str token: bool | str | None = None ) → Organization
參數
- organization (
str) — 要取得概覽的組織名稱。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (string)。預設為本機儲存的權杖,這是推薦的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Organization
包含組織概覽的 Organization 物件。
引發
HTTPError
HTTPError— 若該組織在 Hub 上不存在,則回傳 HTTP 404。
取得 Hub 上組織的概覽。
get_paths_info
< 原始碼 >( repo_id: str paths: list[str] | str expand: bool = False revision: str | None = None repo_type: str | None = None token: str | bool | None = None ) → list[Union[RepoFile, RepoFolder]]
參數
- repo_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,中間以/分隔。 - paths (
Union[list[str], str], 選填) — 要取得資訊的路徑。若路徑不存在,將會被忽略,不會觸發例外。 - expand (
bool, 選填, 預設為False) — 是否取得關於路徑的更多資訊(例如最後一次提交與檔案的安全掃描結果)。此操作對伺服器而言成本較高,因此每一頁僅傳回 50 筆結果(而非 1000 筆)。由於huggingface_hub已實作分頁功能,除了取得結果的時間外,對您而言是透明的。 - revision (
str, 選填) — 要取得資訊的儲存庫版本。預設為"main"分支。 - repo_type (
str, 選填) — 要取得資訊的儲存庫類型 ("model","dataset"或"space")。預設為"model"。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (string)。預設為本機儲存的權杖,這是推薦的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
list[Union[RepoFile, RepoFolder]]
路徑資訊,為 RepoFile 和 RepoFolder 物件的列表。 (RepoFile)
- RepositoryNotFoundError — 如果找不到儲存庫(錯誤 404):repo_id/repo_type 錯誤、儲存庫為私人且未經驗證,或是儲存庫不存在。
- RevisionNotFoundError — 如果在儲存庫中找不到該版本(錯誤 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
< 原始碼 >( repo_id: str author: str | None = None discussion_type: constants.DiscussionTypeFilter | None = None discussion_status: constants.DiscussionStatusFilter | None = None repo_type: str | None = None token: bool | str | None = None ) → Iterator[Discussion]
參數
- repo_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,中間以/分隔。 - author (
str, 選填) — 傳入值以依討論作者篩選。None代表不篩選。預設為None。 - discussion_type (
str, 選填) — 設為"pull_request"僅獲取合併請求,設為"discussion"僅獲取討論。設為"all"或None可同時獲取兩者。預設為None。 - discussion_status (
str, 選填) — 設為"open"(或"closed") 僅獲取開啟 (或關閉) 的討論。設為"all"或None可同時獲取兩者。預設為None。 - repo_type (
str, 選填) — 若從資料集或空間獲取,請設為"dataset"或"space";若從模型獲取,則設為None或"model"。預設為None。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (string)。預設為本機儲存的權杖,這是推薦的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Iterator[Discussion]
Discussion 物件的迭代器。
獲取給定儲存庫的討論與合併請求。
範例
get_safetensors_metadata
< 原始碼 >( repo_id: str repo_type: str | None = None revision: str | None = None token: bool | str | None = None ) → SafetensorsRepoMetadata
參數
- repo_id (
str) — 使用者或組織名稱與儲存庫名稱,中間以/分隔。 - repo_type (
str, 選填) — 若檔案位於資料集或空間,請設為"dataset"或"space";若位於模型,則設為None或"model"。預設為None。 - revision (
str, 選填) — 要獲取檔案的 Git 版本。可以是分支名稱、標籤或提交雜湊值。預設為"main"分支的最新狀態。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (string)。預設為本機儲存的權杖,這是推薦的驗證方式(請參閱 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 檔案解析詮釋資料,請使用 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
< 原始碼 >( repo_id: str token: bool | str | None = None ) → SpaceRuntime
參數
- repo_id (
str) — 要更新的儲存庫 ID。例如:"bigcode/in-the-stack"。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (string)。預設為本機儲存的權杖,這是推薦的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
有關 Space 的執行時間資訊,包含 Space 階段與硬體。
取得空間的執行階段資訊。
get_space_secrets
< 原始碼 >( repo_id: str token: bool | str | None = None ) → dict[str, SpaceSecret]
參數
- repo_id (
str) — 要查詢的儲存庫 ID。例如:"bigcode/in-the-stack"。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (string)。預設為本機儲存的權杖,這是推薦的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
dict[str, SpaceSecret]
以祕密名稱為鍵的 SpaceSecret 物件字典。
取得空間的所有祕密 (secrets)。
祕密值是唯寫的,無法讀回。僅會傳回金鑰、說明與最後更新時間。
祕密允許將祕密金鑰或權杖設定至 Space 中,而無需將其寫死在程式碼中。欲知詳情,請參閱 https://huggingface.co/docs/hub/spaces-overview#managing-secrets。
get_space_variables
< 原始碼 >( repo_id: str token: bool | str | None = None )
參數
- repo_id (
str) — 要查詢的儲存庫 ID。例如:"bigcode/in-the-stack"。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (string)。預設為本機儲存的權杖,這是推薦的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
取得空間的所有變數。
變數允許將環境變數設定至 Space 中,而無需將其寫死在程式碼中。欲知詳情,請參閱 https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables
get_user_overview
< 原始碼 >( username: str token: bool | str | None = None ) → User
參數
- username (
str) — 要取得概覽的使用者名稱。 - token (
bool或str, 選填) — 有效的使用者存取權杖 (string)。預設為本機儲存的權杖,這是推薦的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
User
包含使用者概覽的 User 物件。
引發
HfHubHTTPError
HfHubHTTPError— 若該使用者在 Hub 上不存在,則回傳 HTTP 404。
取得 Hub 上使用者的概覽。
get_webhook
< 原始碼 >( webhook_id: str token: bool | str | None = None ) → WebhookInfo
參數
- webhook_id (
str) — 要取得的 Webhook 唯一識別碼。 - token (
bool或str,選擇性) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的身份驗證方式(參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。
返回
關於 Webhook 的資訊。
透過 ID 取得 Webhook。
範例
>>> 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
< 來源 >( repo_id: str user: str repo_type: str | None = None token: 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— 若儲存庫未設為閘控 (gated),則回應 HTTP 400。HfHubHTTPError— 如果使用者已經擁有對該儲存庫的存取權限,則為 HTTP 400 錯誤。HfHubHTTPError— 若您對儲存庫僅有唯讀權限,則回應 HTTP 403。如果您在該儲存庫所屬的組織中沒有write或admin角色,或如果您傳入的是read權杖,就會發生此情況。HfHubHTTPError— 若 Hub 上不存在該使用者,則回應 HTTP 404。
為給定的門控(gated)儲存庫向使用者授與存取權限。
授與存取權限不需要使用者自行發送存取請求。使用者會被自動添加到已接受列表中,這意味著他們可以下載檔案。您可以隨時使用 cancel_access_request() 或 reject_access_request() 來撤銷已授與的權限。
關於閘控儲存庫的更多資訊,請參閱 https://huggingface.co/docs/hub/models-gated。
hf_hub_download
< 來源 >( repo_id: str filename: str subfolder: str | None = None repo_type: str | None = None revision: str | None = None cache_dir: str | Path | None = None local_dir: str | Path | None = None force_download: bool = False etag_timeout: float = 10 token: bool | str | None = None local_files_only: bool = False tqdm_class: type[base_tqdm] | None = None dry_run: bool = False ) → str 或 DryRunFileInfo
參數
- repo_id (
str) — 使用者名稱或組織名稱與儲存庫名稱,以/分隔。 - filename (
str) — 儲存庫中的檔案名稱。 - subfolder (
str,選擇性) — 對應儲存庫內資料夾的選用值。 - repo_type (
str,選擇性) — 若從資料集或 Space 下載,請設為"dataset"或"space";若從模型下載,則設為None或"model"。預設為None。 - revision (
str,選擇性) — 選用的 Git 修訂版本 ID,可以是分支名稱、標籤或提交雜湊值(commit hash)。 - cache_dir (
str,Path,選擇性) — 儲存快取檔案的資料夾路徑。 - local_dir (
str或Path,選擇性) — 若提供,下載的檔案將會放置在此目錄下。 - force_download (
bool,選擇性,預設為False) — 即便檔案已存在於本地快取中,是否仍要下載該檔案。 - etag_timeout (
float,選擇性,預設為10) — 獲取 ETag 時,在放棄請求前需等待伺服器傳送資料的秒數,此參數會傳遞給httpx.request。 - token (
bool或str,選擇性) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的身份驗證方式(參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。 - local_files_only (
bool,選擇性,預設為False) — 若為True,則避免下載檔案,若該檔案存在,則直接回傳本地快取檔案的路徑。 - tqdm_class (
tqdm,選擇性) — 若提供,則覆寫預設的進度條行為。傳入的參數必須繼承自tqdm.auto.tqdm或至少模擬其行為。預設為自訂的 HF 進度條,該進度條可透過設定HF_HUB_DISABLE_PROGRESS_BARS環境變數來停用。 - dry_run (
bool,選擇性,預設為False) — 若為True,則執行試運行(dry run)而不實際下載檔案。回傳一個 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 的一個子資料夾(依儲存庫類型進行命名空間隔離)
- 在每個儲存庫資料夾中
- refs 是最新已知修訂版本 => 提交雜湊值(commit_hash)配對的列表
- blobs 包含實際的檔案 Blob(根據它們是 LFS 檔案與否,由其 git-sha 或 sha256 識別)
- snapshots 包含每個提交的一個子資料夾,每個“提交”包含在該特定提交時已解析的檔案子集。每個檔案名稱都是一個指向該特定提交時 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
< 來源 >( repo_id: str discussion_num: int comment_id: str token: bool | str | None = None repo_type: str | None = None ) → DiscussionComment
參數
- repo_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,以/分隔。 - discussion_num (
int) — 討論或 Pull Request 的編號。必須為嚴格正整數。 - comment_id (
str) — 要編輯的留言 ID。 - repo_type (
str,選擇性) — 若上傳到資料集或 Space,請設為"dataset"或"space";若上傳到模型,則設為None或"model"。預設為None。 - token (
bool或str,選擇性) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的身份驗證方式(參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。
隱藏的留言
隱藏討論 / Pull Request 中的一則留言。
隱藏的留言內容將無法再被檢索。隱藏留言的操作是不可逆的。
可能會引發下列錯誤
HTTPError如果 HuggingFace API 回傳錯誤ValueError如果某些參數值無效- RepositoryNotFoundError 如果找不到要下載的儲存庫。這可能是因為它不存在,或者它被設為
private(私人)且您沒有存取權限。
inspect_job
< 來源 >( job_id: str namespace: str | None = None token: bool | str | None = None )
參數
- job_id (
str) — 作業(Job)的 ID。 - namespace (
str,選擇性) — 作業執行所在的命名空間。預設為目前使用者的命名空間。 - token
(Union[bool, str, None],選擇性) — 有效的使用者存取權杖。若未提供,將使用本地儲存的權杖,這是推薦的身份驗證方式。設為False以停用身份驗證。參閱:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
檢查 Hugging Face 基礎設施上的運算作業(Compute Job)。
範例
>>> 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
< 來源 >( scheduled_job_id: str namespace: str | None = None token: bool | str | None = None )
參數
- scheduled_job_id (
str) — 排程作業(Scheduled Job)的 ID。 - namespace (
str,選擇性) — 排程作業所在的命名空間。預設為目前使用者的命名空間。 - token
(Union[bool, str, None],選擇性) — 有效的使用者存取權杖。若未提供,將使用本地儲存的權杖,這是推薦的身份驗證方式。設為False以停用身份驗證。參閱:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
檢查 Hugging Face 基礎設施上的排程運算作業。
kernel_info
< 來源 >( repo_id: str revision: str | None = None timeout: float | None = None token: bool | str | None = None ) → ModelInfo
參數
- repo_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,以/分隔。 - revision (
str,選擇性) — 要從中取得資訊的 Kernel 儲存庫修訂版本。 - timeout (
float,選擇性) — 是否要為對 Hub 的請求設定逾時時間。 - token (
bool或str,選擇性) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的身份驗證方式(參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。
返回
Kernel 儲存庫資訊。
取得 huggingface.co 上特定 Kernel 的資訊。
list_accepted_access_requests
< 來源 >( repo_id: str repo_type: str | None = None token: bool | str | None = None ) → Iterable[AccessRequest]
參數
- repo_id (
str) — 要取得存取請求的儲存庫 ID。 - repo_type (
str,選擇性) — 要取得存取請求的儲存庫類型。必須為model、dataset或space其中之一。預設為model。 - token (
bool或str,選擇性) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的身份驗證方式(參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。
返回
Iterable[AccessRequest]
AccessRequest 物件的可迭代物件。每次包含 username、email、status 和 timestamp 屬性。如果門控儲存庫有自訂表單,fields 屬性將會填入使用者的回答。
引發
HfHubHTTPError
HfHubHTTPError— 若儲存庫未設為閘控 (gated),則回應 HTTP 400。HfHubHTTPError— 若您對儲存庫僅有唯讀權限,則回應 HTTP 403。如果您在該儲存庫所屬的組織中沒有write或admin角色,或如果您傳入的是read權杖,就會發生此情況。
取得給定門控儲存庫的已接受存取請求。
已接受請求意味著使用者已請求該儲存庫的存取權,且該請求已被接受。使用者可以下載儲存庫的任何檔案。如果核准模式是自動的,則此列表預設應包含所有請求。已接受的請求可以隨時使用 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_bucket_tree
< 來源 >( bucket_id: str prefix: str | None = None recursive: bool | None = None token: str | bool | None = None ) → Iterable[Union[BucketFile, BucketFolder]]
參數
- bucket_id (
str) — Bucket 的 ID(例如"username/my-bucket")。 - prefix (
str,選擇性) — 將結果篩選為路徑以此前綴開頭的檔案。 - recursive (
bool, 選填) — 若為True,則遞迴列出檔案。若為False(預設值),則僅列出根目錄下的檔案與資料夾。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Iterable[Union[BucketFile, BucketFolder]]
包含檔案與目錄資訊(路徑等)的 BucketFile 與 BucketFolder 物件的迭代器。
列出儲存貯體(bucket)中的檔案。
list_buckets
< 原始碼 >( namespace: str | None = None search: str | None = None token: bool | str | None = None ) → Iterable[BucketInfo]
參數
- namespace (
str, 選填) — 列出此命名空間(使用者或組織)下的儲存貯體。預設為列出使用者的儲存貯體。 - search (
str, 選填) — 用於篩選儲存貯體名稱的搜尋字串。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Iterable[BucketInfo]
BucketInfo 物件的迭代器。
列出 Hub 上特定命名空間下的儲存貯體。
範例
>>> from huggingface_hub import list_buckets
>>> for bucket in list_buckets(): # lists buckets in the user's namespace
... print(bucket)
>>> for bucket in list_buckets(namespace="huggingface"): # lists buckets in the "huggingface" organization
... print(bucket)
>>> for bucket in list_buckets(search="my-prefix"): # filter buckets by name
... print(bucket)list_collections
< 原始碼 >( owner: list[str] | str | None = None item: list[str] | str | None = None sort: CollectionSort_T | None = None limit: int | None = None token: bool | str | None = None ) → Iterable[Collection]
參數
- owner (
list[str]或str, 選填) — 依擁有者的使用者名稱篩選。 - item (
list[str]或str, 選填) — 篩選包含特定項目的集合。範例:"models/teknium/OpenHermes-2.5-Mistral-7B"、"datasets/squad"或"papers/2311.12983"。 - sort (
Literal["lastModified", "trending", "upvotes"], 選填) — 依最後修改時間、趨勢或按讚數對集合進行排序。 - limit (
int, 選填) — 要傳回的集合數量上限。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Iterable[Collection]
Collection 物件的迭代器。
列出 Hugging Face Hub 上的集合,並可加入篩選條件。
列出集合時,每個集合的項目列表最多截斷為 4 個。若要擷取集合中的所有項目,必須使用 get_collection()。
list_daily_papers
< 原始碼 >( date: str | None = None token: bool | str | None = None week: str | None = None month: str | None = None submitter: str | None = None sort: DailyPapersSort_T | None = None p: int | None = None limit: int | None = None ) → Iterable[PaperInfo]
參數
- date (
str, 選填) — 取得每日論文的日期(ISO 格式 YYYY-MM-DD)。預設為最新論文。 - token (Union[bool, str, None], 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖。若要停用驗證,請傳入
False。 - week (
str, 選填) — 取得每日論文的週次(ISO 格式 YYYY-Www)。例如:2025-W09。 - month (
str, 選填) — 取得每日論文的月份(ISO 格式 YYYY-MM)。例如:2025-02。 - submitter (
str, 選填) — 依提交者的使用者名稱篩選每日論文。 - sort (
Literal["publishedAt", "trending"], 選填) — 每日論文的排序方式。可為publishedAt或trending。預設為"publishedAt"。 - p (
int, 選填) — 分頁頁碼。預設為 0。 - limit (
int, 選填) — 要擷取的論文數量上限。預設為 50。
返回
Iterable[PaperInfo]
huggingface_hub.hf_api.PaperInfo 物件的迭代器。
列出在 Hugging Face Hub 上指定日期發佈的每日論文。
list_dataset_parquet_files
< 原始碼 >( repo_id: str config: str | None = None token: bool | str | None = None ) → list[DatasetParquetEntry]
參數
- repo_id (
str) — 資料集儲存庫 ID(例如:"username/dataset-name")。 - config (
str, 選填) — 依特定的設定/子集名稱進行篩選。若提供,則僅傳回該設定的 parquet 檔案。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
list[DatasetParquetEntry]
包含每個 parquet 檔案的設定(config)、拆分(split)、URL 與大小的 DatasetParquetEntry 物件列表。
列出 Hub 上某資料集可用的 parquet 檔案。
所有託管在 Hub 上的資料集都會由 Dataset Viewer 自動轉換為 Parquet。此方法會傳回包含其 URL、設定、拆分與大小的 parquet 檔案清單。
list_datasets
< 原始碼 >( filter: str | Iterable[str] | None = None author: str | None = None benchmark: Literal[True] | Literal['official'] | str | None = None dataset_name: str | None = None gated: bool | None = None language_creators: str | list[str] | None = None language: str | list[str] | None = None multilinguality: str | list[str] | None = None size_categories: str | list[str] | None = None task_categories: str | list[str] | None = None task_ids: str | list[str] | None = None search: str | None = None sort: DatasetSort_T | None = None limit: int | None = None expand: list[ExpandDatasetProperty_T] | None = None full: bool | None = None token: bool | str | None = None ) → Iterable[DatasetInfo]
參數
- filter (
str或Iterable[str], 選填) — 用於篩選 Hub 上資料集的字串或字串列表。 - author (
str, 選填) — 用於識別所傳回資料集作者的字串。 - benchmark (
True,"official",str, 選填) — 依基準測試(benchmark)篩選資料集。可傳入True或"official"以傳回官方基準測試資料集。為了未來相容性,也可以是代表基準測試名稱的字串(目前僅支援 “official”)。 - dataset_name (
str, 選填) — 可用於依名稱識別 Hub 上資料集的字串或字串列表,例如SQAC或wikineural。 - gated (
bool, 選填) — 用於篩選 Hub 上是否為存取受限(gated)資料集的布林值。預設情況下會傳回所有資料集。若傳入gated=True,則僅傳回受限資料集。若傳入gated=False,則僅傳回非受限資料集。 - language_creators (
str或List, 選填) — 用於識別 Hub 上資料集資料管理方式(如crowdsourced或machine_generated)的字串或字串列表。 - language (
str或List, 選填) — 用於依語言(兩位字元代碼)篩選 Hub 上資料集的字串或字串列表。 - multilinguality (
str或List, 選填) — 用於篩選包含多語言資料集的字串或字串列表。 - size_categories (
str或List, 選填) — 用於依資料集大小(如100K<n<1M或1M<n<10M)識別 Hub 上資料集的字串或字串列表。 - tags (
str或List, 選填) — 已棄用。請改用filter參數傳入標籤以篩選資料集。 - task_categories (
str或List, 選填) — 用於依指定任務(如audio_classification或named_entity_recognition)識別 Hub 上資料集的字串或字串列表。 - task_ids (
str或List, 選填) — 用於依特定任務(如speech_emotion_recognition或paraphrase)識別 Hub 上資料集的字串或字串列表。 - search (
str, 選填) — 將包含在所傳回資料集名稱中的搜尋字串。 - sort (
DatasetSort_T, 選填) — 用於排序結果資料集的鍵值。可能的值為 “created_at”、“downloads”、“last_modified”、“likes” 和 “trending_score”。 - limit (
int, 選填) — 擷取資料集的數量上限。若將此選項設為None,則會擷取所有資料集。 - expand (
list[ExpandDatasetProperty_T], 選填) — 在回應中傳回的屬性列表。使用時,僅會傳回列表中指定的屬性。若已傳入full,則無法使用此參數。可能的值為"author"、"cardData"、"citation"、"createdAt"、"disabled"、"description"、"downloads"、"downloadsAllTime"、"gated"、"lastModified"、"likes"、"mainSize"、"paperswithcode_id"、"private"、"siblings"、"sha"、"tags"、"trendingScore"、"usedStorage"和"resourceGroup"。 - full (
bool, 選填) — 是否擷取所有資料集資料,包括last_modified、card_data和檔案。可包含如 PapersWithCode ID 等實用資訊。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Iterable[DatasetInfo]
huggingface_hub.hf_api.DatasetInfo 物件的迭代器。
列出 Hugging Face Hub 上託管的資料集,並可加入篩選條件。
使用 filter 引數的範例
>>> 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
< 原始碼 >( token: bool | str | None = None ) → Liststr
參數
- token (
bool或str,選填) — 有效的使用者存取權杖(字串)。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。
返回
Liststr
目錄中可用的模型 ID 列表。
列出 Hugging Face 推論目錄(Inference Catalog)中可用的模型。
Inference Catalog 的目標是提供一份經過篩選的模型清單,這些模型皆針對推論進行過優化,並已測試其預設配置。請參閱 https://endpoints.huggingface.co/catalog 查看目錄中可用的模型清單。
使用 create_inference_endpoint_from_catalog() 從目錄部署模型。
list_inference_catalog目前為實驗性功能。其 API 未來可能會有所變動。如果您有任何建議或需求,歡迎提供回饋。
list_inference_endpoints
< 原始碼 >( namespace: str | None = None token: bool | str | None = None ) → listInferenceEndpoint
參數
- namespace (
str,選填) — 要列出端點的命名空間。預設為當前使用者。設定為"*"以列出所有命名空間中的端點(即個人命名空間以及使用者所屬的所有組織)。 - token (
bool或str,選填) — 有效的使用者存取權杖(字串)。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
指定命名空間下的所有推論端點列表。
列出指定命名空間下的所有推論端點。
list_jobs
< 原始碼 >( timeout: int | None = None namespace: str | None = None token: bool | str | None = None )
參數
- timeout (
float,選填) — 是否為 Hub 的請求設定逾時時間。 - namespace (
str,選填) — 列出作業(jobs)的來源命名空間。預設為當前使用者的命名空間。 - token
(Union[bool, str, None],選填) — 有效的使用者存取權杖。若未提供,將使用本地端儲存的權杖,這是建議的驗證方法。若要停用驗證,請設定為False。詳情請參閱:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
列出 Hugging Face 基礎設施上的運算作業(Jobs)。
list_jobs_hardware
< 原始碼 >( token: bool | str | None = None ) → list[JobHardware]
返回
list[JobHardware]
可用硬體配置的列表。
列出 Hugging Face 基礎設施上作業(Jobs)可用的硬體選項。
範例
>>> 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', ephemeral_storage='20 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
< 原始碼 >( repo_id: str repo_type: str | None = None token: bool | str | None = None ) → Iterable[LFSFileInfo]
參數
- repo_id (
str) — 您要列出 LFS 檔案的儲存庫。 - repo_type (
str,選填) — 儲存庫類型。若從資料集(dataset)或空間(space)列出,請設定為"dataset"或"space";若從模型(model)列出,則設為None或"model"。預設為None。 - token (
bool或str,選填) — 有效的使用者存取權杖(字串)。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Iterable[LFSFileInfo]
LFSFileInfo 物件的迭代器。
列出 Hub 上儲存庫中的所有 LFS 檔案。
此功能主要用於計算儲存庫佔用的儲存空間,並最終透過 permanently_delete_lfs_files() 清除大型檔案。請注意,這是一個永久性動作,將會影響所有參照這些已刪除檔案的提交,且無法復原。
範例
>>> 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
< 原始碼 >( user: str | None = None token: bool | str | None = None ) → UserLikes
參數
- user (
str,選填) — 您想要取得按讚列表的使用者名稱。 - token (
bool或str,選填) — 有效的使用者存取權杖(字串)。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
包含使用者名稱以及 3 個儲存庫 ID 列表(模型、資料集與空間各一)的物件。
引發
ValueError
ValueError— 若未傳入user且找不到權杖(無論是透過參數或是機器本身)。
列出使用者在 huggingface.co 上按讚的所有公開儲存庫。
此列表為公開資訊,因此權杖為選填。若未傳入 user,則預設為已登入的使用者。
另請參閱 unlike()。
list_models
< 原始碼 >( filter: str | Iterable[str] | None = None author: str | None = None apps: str | list[str] | None = None gated: bool | None = None inference: Literal['warm'] | None = None inference_provider: Literal['all'] | PROVIDER_T | list[PROVIDER_T] | None = None model_name: str | None = None trained_dataset: str | list[str] | None = None search: str | None = None pipeline_tag: str | None = None num_parameters: str | None = None emissions_thresholds: tuple[float, float] | None = None sort: ModelSort_T | None = None limit: int | None = None expand: list[ExpandModelProperty_T] | None = None full: bool | None = None cardData: bool = False fetch_config: bool = False token: bool | str | None = None ) → Iterable[ModelInfo]
參數
- filter (
str或Iterable[str],選填) — 用於過濾 Hub 上模型的字串或字串列表。模型可依據函式庫、語言、任務、標籤等多種條件進行過濾。 - author (
str,選填) — 用於識別回傳模型之作者(使用者或組織)的字串。 - apps (
str或List,選填) — 用於過濾 Hub 上支援特定應用之模型的字串或字串列表。範例值包括"ollama"或["ollama", "vllm"]。 - gated (
bool,選填) — 用於過濾 Hub 上是否為「存取受限(gated)」模型的布林值。預設回傳所有模型。若傳入gated=True,則僅回傳存取受限的模型;若傳入gated=False,則僅回傳非存取受限的模型。 - inference (
Literal["warm"],選填) — 若設為 "warm",則過濾出 Hub 上目前由至少一個供應商(provider)服務的模型。 - inference_provider (
Literal["all"]或str,選填) — 用於過濾 Hub 上由特定供應商服務之模型的字串。傳入"all"可取得所有由至少一個供應商服務的模型。 - trained_dataset (
str或List,選填) — Hub 上模型所使用之訓練資料集的字串標籤或標籤列表。 - search (
str,選填) — 將包含在回傳模型 ID 中的字串。 - pipeline_tag (
str,選填) — 用於過濾 Hub 上模型的管線標籤字串,例如summarization。 - num_parameters (
str,選填) — 依參數數量過濾模型。接受與 Hub UI 和 API 相同的範圍語法,例如"min:6B,max:128B"、"min:6B"或"max:128B"。 - emissions_thresholds (
Tuple,選填) — 一個包含兩個整數或浮點數的元組,表示用來過濾結果模型的碳足跡最小值與最大值(單位:克)。 - sort (
ModelSort_T,選填) — 用於排序結果模型的關鍵字。可能的值為 "created_at"、"downloads"、"last_modified"、"likes" 和 "trending_score"。 - 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。 - model_name (
str,選填) — (已棄用)。請改用search。
返回
Iterable[ModelInfo]
包含 huggingface_hub.hf_api.ModelInfo 物件的可迭代物件。
列出託管在 Hugging Face 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 models with 6B to 128B parameters
>>> api.list_models(num_parameters="min:6B,max:128B", sort="likes")list_organization_followers
< 原始碼 >( organization: str token: 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— 若該組織在 Hub 上不存在,則會回傳 HTTP 404。
列出 Hub 上組織的追蹤者。
list_organization_members
< 原始碼 >( organization: str token: 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— 若該組織在 Hub 上不存在,則會回傳 HTTP 404。
Hub 上組織的成員列表。
list_papers
< 原始碼 >( query: str | None = None limit: int | None = None token: bool | str | None = None ) → Iterable[PaperInfo]
參數
- query (
str,選填) — 用於尋找論文的搜尋查詢字串。若提供,則回傳符合該查詢的論文。 - limit (
int,選填) — 要回傳的論文數量上限。 - token (Union[bool, str, None],選填) — 有效的使用者存取權杖(字串)。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入
False。
返回
Iterable[PaperInfo]
huggingface_hub.hf_api.PaperInfo 物件的迭代器。
根據搜尋查詢,列出 Hugging Face Hub 上的每日論文。
list_pending_access_requests
< 原始碼 >( repo_id: str repo_type: str | None = None token: bool | str | None = None ) → Iterable[AccessRequest]
參數
- repo_id (
str) — 要取得存取請求的儲存庫 ID。 - repo_type (
str,選填) — 要取得存取請求的儲存庫類型。必須是model、dataset或space其中之一。預設為model。 - token (
bool或str,選填) — 有效的使用者存取權杖(字串)。預設為本地端儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Iterable[AccessRequest]
AccessRequest 物件的可迭代物件。每次包含 username、email、status 和 timestamp 屬性。如果門控儲存庫有自訂表單,fields 屬性將會填入使用者的回答。
引發
HfHubHTTPError
HfHubHTTPError— 若儲存庫未設為閘控 (gated),則回應 HTTP 400。HfHubHTTPError— 若您對儲存庫僅有唯讀權限,則回應 HTTP 403。如果您在該儲存庫所屬的組織中沒有write或admin角色,或如果您傳入的是read權杖,就會發生此情況。
取得特定存取受限(gated)儲存庫的待處理存取請求。
待處理請求表示使用者已請求存取該儲存庫,但請求尚未被處理。如果啟用自動批准模式,此列表應為空。可以使用 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
< 原始碼 >( repo_id: str repo_type: str | None = None token: bool | str | None = None ) → Iterable[AccessRequest]
參數
- repo_id (
str) — 要取得存取請求的儲存庫 ID。 - repo_type (
str, 選填) — 取得存取請求的儲存庫類型。必須為model、dataset或space其中之一。預設為model。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(詳見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Iterable[AccessRequest]
AccessRequest 物件的可迭代物件。每次包含 username、email、status 和 timestamp 屬性。如果門控儲存庫有自訂表單,fields 屬性將會填入使用者的回答。
引發
HfHubHTTPError
HfHubHTTPError— 若儲存庫未設為閘控 (gated),則回應 HTTP 400。HfHubHTTPError— 若您對儲存庫僅有唯讀權限,則回應 HTTP 403。如果您在該儲存庫所屬的組織中沒有write或admin角色,或如果您傳入的是read權杖,就會發生此情況。
取得指定 gated 儲存庫的已拒絕存取請求。
已拒絕的請求意味著使用者曾請求存取該儲存庫,但請求已被儲存庫擁有者(您或您組織中的其他成員)明確拒絕。該使用者無法下載儲存庫中的任何檔案。被拒絕的請求可以隨時透過 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
< 原始碼 >( repo_id: str repo_type: str | None = None token: bool | str | None = None revision: str | None = None formatted: bool = False ) → list[GitCommitInfo]
參數
- repo_id (
str) — 命名空間(使用者或組織名稱)加上儲存庫名稱,並以/分隔。 - repo_type (
str, 選填) — 若要列出資料集或空間的提交記錄,請設為"dataset"或"space";若要列出模型的提交記錄,則設為None或"model"。預設為None。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(詳見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - revision (
str, 選填) — 提交所在的 Git 版本(分支、標籤或提交雜湊值)。預設為"main"分支的開頭。 - formatted (
bool) — 是否回傳 HTML 格式的提交標題與說明。預設為 False。
返回
list[GitCommitInfo]
包含 Hub 上儲存庫提交相關資訊的物件清單。
- RepositoryNotFoundError — 如果找不到儲存庫(錯誤 404):repo_id/repo_type 錯誤、儲存庫為私人且未經驗證,或是儲存庫不存在。
- RevisionNotFoundError — 如果在儲存庫中找不到該版本(錯誤 404)。
取得 Hub 上儲存庫指定版本的提交清單。
提交會依照日期排序(最新提交排在最前面)。
範例
>>> 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
< 原始碼 >( repo_id: str revision: str | None = None repo_type: str | None = None token: str | bool | None = None ) → list[str]
參數
- 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。
返回
list[str]
指定儲存庫中的檔案清單。
取得指定儲存庫中的檔案清單。
list_repo_likers
< 原始碼 >( repo_id: str repo_type: str | None = None token: bool | str | None = None ) → Iterable[User]
參數
- repo_id (
str) — 要檢索的儲存庫。範例:"user/my-cool-model"。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(詳見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - repo_type (
str, 選填) — 若要上傳至資料集或空間,請設為"dataset"或"space";若要上傳至模型,則設為None或"model"。預設為None。
返回
Iterable[User]
huggingface_hub.hf_api.User 物件的可迭代對象。
列出所有在 Hugging Face Hub 上對指定儲存庫按讚的使用者。
另請參閱 list_liked_repos()。
list_repo_refs
< 原始碼 >( repo_id: str repo_type: str | None = None include_pull_requests: bool = False token: str | bool | None = None ) → GitRefs
參數
- repo_id (
str) — 命名空間(使用者或組織名稱)加上儲存庫名稱,並以/分隔。 - repo_type (
str, 選填) — 若要列出資料集、空間或核心的參照,請設為"dataset"、"space"或"kernel";若要列出模型的參照,則設為None或"model"。預設為None。 - include_pull_requests (
bool, 選填) — 是否在清單中包含來自合併請求(Pull Requests)的參照。預設為False。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(詳見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
包含 Hub 上儲存庫所有分支與標籤相關資訊的物件。
取得給定儲存庫的參照清單(包括標籤與分支)。
範例
>>> 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
< 原始碼 >( repo_id: str path_in_repo: str | None = None recursive: bool = False expand: bool = False revision: str | None = None repo_type: str | None = None token: str | bool | None = None ) → Iterable[Union[RepoFile, RepoFolder]]
參數
- repo_id (
str) — 命名空間(使用者或組織名稱)加上儲存庫名稱,並以/分隔。 - path_in_repo (
str, 選填) — 儲存庫中樹狀結構(資料夾)的相對路徑,例如:"checkpoints/1fec34a/results"。預設為儲存庫的根樹狀結構(資料夾)。 - recursive (
bool, 選填, 預設為False) — 是否遞迴地列出樹狀結構中的檔案與資料夾。 - expand (
bool, 選填, 預設為False) — 是否擷取有關樹狀結構中檔案與資料夾的更多資訊(例如最後一次提交記錄以及檔案的安全掃描結果)。此操作對伺服器而言成本較高,因此每頁僅傳回 50 個結果(而非 1000 個)。由於huggingface_hub已實作分頁機制,這對您而言是透明的,僅需注意取得結果所需的時間。 - revision (
str, 選填) — 用以取得樹狀結構的儲存庫版本。預設為"main"分支。 - repo_type (
str, 選填) — 用以取得樹狀結構的儲存庫類型 ("model","dataset","space"或"kernel")。預設為"model"。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(詳見 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 — 如果在儲存庫中找不到該版本(錯誤 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
< 原始碼 >( timeout: int | None = None namespace: str | None = None token: bool | str | None = None )
參數
- timeout (
float, 選填) — 是否為 Hub 的請求設定逾時時間。 - namespace (
str, 選填) — 列出作業時所在的命名空間。預設為當前使用者的命名空間。 - token (
Union[bool, str, None], 選填) — 有效的使用者存取權杖。若未提供,則會使用本地儲存的權杖,這是推薦的驗證方式。若要停用驗證,請設為False。詳見:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
列出 Hugging Face 基礎架構上已排程的運算作業 (Jobs)。
list_spaces
< 原始碼 >( filter: str | Iterable[str] | None = None author: str | None = None search: str | None = None datasets: str | Iterable[str] | None = None models: str | Iterable[str] | None = None linked: bool = False sort: SpaceSort_T | None = None limit: int | None = None expand: list[ExpandSpaceProperty_T] | None = None full: bool | None = None token: bool | str | None = None ) → Iterable[SpaceInfo]
參數
- filter (
str或Iterable, 選填) — 用於識別 Hub 上 Spaces 的標籤字串或標籤清單。 - author (
str, 選填) — 用於識別所回傳 Spaces 作者的字串。 - search (
str, 選填) — 將包含在回傳 Spaces 中的搜尋字串。 - datasets (
str或Iterable, 選填) — 是否回傳使用特定資料集的 Spaces。特定資料集的名稱可作為字串傳入。 - models (
str或Iterable, 選填) — 是否回傳使用特定模型的 Spaces。特定模型的名稱可作為字串傳入。 - linked (
bool, 選填) — 是否回傳使用模型或資料集的 Spaces。 - sort (
SpaceSort_T, 選填) — 用於排序結果 Spaces 的鍵值。可能的值包括 “created_at”、“last_modified”、“likes” 和 “trending_score”。 - limit (
int, 選填) — 擷取 Spaces 的數量限制。將此選項保留為None將會擷取所有 Spaces。 - expand (
list[ExpandSpaceProperty_T], 選填) — 於回應中要回傳的屬性清單。使用時,僅會回傳清單中的屬性。若已傳入full參數,則無法使用此參數。可能的值包括"author","cardData","datasets","disabled","lastModified","createdAt","likes","models","private","runtime","sdk","siblings","sha","subdomain","tags","trendingScore","usedStorage"以及"resourceGroup"。 - full (
bool, 選用) — 是否要獲取所有 Spaces 資料,包含last_modified、siblings與card_data欄位。 - token (
bool或str, 選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(請見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Iterable[SpaceInfo]
huggingface_hub.hf_api.SpaceInfo 物件的可迭代集合。
根據篩選條件,列出託管於 Huggingface Hub 上的 Spaces。
list_spaces_hardware
< 原始碼 >( token: bool | str | None = None ) → list[JobHardware]
返回
list[JobHardware]
可用硬體配置的列表。
列出 Spaces 可用的硬體選項。
list_user_followers
< 原始碼 >( username: str token: bool | str | None = None ) → Iterable[User]
參數
- username (
str) — 要取得追蹤者列表的使用者名稱。 - token (
bool或str, 選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(請見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Iterable[User]
包含該使用者追蹤者的 User 物件列表。
引發
HfHubHTTPError
HfHubHTTPError— 若該使用者在 Hub 上不存在,則回傳 HTTP 404。
取得 Hub 上某使用者的追蹤者列表。
list_user_following
< 原始碼 >( username: str token: bool | str | None = None ) → Iterable[User]
參數
- username (
str) — 要取得該使用者所追蹤對象的使用者名稱。 - token (
bool或str, 選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(請見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Iterable[User]
包含該使用者所追蹤對象的 User 物件列表。
引發
HfHubHTTPError
HfHubHTTPError— 若該使用者在 Hub 上不存在,則回傳 HTTP 404。
取得 Hub 上某使用者所追蹤對象的列表。
list_webhooks
< 原始碼 >( token: bool | str | None = None ) → list[WebhookInfo]
參數
- token (
bool或str, 選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(請見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
list[WebhookInfo]
Webhook 資訊物件列表。
列出所有已設定的 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
< 原始碼 >( repo_id: str discussion_num: int token: bool | str | None = None comment: str | None = None repo_type: str | None = None ) → DiscussionStatusChange
參數
- repo_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,中間以/分隔。 - discussion_num (
int) — 討論 (Discussion) 或合併請求 (Pull Request) 的編號。必須為嚴格的正整數。 - comment (
str, 選用) — 狀態變更時發布的選用註解。 - repo_type (
str, 選用) — 若上傳至 dataset 或 space,請設為"dataset"或"space";若上傳至 model,請設為None或"model"。預設為None。 - token (
bool或str, 選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(請見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
狀態變更事件
合併合併請求 (Pull Request)。
可能會引發下列錯誤
HTTPError如果 HuggingFace API 回傳錯誤ValueError如果某些參數值無效- RepositoryNotFoundError 如果找不到要下載的儲存庫。這可能是因為它不存在,或者它被設為
private(私人)且您沒有存取權限。
model_info
< 原始碼 >( repo_id: str revision: str | None = None timeout: float | None = None securityStatus: bool | None = None files_metadata: bool = False expand: list[ExpandModelProperty_T] | None = None token: bool | str | None = None ) → huggingface_hub.hf_api.ModelInfo
參數
- repo_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,中間以/分隔。 - revision (
str, 選用) — 要取得資訊的模型儲存庫修訂版本。 - timeout (
float, 選用) — 是否要為 Hub 請求設定逾時時間。 - securityStatus (
bool, 選用) — 是否同時從模型儲存庫擷取安全性狀態。安全性狀態將於security_repo_status欄位中回傳。 - files_metadata (
bool, 選用) — 是否要擷取儲存庫中檔案的元資料(大小、LFS 元資料等)。預設為False。 - expand (
list[ExpandModelProperty_T], 選用) — 指定要在回應中回傳的屬性列表。使用此參數時,僅會回傳清單中的屬性。若已傳入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 (
bool或str, 選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(請見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
模型儲存庫資訊。
取得 huggingface.co 上特定模型的資訊。
若傳入有效的權杖或已登入,模型可以是私有的。
可能會引發下列錯誤
- RepositoryNotFoundError 如果找不到要下載的儲存庫。這可能是因為它不存在,或者它被設為
private(私人)且您沒有存取權限。- RevisionNotFoundError 如果找不到要下載的版本。
move_bucket
< 原始碼 >( from_id: str to_id: str token: bool | str | None = None )
參數
- from_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,中間以/分隔。原始儲存庫識別碼(例如"username/my-bucket")。 - to_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,中間以/分隔。最終儲存庫識別碼(例如"username/new-bucket-name"或"organization/my-bucket")。 - token (
bool或str, 選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(請見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
引發
BucketNotFoundError
BucketNotFoundError— 若找不到來源儲存庫。這可能是因為它不存在,或者它被設為private且您沒有存取權限。
將儲存庫從“namespace1/repo_name1”移至“namespace2/repo_name2”
請注意,這有一些限制。關於轉移儲存庫的詳細資訊,請參閱 https://huggingface.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo。
move_repo
< 原始碼 >( from_id: str to_id: str repo_type: str | None = None token: str | bool | None = None )
參數
- from_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,中間以/分隔。原始儲存庫識別碼。 - to_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,中間以/分隔。最終儲存庫識別碼。 - repo_type (
str, 選用) — 若上傳至 dataset 或 space,請設為"dataset"或"space";若上傳至 model,請設為None或"model"。預設為None。 - token (
bool或str, 選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(請見 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: str | None = None revision: str | None = None token: bool | str | None = None ) → SafetensorsFileMetadata
參數
- repo_id (
str) — 使用者或組織名稱與儲存庫名稱,中間以/分隔。 - filename (
str) — 儲存庫中的檔案名稱。 - repo_type (
str, 選用) — 若檔案位於 dataset 或 space 中,請設為"dataset"或"space";若位於 model 中,請設為None或"model"。預設為None。 - revision (
str, 選用) — 要擷取檔案的 git 修訂版本。可以是分支名稱、標籤或 commit hash。預設為"main"分支的開頭。 - token (
bool或str, 選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(請見 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: str | None = None token: bool | str | None = None ) → InferenceEndpoint
參數
- name (
str) — 要暫停的 Inference Endpoint 名稱。 - namespace (
str, 選用) — Inference Endpoint 所在的命名空間。預設為目前使用者。 - token (
bool或str, 選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(請見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
關於已暫停之 Inference Endpoint 的資訊。
暫停 Inference Endpoint。
已暫停的 Inference Endpoint 將不會被收費。您可以隨時使用 resume_inference_endpoint() 恢復它。這與使用 scale_to_zero_inference_endpoint() 將 Inference Endpoint 縮放至零不同,後者在接收到請求時會自動重啟。
為方便起見,您也可以使用 pause_inference_endpoint() 來暫停 Inference Endpoint。
pause_space
< 原始碼 >( repo_id: str token: bool | str | None = None ) → SpaceRuntime
參數
- repo_id (
str) — 要暫停的 Space ID。例如:"Salesforce/BLIP2"。 - token (
bool或str, 選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方式(請見 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
關於您 Space 的執行階段資訊,包含 stage=PAUSED 與請求的硬體。
- RepositoryNotFoundError — 若找不到您的 Space(錯誤 404)。很可能是 repo_id 錯誤,或是您的 Space 為私人狀態但您未經驗證。
- HfHubHTTPError — 403 Forbidden:只有 Space 的擁有者才能將其暫停。如果您想管理不屬於您的 Space,請透過開啟討論 (Discussion) 來詢問擁有者,或複製該 Space。
- BadRequestError — 若您的 Space 是靜態 Space。靜態 Space 始終在執行中且不計費。若您想隱藏靜態 Space,可以將其設為私人。
暫停您的 Space。
已暫停的 Space 會停止執行,直到擁有者手動重啟為止。這與免費 Space 在 48 小時不活動後進入的睡眠狀態不同。暫停期間不會向您的帳戶收費,無論您選擇何種硬體皆然。若要重啟您的 Space,請使用 restart_space() 並前往您的 Space 設定頁面。
如需更多詳細資訊,請造訪 說明文件。
permanently_delete_lfs_files
< 原始碼 >( repo_id: str lfs_files: Iterable[LFSFileInfo] rewrite_history: bool = True repo_type: str | None = None token: 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)列出,請設定為"dataset"或"space";若要從模型(model)列出,則設為None或"model"。預設值為None。 - token (
bool或str,選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
從 Hub 上的儲存庫中永久刪除 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
< 原始碼 >( repo_id: str additions: Iterable[CommitOperationAdd] token: str | bool | None = None repo_type: str | None = None revision: str | None = None create_pr: bool | None = None num_threads: int = 5 free_memory: bool = True gitignore_content: str | None = None )
參數
- repo_id (
str) — 您將要在其中提交檔案的儲存庫,例如:"username/custom_transformers"。 - operations (
CommitOperationAdd的Iterable) — 要上傳的檔案清單。警告:此清單中的物件將會被修改,以包含與上傳相關的資訊。請勿將相同的物件用於多次提交。 - 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,為未來的提交做準備。
如果您是在運行時產生要上傳的檔案,並且不想在一次性上傳前將它們儲存在記憶體中,此方法非常實用。
這是一種進階用戶方法。在進行一般提交時,您不需要直接呼叫它。請改為直接使用 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")read_paper
< 原始碼 >( id: str ) → str
取得 Hub 上論文頁面的 Markdown 內容。
reject_access_request
< 原始碼 >( repo_id: str user: str repo_type: str | None = None rejection_reason: str | None token: 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— 若儲存庫未設為閘控 (gated),則回應 HTTP 400。HfHubHTTPError— 若您對儲存庫僅有唯讀權限,則回應 HTTP 403。如果您在該儲存庫所屬的組織中沒有write或admin角色,或如果您傳入的是read權杖,就會發生此情況。HfHubHTTPError— 若 Hub 上不存在該使用者,則回應 HTTP 404。HfHubHTTPError— 若找不到該使用者的存取請求,則回應 HTTP 404。HfHubHTTPError— 如果使用者存取請求已在拒絕清單中,則會出現 HTTP 404 錯誤。
拒絕使用者對特定門控(gated)儲存庫的存取請求。
被拒絕的請求將進入拒絕清單。使用者無法下載該儲存庫的任何檔案。被拒絕的請求可以隨時使用 accept_access_request() 和 cancel_access_request() 進行接受或取消。取消的請求將回到待處理清單,而接受的請求則會進入已接受清單。
關於閘控儲存庫的更多資訊,請參閱 https://huggingface.co/docs/hub/models-gated。
rename_discussion
< 原始碼 >( repo_id: str discussion_num: int new_title: str token: bool | str | None = None repo_type: str | None = None ) → DiscussionTitleChange
參數
- repo_id (
str) — 命名空間(使用者或組織)與以/分隔的儲存庫名稱。 - discussion_num (
int) — 討論或合併請求的編號。必須是嚴格為正的整數。 - new_title (
str) — 討論的新標題。 - repo_type (
str,選用) — 若要上傳至資料集或空間,請設定為"dataset"或"space";若要上傳至模型,則設為None或"model"。預設值為None。 - token (
bool或str,選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的驗證方法(請參閱 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
< 原始碼 >( repo_id: str repo_type: str | None = None token: str | bool | None = None )
參數
- repo_id (
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 上。
repo_info
< 原始碼 >( repo_id: str revision: str | None = None repo_type: str | None = None timeout: float | None = None files_metadata: bool = False expand: ExpandModelProperty_T | ExpandDatasetProperty_T | ExpandSpaceProperty_T | None = None token: bool | str | None = None ) → Union[SpaceInfo, DatasetInfo, ModelInfo]
參數
- repo_id (
str) — 命名空間(使用者或組織)與以/分隔的儲存庫名稱。 - revision (
str,選用) — 要從中取得資訊的儲存庫修訂版本。 - repo_type (
str,選用) — 若要從資料集或空間取得儲存庫資訊,請設定為"dataset"或"space";若要從模型取得,則設為None或"model"。預設值為None。 - timeout (
float,選用) — 是否為 Hub 的請求設定逾時時間。 - expand (
ExpandModelProperty_T或ExpandDatasetProperty_T或ExpandSpaceProperty_T,選用) — 要在回應中回傳的屬性清單。使用時,將僅回傳清單中的屬性。如果傳入了files_metadata,則無法使用此參數。如需可用屬性的詳細清單,請查看 model_info()、dataset_info() 或 space_info()。 - files_metadata (
bool,選用) — 是否擷取儲存庫中檔案的中繼資料(大小、LFS 中繼資料等)。預設為False。 - token (
bool或str,選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的驗證方法(請參閱 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
< 原始碼 >( repo_id: str hardware: SpaceHardware token: bool | str | None = None sleep_time: int | None = None ) → SpaceRuntime
參數
- repo_id (
str) — 要更新的儲存庫 ID。範例:"bigcode/in-the-stack"。 - hardware (
str或 SpaceHardware) — 用於執行空間(Space)的硬體。範例:"t4-medium"。 - token (
bool或str,選用) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - sleep_time (
int,選用) — 在空間進入休眠前需等待的非活動秒數。如果您不希望空間進入休眠(升級硬體的預設行為),請設定為-1。對於免費硬體,您無法設定休眠時間(固定為 48 小時無活動即休眠)。詳情請參閱 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。
返回
有關 Space 的執行時間資訊,包含 Space 階段與硬體。
為空間請求新硬體。
您也可以在建立空間儲存庫時直接請求硬體!詳細資訊請參閱 create_repo()。
request_space_storage
< 原始碼 >( repo_id: str storage: SpaceStorage token: bool | str | None = None ) → SpaceRuntime
參數
- repo_id (
str) — 要更新的 Space 之 ID。範例:"open-llm-leaderboard/open_llm_leaderboard"。 - storage (
str或 SpaceStorage) — 儲存層級。可為 ‘small’、‘medium’ 或 ‘large’。 - token (
bool或str,選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的身份驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。
返回
有關 Space 的執行時間資訊,包含 Space 階段與硬體。
為 Space 請求永久儲存空間。
request_space_storage已棄用,將在 2.0 版本中移除。請改用 set_space_volumes()。
restart_space
< 原始碼 >( repo_id: str token: bool | str | None = None factory_reboot: bool = False ) → SpaceRuntime
參數
- repo_id (
str) — 要重新啟動的 Space 之 ID。範例:"Salesforce/BLIP2"。 - token (
bool或str,選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的身份驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。 - factory_reboot (
bool,選填) — 若為True,該 Space 將從頭開始重建,且不快取任何需求。
返回
關於您 Space 的執行階段資訊。
- RepositoryNotFoundError — 若找不到您的 Space(錯誤 404)。很可能是 repo_id 錯誤,或是您的 Space 為私人狀態但您未經驗證。
- HfHubHTTPError — 403 Forbidden:只有 Space 的擁有者可以重新啟動它。如果您想重新啟動不屬於您的 Space,請透過開啟 Discussion(討論)詢問擁有者,或複製該 Space。
- BadRequestError — 若您的 Space 是靜態 Space。靜態 Space 始終在執行中且不計費。若您想隱藏靜態 Space,可以將其設為私人。
重新啟動您的 Space。
若您已將 Space 設定為暫停(請參閱 pause_space()),這是以程式方式重新啟動它的唯一方法。您必須是該 Space 的擁有者才能重新啟動它。如果您使用的是升級後的硬體,Space 一旦重新啟動,系統將會向您的帳戶收費。無論 Space 當前狀態如何,您都可以觸發重新啟動。
如需更多詳細資訊,請造訪 說明文件。
resume_inference_endpoint
< 原始碼 >( name: str namespace: str | None = None running_ok: bool = True token: bool | str | None = None ) → InferenceEndpoint
參數
- name (
str) — 要恢復的 Inference Endpoint 名稱。 - namespace (
str,選填) — Inference Endpoint 所在的命名空間。預設為目前使用者。 - running_ok (
bool,選填) — 若為True,當 Inference Endpoint 已經在執行時,此方法將不會拋出錯誤。預設為True。 - token (
bool或str,選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的身份驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用身份驗證,請傳入False。
關於已恢復的 Inference Endpoint 之資訊。
恢復 Inference Endpoint。
為方便起見,您也可以使用 InferenceEndpoint.resume() 來恢復 Inference Endpoint。
resume_scheduled_job
< 原始碼 >( scheduled_job_id: str namespace: str | None = None token: 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: str | None = None token: str | bool | None = None )
參數
- repo_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,並以/分隔。 - revision (
str) — 要檢查的儲存庫版本(revision)。 - repo_type (
str,選填) — 若要從資料集(dataset)或 Space 取得儲存庫資訊,請設為"dataset"或"space";若從模型(model)取得資訊,則設為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: dict[str, Any] | None = None secrets: dict[str, Any] | None = None flavor: SpaceHardware | None = None timeout: int | float | str | None = None labels: dict[str, str] | None = None volumes: list[Volume] | None = None namespace: str | None = None token: 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],選填) — 定義該任務的環境變數。 - secrets (
dict[str, Any],選填) — 定義該任務的敏感環境變數(Secrets)。 - flavor (
str,選填) — 硬體類型(Flavor),如同 Hugging Face Spaces。請參閱 SpaceHardware 以取得可用值。預設為"cpu-basic"。 - timeout (
Union[int, float, str],選填) — 任務的最長持續時間:int/float 單位為 s(秒,預設)、m(分鐘)、h(小時)或 d(天)。範例:300或"5m"代表 5 分鐘。 - labels (
dict[str, str],選填) — 附加到任務上的標籤(鍵值對)。 - volumes (
list[Volume],選填) — 掛載至任務容器中的 Hugging Face Buckets 或儲存庫。每個 Volume 都是一個 Volume,包含type("bucket"、"model"、"dataset"或"space")、source(例如"username/my-bucket")以及mount_path(例如"/data")。 - namespace (
str,選填) — 建立任務的命名空間。預設為目前使用者的命名空間。 - token (
Union[bool, str, None],選填) — 有效的使用者存取權杖。若未提供,將使用本地儲存的權杖,這是推薦的身份驗證方式。設為False可停用身份驗證。請參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
在 Hugging Face 基礎架構上執行計算任務(Jobs)。
範例
執行您的第一個任務
>>> from huggingface_hub import run_job
>>> run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"])執行 GPU 任務
>>> from huggingface_hub import run_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()}")"]
>>> run_job(image=image, command=command, flavor="a10g-small")執行具有 Volume 的任務
>>> from huggingface_hub import Volume, run_job
>>> dataset_volume = Volume(type="dataset", source="HuggingFaceFW/fineweb", mount_path="/data")
>>> output_bucket_volume = Volume(type="bucket", source="username/my-bucket", mount_path="/output")
>>> image = "duckdb/duckdb"
>>> command = ["duckdb", "-c", "COPY (SELECT * FROM '/data/**/*.parquet' LIMIT 5) TO '/output/first-rows.parquet'"]
>>> run_job(image=image, command=command, volumes=[dataset_volume, output_bucket_volume])run_uv_job
< 原始碼 >( script: str script_args: list[str] | None = None dependencies: list[str] | None = None python: str | None = None image: str | None = None env: dict[str, Any] | None = None secrets: dict[str, Any] | None = None flavor: SpaceHardware | None = None timeout: int | float | str | None = None labels: dict[str, str] | None = None volumes: list[Volume] | None = None namespace: str | None = None token: bool | str | None = None )
參數
- script (
str) — UV 腳本的路徑或 URL,或是指令。 - script_args (
list[str],選填) — 傳遞給腳本或指令的參數。 - dependencies (
list[str],選填) — 執行 UV 腳本所需的相依套件。 - python (
str,選填) — 使用特定的 Python 版本。預設為 3.12。 - image (
str,選填,預設為 “ghcr.io/astral-sh/uv —python3.12-bookworm”):使用已安裝uv的自訂 Docker 映像。 - env (
dict[str, Any],選填) — 定義該任務的環境變數。 - secrets (
dict[str, Any],選填) — 定義該任務的敏感環境變數(Secrets)。 - flavor (
str,選填) — 硬體類型(Flavor),如同 Hugging Face Spaces。請參閱 SpaceHardware 以取得可用值。預設為"cpu-basic"。 - timeout (
Union[int, float, str],選填) — 任務的最長持續時間:int/float 單位為 s(秒,預設)、m(分鐘)、h(小時)或 d(天)。範例:300或"5m"代表 5 分鐘。 - labels (
dict[str, str],選填) — 附加到任務上的標籤(鍵值對)。 - volumes (
list[Volume],選填) — 掛載至任務容器中的 Hugging Face Buckets 或儲存庫。每個 Volume 都是一個 Volume,包含type("bucket"、"model"、"dataset"或"space")、source(例如"username/my-bucket")以及mount_path(例如"/data")。 - namespace (
str,選填) — 建立任務的命名空間。預設為目前使用者的命名空間。 - token
(Union[bool, str, None], 選填) — 有效的使用者存取權杖 (access token)。若未提供,將使用本機儲存的權杖,這是建議的驗證方式。設為False可停用驗證。參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
在 Hugging Face 基礎架構上執行 UV 指令碼作業。
範例
從網址執行腳本
>>> 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")執行本機腳本
>>> from huggingface_hub import run_uv_job
>>> script = "my_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")執行指令
>>> from huggingface_hub import run_uv_job
>>> script = "lighteval"
>>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"]
>>> run_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small")掛載儲存空間 (Volumes),例如在訓練期間儲存模型檢查點 (checkpoints)
>>> from huggingface_hub import Volume, run_uv_job
>>> script = "my_sft.py"
>>> script_args = ["--output_dir", "/training-outputs/training-v3-final", ...]
>>> checkpoints_bucket = Volume(type="bucket", source="username/my-bucket", mount_path="/training-outputs")
>>> run_uv_job(script, script_args=script_args, volumes=[checkpoints_bucket])scale_to_zero_inference_endpoint
< 原始碼 >( name: str namespace: str | None = None token: bool | str | None = None ) → InferenceEndpoint
參數
- name (
str) — 要擴展至零 (scale to zero) 的推論端點名稱。 - namespace (
str, 選填) — 推論端點所在的命名空間。預設為目前的使用者。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
關於已擴展至零的推論端點的資訊。
將推論端點擴展至零。
擴展至零的推論端點將不會被計費。當下次收到請求時,它將會恢復,並伴隨冷啟動延遲 (cold start delay)。這與使用 pause_inference_endpoint() 暫停推論端點不同,後者需要使用 resume_inference_endpoint() 手動恢復。
為方便起見,您也可以使用 InferenceEndpoint.scale_to_zero() 將推論端點擴展至零。
search_spaces
< 原始碼 >( query: str filter: str | Iterable[str] | None = None sdk: str | list[str] | None = None include_non_running: bool = False token: bool | str | None = None ) → Iterable[SpaceSearchResult]
參數
- query (
str) — 搜尋查詢字串。 - filter (
str或Iterable[str], 選填) — 用於篩選的字串標籤或標籤列表。 - sdk (
str或list[str], 選填) — 按 SDK 進行篩選(例如"gradio","docker","static")。 - include_non_running (
bool, 選填) — 是否將非運行中的 Spaces 包含在結果中。預設為False。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Iterable[SpaceSearchResult]
SpaceSearchResult 物件的可迭代集合。
使用語意搜尋在 Hub 上搜尋 Spaces。
此端點針對多字查詢使用語意搜尋(基於嵌入技術),並針對單字查詢使用全文搜尋。
set_space_sleep_time
< 原始碼 >( repo_id: str sleep_time: int token: bool | str | None = None ) → SpaceRuntime
參數
- repo_id (
str) — 要更新的儲存庫 ID。範例:"bigcode/in-the-stack"。 - sleep_time (
int, 選填) — 在 Space 進入睡眠前需等待的閒置秒數。若您不希望 Space 暫停,請設為-1(這是已升級硬體的預設行為)。對於免費硬體,您無法設定睡眠時間(值固定為 48 小時閒置)。更多詳細資訊請參閱 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
有關 Space 的執行時間資訊,包含 Space 階段與硬體。
為運行在升級版硬體上的 Space 設定自訂睡眠時間。
您的 Space 將在閒置 X 秒後進入睡眠。當 Space 處於「睡眠」模式時,您將不會被收費。若有新訪客造訪您的 Space,它會被「喚醒」。僅升級版硬體可以設定睡眠時間。欲了解更多關於睡眠階段的資訊,請參閱 https://huggingface.co/docs/hub/spaces-gpus#sleep-time。
您也可以在請求硬體時使用 request_space_hardware() 設定自訂睡眠時間。
set_space_volumes
< 原始碼 >( repo_id: str volumes: list[Volume] token: bool | str | None = None )
參數
- repo_id (
str) — 要更新的 Space ID。範例:"username/my-space"。 - volumes (
list[Volume]) — 要掛載的 Volume 物件列表。每個 volume 包含一個type("bucket","model","dataset"或"space")、一個source(儲存庫或 bucket ID)、一個mount_path(容器內的路徑),以及選填的revision、read_only和path欄位。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
引發
BadRequestError
BadRequestError— 若 Space 為靜態 Space(靜態 Space 不支援 volumes)。
為 Space 設定 volumes。
設定(或替換)Space 中掛載的 volumes 列表。每個 volume 允許 Space 的容器存取 Hub 資源(模型、資料集或儲存 bucket)。
範例
>>> from huggingface_hub import HfApi, Volume
>>> api = HfApi()
>>> api.set_space_volumes(
... "username/my-space",
... volumes=[
... Volume(type="model", source="username/my-model", mount_path="/models", read_only=True),
... Volume(type="bucket", source="username/my-bucket", mount_path="/data"),
... ],
... )snapshot_download
< 原始碼 >( repo_id: str repo_type: str | None = None revision: str | None = None cache_dir: str | Path | None = None local_dir: str | Path | None = None etag_timeout: float = 10 force_download: bool = False token: bool | str | None = None local_files_only: bool = False allow_patterns: list[str] | str | None = None ignore_patterns: list[str] | str | None = None max_workers: int = 8 tqdm_class: type[base_tqdm] | None = None dry_run: bool = False ) → str 或 DryRunFileInfo 列表
參數
- repo_id (
str) — 使用者名稱或組織名稱,以及儲存庫名稱,中間以/分隔。 - repo_type (
str, 選填) — 若從資料集或空間下載,請設為"dataset"或"space";若從模型下載,則設為None或"model"。預設為None。 - revision (
str, 選填) — 選填的 Git 修訂 ID,可以是分支名稱、標籤或提交雜湊值 (commit hash)。 - cache_dir (
str,Path, 選填) — 儲存快取檔案的資料夾路徑。 - local_dir (
str或Path, 選填) — 若提供此參數,下載的檔案將會放置在此目錄下。 - etag_timeout (
float, 選填, 預設為10) — 擷取 ETag 時,等待伺服器傳送資料的秒數,若超過此時間將放棄,此值會傳遞給httpx.request。 - force_download (
bool, 選填, 預設為False) — 是否即使檔案已存在於本機快取中,仍要重新下載。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - local_files_only (
bool, 選填, 預設為False) — 若為True,則避免下載檔案,若快取中有檔案則回傳本機路徑。 - allow_patterns (
list[str]或str, 選填) — 若提供此參數,則僅下載符合至少一種模式的檔案。 - ignore_patterns (
list[str]或str, 選填) — 若提供此參數,則不下載符合任何模式的檔案。 - max_workers (
int, 選填) — 並行下載檔案的執行緒數量(1 個執行緒 = 1 個檔案下載)。預設為 8。 - tqdm_class (
tqdm, 選填) — 若提供此參數,將覆寫進度條的預設行為。傳入的參數必須繼承自tqdm.auto.tqdm,或者至少模擬其行為。請注意,tqdm_class不會傳遞給單一檔案的下載進度。預設為自訂的 HF 進度條,可透過設定HF_HUB_DISABLE_PROGRESS_BARS環境變數來停用。 - dry_run (
bool, 選填, 預設為False) — 若為True,則進行試運行 (dry run) 而不實際下載檔案。會回傳一個包含資訊的 DryRunFileInfo 物件列表,說明將會下載哪些內容。
返回
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/ 資料夾來儲存與下載檔案相關的 metadata。雖然此機制不如主要的快取系統穩健,但它經過最佳化,適合定期提取儲存庫的最新版本。
另一種替代方案是複製 (clone) 儲存庫,但這需要安裝並正確設定 git 和 git-lfs。此外,使用 git 複製儲存庫時,無法篩選要下載哪些檔案。
space_info
< 原始碼 >( repo_id: str revision: str | None = None timeout: float | None = None files_metadata: bool = False expand: list[ExpandSpaceProperty_T] | None = None token: bool | str | None = None ) → SpaceInfo
參數
- repo_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,中間以/分隔。 - revision (
str, 選填) — 獲取資訊時的 Space 儲存庫修訂版本。 - timeout (
float, 選填) — 是否為 Hub 的請求設定逾時時間。 - files_metadata (
bool, 選填) — 是否擷取儲存庫中檔案的 metadata(大小、LFS metadata 等)。預設為False。 - expand (
list[ExpandSpaceProperty_T], 選填) — 在回應中要回傳的屬性列表。使用此參數時,將僅回傳列表中指定的屬性。若已傳入full,則無法使用此參數。可能的值包括"author","cardData","createdAt","datasets","disabled","lastModified","likes","models","private","runtime","sdk","siblings","sha","subdomain","tags","trendingScore","usedStorage"和"resourceGroup"。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
返回
Space 儲存庫資訊。
獲取 huggingface.co 上特定 Space 的資訊。
若您傳入有效的權杖,Space 可以是私有的。
可能會引發下列錯誤
- RepositoryNotFoundError 如果找不到要下載的儲存庫。這可能是因為它不存在,或者它被設為
private(私人)且您沒有存取權限。- RevisionNotFoundError 如果找不到要下載的版本。
super_squash_history
< 原始碼 >( repo_id: str branch: str | None = None commit_message: str | None = None repo_type: str | None = None token: str | bool | None = None )
參數
- repo_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,中間以/分隔。 - branch (
str, 選填) — 要壓縮的分支。預設為"main"分支的開頭。 - commit_message (
str, 選填) — 用於壓縮後提交 (squashed commit) 的提交訊息。 - repo_type (
str, 選填) — 若列出來自資料集或 Space 的提交,請設為"dataset"或"space";若從模型列出,則設為None或"model"。預設為None。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本機儲存的權杖,這是建議的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
- RepositoryNotFoundError — 如果找不到儲存庫(錯誤 404):repo_id/repo_type 錯誤、儲存庫為私人且未經驗證,或是儲存庫不存在。
- RevisionNotFoundError — 若找不到要壓縮的分支。
- BadRequestError — 若分支參考無效。您無法壓縮標籤 (tags) 的歷史紀錄。
壓縮 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
< 原始碼 >( scheduled_job_id: str namespace: str | None = None token: bool | str | None = None )
參數
- scheduled_job_id (
str) — 排程任務的 ID。 - namespace (
str, 選填) — 排程任務(scheduled Job)所在的命名空間。預設為當前使用者的命名空間。 - token
(Union[bool, str, None], 選填) — 有效的使用者存取權杖(access token)。若未提供,將使用本地儲存的權杖,這是推薦的驗證方式。設為False可停用驗證。參考:https://huggingface.co/docs/huggingface_hub/quick-start#authentication。
暫停(pause)Hugging Face 基礎設施上的排程運算任務。
sync_bucket
< 原始碼 >( source: str | None = None dest: str | None = None delete: bool = False ignore_times: bool = False ignore_sizes: bool = False existing: bool = False ignore_existing: bool = False include: list[str] | None = None exclude: list[str] | None = None filter_from: str | None = None plan: str | None = None apply: str | None = None dry_run: bool = False verbose: bool = False quiet: bool = False token: bool | str | None = None ) → [SyncPlan]
參數
- source (str, 選填) — 來源路徑:本地目錄或
hf://buckets/namespace/bucket_name(/prefix)。除非使用apply,否則此為必填。 - dest (str, 選填) — 目標路徑:本地目錄或
hf://buckets/namespace/bucket_name(/prefix)。除非使用apply,否則此為必填。 - delete (bool, 選填, 預設值為 False) — 刪除來源中不存在的目標檔案。
- ignore_times (bool, 選填, 預設值為 False) — 僅根據檔案大小略過檔案,忽略修改時間。
- ignore_sizes (bool, 選填, 預設值為 False) — 僅根據修改時間略過檔案,忽略檔案大小。
- existing (bool, 選填, 預設值為 False) — 略過在接收端建立新檔案(僅更新現有檔案)。
- ignore_existing (bool, 選填, 預設值為 False) — 略過更新接收端已存在的檔案(僅建立新檔案)。
- include (list[str], 選填) — 包含符合樣式的檔案(fnmatch 風格)。
- exclude (list[str], 選填) — 排除符合樣式的檔案(fnmatch 風格)。
- filter_from (str, 選填) — 包含 include/exclude 規則的過濾檔案路徑。
- plan (str, 選填) — 將同步計畫儲存至此 JSONL 檔案,而非直接執行。
- apply (str, 選填) — 套用先前儲存的計畫檔案。設定此項時,不需要
source和dest。 - dry_run (bool, 選填, 預設值為 False) — 將同步計畫以 JSONL 格式列印至標準輸出(stdout)而不執行。
- verbose (bool, 選填, 預設值為 False) — 顯示詳細的各檔案操作內容。
- quiet (bool, 選填, 預設值為 False) — 隱藏所有輸出與進度條。
- token (Union[bool, str, None], 選填) — 有效的使用者存取權杖。若未提供,將使用本地儲存的權杖。
返回
[SyncPlan]
計算出(或載入的)同步計畫。
在本地目錄與儲存貯體(bucket)之間同步檔案。
這等同於 hf buckets sync CLI 指令。source 或 dest 必須有一個為儲存貯體路徑(hf://buckets/...),另一個必須為本地目錄路徑。
範例
>>> from huggingface_hub import HfApi
>>> api = HfApi()
# Upload local directory to bucket
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket")
# Download bucket to local directory
>>> api.sync_bucket("hf://buckets/username/my-bucket", "./data")
# Sync with delete and filtering
>>> api.sync_bucket(
... "./data",
... "hf://buckets/username/my-bucket",
... delete=True,
... include=["*.safetensors"],
... )
# Dry run: preview what would be synced
>>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True)
>>> plan.summary()
{'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}
# Save plan for review, then apply
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl")
>>> api.sync_bucket(apply="sync-plan.jsonl")unlike
< 原始碼 >( repo_id: str token: bool | str | None = None repo_type: str | None = None )
參數
- repo_id (
str) — 要取消按讚的儲存庫。範例:"user/my-cool-model"。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - repo_type (
str, 選填) — 如果要取消按讚的是資料集或 Space,請設為"dataset"或"space";如果要取消按讚的是模型,請設為None或"model"。預設值為None。
- RepositoryNotFoundError — 如果找不到儲存庫(錯誤 404):repo_id/repo_type 錯誤、儲存庫為私人且未經驗證,或是儲存庫不存在。
在 Hub 上取消對特定儲存庫的按讚(例如從最愛列表中移除)。
為防止濫用,無法透過指令稿(script)對儲存庫進行 like(按讚)。
另請參閱 list_liked_repos()。
update_collection_item
< 原始碼 >( collection_slug: str item_object_id: str note: str | None = None position: int | None = None token: bool | str | None = None )
參數
- collection_slug (
str) — 要更新的選集(collection)slug。範例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。 - item_object_id (
str) — 選集中項目的 ID。這不是 Hub 上項目的 ID(repo_id 或論文 ID),必須從 CollectionItem 物件中獲取。範例:collection.items[0].item_object_id。 - note (
str, 選填) — 附加在選集項目中的備註。備註長度限制為 500 個字元。 - position (
int, 選填) — 項目在選集中的新位置。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方法(請參閱 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
< 原始碼 >( collection_slug: str title: str | None = None description: str | None = None position: int | None = None private: bool | None = None theme: str | None = None token: bool | str | None = None )
參數
- collection_slug (
str) — 要更新的選集 slug。範例:"TheBloke/recent-models-64f9a55bb3115b4f513ec026"。 - title (
str) — 要更新的選集標題。 - description (
str, 選填) — 要更新的選集描述。 - position (
int, 選填) — 選集在使用者選集列表中的新位置。 - private (
bool, 選填) — 選集是否應為私人狀態。 - theme (
str, 選填) — Hub 上選集的主題。 - token (
bool或str, 選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是推薦的驗證方法(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
更新 Hub 上選集的詮釋資料(metadata)。
所有參數皆為選填。僅有提供的詮釋資料會被更新。
回傳: 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
< 原始碼 >( name: str accelerator: str | None = None instance_size: str | None = None instance_type: str | None = None min_replica: int | None = None max_replica: int | None = None scale_to_zero_timeout: int | None = None scaling_metric: InferenceEndpointScalingMetric | None = None scaling_threshold: float | None = None repository: str | None = None framework: str | None = None revision: str | None = None task: str | None = None custom_image: dict | None = None env: dict[str, str] | None = None secrets: dict[str, str] | None = None domain: str | None = None path: str | None = None cache_http_responses: bool | None = None tags: list[str] | None = None namespace: str | None = None token: bool | str | None = None ) → InferenceEndpoint
參數
- name (
str) — 要更新的推論端點名稱。 - accelerator (
str, 選填) — 用於推論的硬體加速器(例如"cpu")。 - instance_size (
str, 選填) — 用於託管模型的執行個體(instance)大小或類型(例如"x4")。 - instance_type (
str, 選填) — 部署推論端點的雲端執行個體類型(例如"intel-icl")。 - min_replica (
int, 選填) — 推論端點保持運行的最小複本(實例)數量。 - max_replica (
int, 選填) — 推論端點可擴展到的最大複本(實例)數量。 - scale_to_zero_timeout (
int, 選填) — 端點閒置多久(以分鐘為單位)後將縮放至零。 - scaling_metric (
str或InferenceEndpointScalingMetric, 選填) — 用於擴展的指標參考。提供時,可為 “pendingRequests” 或 “hardwareUsage”。預設為 None。 - scaling_threshold (
float, 選填) — 用於觸發擴展的指標閾值。若未提供擴展指標,則忽略此項。預設為 None。 - repository (
str, 選填) — 與推論端點關聯的模型儲存庫名稱(例如"gpt2")。 - framework (
str, 選填) — 模型使用的機器學習框架(例如"custom")。 - revision (
str, 選填) — 部署於推論端點的特定模型版本(例如"6c0e6080953db56375760c0471a8c5f2929baf11")。 - task (
str, 選填) — 模型部署的任務類型(例如"text-classification")。 - custom_image (
dict, 選填) — 用於推論端點的自訂 Docker 映像檔。如果您想在text-generation-inference(TGI) 框架上部署推論端點,此選項非常有用(請參閱範例)。 - env (
dict[str, str], 選填) — 要注入容器環境中的非機密環境變數。 - secrets (
dict[str, str], 選填) — 要注入容器環境中的機密數值。 - domain (
str, 選填) — 推論端點部署的自訂網域。若已設定,推論端點將可透過此網域存取(例如"my-new-domain.cool-website.woof")。 - path (
str, 選填) — 部署模型的自訂路徑,應以/開頭(例如"/models/google-bert/bert-base-uncased")。 - cache_http_responses (
bool, 選填) — 是否快取來自推論端點的 HTTP 回應。 - tags (
list[str], 選填) — 與推論端點關聯的標籤列表。 - namespace (
str, 選填) — 推論端點要更新所在的命名空間。預設為當前使用者的命名空間。 - token (
bool或str,選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。
有關更新後的 Inference Endpoint 的資訊。
更新推理端點 (Inference Endpoint)。
此方法允許更新運算配置、已部署的模型、路由,或上述項目的任意組合。所有參數皆為選填,但至少需提供一個。
為了方便起見,您也可以使用 InferenceEndpoint.update() 來更新推理端點。
update_repo_settings
< 原始碼 >( repo_id: str gated: Literal['auto', 'manual', False] | None = None private: bool | None = None visibility: RepoVisibility_T | None = None token: str | bool | None = None repo_type: str | None = None )
參數
- repo_id (
str) — 命名空間(使用者或組織)與儲存庫名稱,中間以 / 分隔。 - gated (
Literal["auto", "manual", False],選填) — 儲存庫的存取門控狀態。若設為None(預設),將不會更新儲存庫的gated設定。- “auto”:儲存庫設有存取門控,存取請求將根據預設準則自動核准或拒絕。
- “manual”:儲存庫設有存取門控,存取請求需要人工核准。
- False : 儲存庫未設存取門控,任何人皆可存取。
- private (
bool,選填) — 儲存庫是否應為私有。不可與visibility同時傳入。 - visibility (
Literal["public", "private", "protected"],選填) — 儲存庫的可見度。可為"public"或"private",Spaces 可選"protected"。 - token (
Union[str, bool, None],選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的驗證方式(請參閱 https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。若要停用驗證,請傳入False。 - repo_type (
str,選填) — 要更新設定的儲存庫類型 ("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
< 原始碼 >( webhook_id: str url: str | None = None watched: list[dict | WebhookWatchedItem] | None = None domains: list[constants.WEBHOOK_DOMAIN_T] | None = None secret: str | None = None token: bool | str | None = None ) → WebhookInfo
參數
- webhook_id (
str) — 待更新 Webhook 的唯一識別碼。 - url (
str,選填) — 載荷 (payload) 將傳送到的 URL。 - watched (
list[WebhookWatchedItem],選填) — 要監控的項目清單。可以是使用者、組織、模型、資料集或空間。詳情請參考 WebhookWatchedItem。被監控項目也可以一般的字典形式提供。 - domains (
list[Literal["repo", "discussion"]],選填) — 要監控的領域。可包含 “repo”、“discussion” 或兩者。 - secret (
str,選填) — 用於簽署載荷的密鑰,提供額外的安全性。 - token (
bool或str,選填) — 有效的使用者存取權杖(字串)。預設為本地儲存的權杖,這是建議的驗證方式(請參閱 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
< 原始碼 >( path_or_fileobj: str | Path | bytes | BinaryIO path_in_repo: str repo_id: str token: str | bool | None = None repo_type: str | None = None revision: str | None = None commit_message: str | None = None commit_description: str | None = None create_pr: bool | None = None parent_commit: str | None = None run_as_future: bool = False _hot_reload: bool | None = None ) → CommitInfo 或 Future
參數
- path_or_fileobj (
str,Path,bytes或IO) — 本地機器上的檔案路徑,或二進位資料串流 / 檔案物件 / 緩衝區。 - 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,選填) — 是否建立一個包含該提交的 Pull Request。預設為False。若未設定revision,則會針對"main"分支開啟 PR。若已設定revision且為分支名稱,則會針對該分支開啟 PR。若已設定revision但非分支名稱(例如提交的 oid),伺服器將會回傳RevisionNotFoundError。 - parent_commit (
str,選填) — 父提交的 OID / SHA,為十六進位字串。也支援簡寫(前 7 個字元)。若已指定且create_pr為False,當revision未指向parent_commit時,提交將會失敗。若已指定且create_pr為True,將會從parent_commit建立 pull request。指定parent_commit可確保在提交變更前儲存庫未被變更,這在儲存庫被同時更新/提交時特別有用。 - run_as_future (
bool,選填) — 是否在背景執行此方法。背景作業會循序執行,不會阻塞主執行緒。傳入run_as_future=True將會回傳一個 Future 物件。預設為False。
返回
CommitInfo 或 Future
包含新建立 commit 相關資訊(commit 雜湊、commit url、pr url、commit 訊息等)的 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
< 原始碼 >( repo_id: str folder_path: str | Path path_in_repo: str | None = None commit_message: str | None = None commit_description: str | None = None token: str | bool | None = None repo_type: str | None = None revision: str | None = None create_pr: bool | None = None parent_commit: str | None = None allow_patterns: list[str] | str | None = None ignore_patterns: list[str] | str | None = None delete_patterns: list[str] | str | None = 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,選填) — 是否建立一個包含該提交的 Pull Request。預設為False。若未設定revision,則會針對"main"分支開啟 PR。若已設定revision且為分支名稱,則會針對該分支開啟 PR。若已設定revision但非分支名稱(例如提交的 oid),伺服器將會回傳RevisionNotFoundError。 - parent_commit (
str,選填) — 父提交的 OID / SHA,為十六進位字串。也支援簡寫(前 7 個字元)。若已指定且create_pr為False,當revision未指向parent_commit時,提交將會失敗。若已指定且create_pr為True,將會從parent_commit建立 pull request。指定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 雜湊、commit url、pr url、commit 訊息等)的 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
< 原始碼 >( repo_id: str folder_path: str | Path repo_type: str revision: str | None = None private: bool | None = None allow_patterns: list[str] | str | None = None ignore_patterns: list[str] | str | None = None num_workers: int | None = 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,選填) — 要提交的分支。若未提供,將使用main分支。 - private (
bool,optional) — 儲存庫是否應為私有。若為None(預設值),則除非該組織的預設設定為私有,否則儲存庫將設為公開。 - allow_patterns (
list[str]或str, optional) — 若提供此參數,則僅上傳符合至少一個模式的檔案。 - ignore_patterns (
list[str]或str, optional) — 若提供此參數,則不上傳任何符合這些模式的檔案。 - num_workers (
int, optional) — 要啟動的 worker 數量。預設為 CPU 核心數的一半(最少為 1)。若您的機器允許,增加 worker 數量可能會加快處理速度。然而,在連線速度較慢的機器上,建議減少 worker 數量以確保更好的可續傳性。事實上,若處理程序中斷,已部分上傳的檔案必須重新完全上傳。 - print_report (
bool, optional) — 是否列印上傳進度報告。預設為 True。報告會每 X 秒(預設為 60)輸出至sys.stdout並覆蓋先前的報告。 - print_report_every (
int, optional) — 列印報告的頻率。預設為 60 秒。
以最穩健的方式將大型資料夾上傳至 Hub。
啟動多個 worker 以最佳化方式上傳檔案。在提交至儲存庫前,檔案必須經過雜湊運算(hashing),若為 LFS 檔案則需先行預上傳(pre-uploaded)。Worker 會針對資料夾中的每個檔案執行這些任務。在每個步驟中,有關上傳過程的一些中繼資料會儲存在資料夾內的 .cache/.huggingface/ 中,以便在程序中斷時能繼續執行。整個過程可能會產生多次提交。
幾點注意事項
- 儲存庫限制仍然適用: https://huggingface.co/docs/hub/repositories-recommendations
- 請勿同時啟動多個平行程序。
- 您可以隨時中斷並恢復處理程序。
- 請勿將同一個資料夾上傳至多個儲存庫。若您有此需求,必須先刪除本機的
.cache/.huggingface/資料夾。
雖然
upload_large_folder在上傳大型資料夾時更為穩健,但在功能上比 upload_folder() 更受限。在實務上:
- 您無法設定自訂的
path_in_repo。若您想要上傳至子資料夾,需要在本機建立正確的結構。- 您無法設定自訂的
commit_message和commit_description,因為系統會建立多個提交。- 您無法在上傳期間從儲存庫中刪除檔案。請先進行單獨的刪除提交。
- 您無法直接建立 PR。請先(透過 UI 或使用 create_pull_request())建立 PR,然後透過傳遞
revision來提交至該 PR。
技術細節
upload_large_folder 的處理流程如下:
- (檢查參數並進行設定。)
- 若儲存庫不存在則建立之。
- 列出要上傳的本機檔案。
- 執行驗證檢查,若可能超過儲存庫限制則顯示警告。
- 若檔案總數超過 10 萬個(建議上限),則發出警告。
- 若任何資料夾包含超過 1 萬個檔案(建議上限),則發出警告。
- 若有檔案大於 20GB(建議)或 50GB(硬性限制),則發出警告。
- 啟動 worker。Worker 可執行以下任務:
- 檔案雜湊運算。
- 獲取檔案清單的上傳模式(一般或 LFS)。
- 預上傳 LFS 檔案。
- 提交一批檔案。一旦 worker 完成一項任務,它將根據優先權清單(見下文)進入下一項任務,直到所有檔案皆已上傳並提交。
- 當 worker 運作時,定期將報告輸出至 sys.stdout。
優先順序
- 若距離上次提交嘗試已超過 5 分鐘(且至少有 1 個檔案),則提交。
- 若至少有 150 個檔案準備好提交,則提交。
- 若至少有 10 個檔案已完成雜湊運算,則獲取上傳模式。
- 若至少有 1 個檔案且沒有 worker 正在預上傳,則預上傳 LFS 檔案。
- 若至少有 1 個檔案且沒有 worker 正在執行雜湊,則進行檔案雜湊。
- 若至少有 1 個檔案且沒有 worker 正在獲取上傳模式,則獲取上傳模式。
- 若至少有 1 個檔案,則預上傳 LFS 檔案。
- 若至少有 1 個檔案待雜湊,則進行檔案雜湊。
- 若至少有 1 個檔案待獲取上傳模式,則獲取上傳模式。
- 若至少有 1 個檔案待提交且距離上次提交嘗試已過 1 分鐘,則提交。
- 若至少有 1 個檔案待提交且所有其他佇列皆為空,則提交。
特殊規則
- 每次只能有一個 worker 進行提交。
- 若沒有可用的任務,worker 會等待 10 秒後再重新檢查。
verify_repo_checksums
< 原始碼 >( repo_id: str repo_type: str | None = None revision: str | None = None local_dir: str | Path | None = None cache_dir: str | Path | None = None token: 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 — 如果在儲存庫中找不到該版本(錯誤 404)。
針對儲存庫驗證本機檔案與 Hub 的校驗和(checksums)。
whoami
< 原始碼 >( token: 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 以得知「我是誰」(whoami)。
若傳入 cache=True,結果將在 Python 程序期間被快取以供後續呼叫。如果您計畫多次呼叫 whoami,此功能相當實用,因為基於安全考量,此端點有嚴格的速率限制。
API 資料類別 (Dataclasses)
AccessRequest
class huggingface_hub.hf_api.AccessRequest
< 原始碼 >( username: str fullname: str email: str | None timestamp: datetime status: Literal['pending', 'accepted', 'rejected'] fields: dict[str, Any] | None = None )
參數
- username (
str) — 請求存取權的使用者名稱。 - fullname (
str) — 請求存取權的使用者全名。 - email (
Optional[str]) — 請求存取權的使用者電子郵件。若使用者是手動獲准存取,則在 /accepted 清單中可能為None。 - timestamp (
datetime) — 請求的時間戳記。 - status (
Literal["pending", "accepted", "rejected"]) — 請求的狀態。可以是["pending", "accepted", "rejected"]其中之一。 - fields (
dict[str, Any], optional) — 使用者在存取表單(gate form)中填寫的額外欄位。
包含使用者存取請求相關資訊的資料結構。
BucketFile
包含 Hub 上 bucket 中檔案的相關資訊。此物件由 list_bucket_tree() 傳回。
類似於 RepoFile,但針對的是 bucket 中的檔案。
BucketFileMetadata
class huggingface_hub.BucketFileMetadata
< 原始碼 >( size: int xet_file_data: XetFileData )
包含 bucket 中檔案相關資訊的資料結構。
BucketInfo
class huggingface_hub.BucketInfo
< 原始碼 >( **kwargs )
包含 Hub 上 bucket 相關資訊。此物件由 bucket_info() 和 list_buckets() 傳回。
BucketUrl
class huggingface_hub.BucketUrl
< 原始碼 >( url: str endpoint: str = '' )
參數
- url (
str) — Bucket URL 的字串值。 - endpoint (
str, optional) — Hub 的端點。預設為 https://huggingface.co。
描述 Hub 上的 bucket URL。
BucketUrl 由 create_bucket() 傳回。在初始化時,URL 會被解析以填入以下屬性:
- endpoint (
str) - namespace (
str) - bucket_id (
str) - url (
str) - uri (
HfUri)
DatasetLeaderboardEntry
class huggingface_hub.DatasetLeaderboardEntry
< 原始碼 >( **kwargs )
參數
- rank (
int) — 模型在排行榜上的排名(1 為起始)。 - model_id (
str) — 模型 ID(例如"meta-llama/Llama-3-8b")。 - value (
float) — 評估分數值。 - filename (
str) — 包含評估資料的結果檔案名稱。 - verified (
bool) — 結果是否已通過驗證。 - source (
dict[str, Any]) — 評估結果來源的相關資訊。包含如"url"、"name"和"isExternal"等鍵值。 - author (
User或Organization) — 模型作者,根據 API 回應中的"type"欄位進行解析。 - pull_request (
int, optional) — 與此排行榜條目關聯的 Pull Request 編號(若有)。 - notes (
str, optional) — 與此排行榜條目相關的備註(若有)。
包含 Hub 上資料集排行榜中單一條目的相關資訊。
排行榜會根據模型在特定基準資料集上的評估分數進行排名。此物件由 get_dataset_leaderboard() 傳回。若要獲取特定模型在各基準測試中的評估結果,請參閱 ModelInfo.eval_results(透過 model_info() 並設定 expand=["evalResults"])以及 EvalResultEntry。
EvalResultEntry
class huggingface_hub.EvalResultEntry
< 原始碼 >( dataset_id: str task_id: str value: typing.Any dataset_revision: str | None = None verify_token: str | None = None date: str | None = None source_url: str | None = None source_name: str | None = None source_user: str | None = None source_org: str | None = None notes: str | None = None )
參數
- dataset_id (
str) — Hub 上的基準資料集 ID。例如:「cais/hle」、「Idavidrein/gpqa」。 - task_id (
str) — 基準測試中的任務識別碼。例如:「gpqa_diamond」。 - value (
Any) — 度量分數值。例如:20.90。 - dataset_revision (
str, optional) — 基準資料集的 Git SHA。 - verify_token (
str, optional) — 一個可用於證明評估結果具備可審計性與可重現性的簽章。 - date (
str, optional) — 評估執行時間(ISO-8601 日期時間格式)。預設為 git 提交時間。 - source_url (
str, optional) — 評估來源連結(例如:https://huggingface.co/spaces/SaylorTwift/smollm3-mmlu-pro)。若提供了source_name、source_user或source_org,則此欄位為必填。 - source_name (
str, optional) — 來源顯示名稱。範例:「Eval Logs」。 - source_user (
str, optional) — 用於歸屬的 HF 使用者名稱。範例:「celinah」。 - source_org (
str, optional) — 用於歸屬的 HF 組織名稱。範例:「cais」。 - notes (
str, optional) — 有關評估設定的詳細資訊。範例:「tools」、「no-tools」、「chain-of-thought」。
適用於 .eval_results/*.yaml 格式的評估結果條目。
代表儲存在模型儲存庫中,且會自動出現在模型頁面及基準資料集排行榜上的評估分數。
對於 README.md 中的舊版 model-index 格式,請改用 EvalResult。
詳情請參閱 https://huggingface.co/docs/hub/eval-results。
範例
>>> from huggingface_hub import EvalResultEntry
>>> # Minimal example with required fields only
>>> result = EvalResultEntry(
... dataset_id="Idavidrein/gpqa",
... task_id="gpqa_diamond",
... value=0.412,
... )
>>> # Full example with all fields
>>> result = EvalResultEntry(
... dataset_id="cais/hle",
... task_id="default",
... value=20.90,
... dataset_revision="5503434ddd753f426f4b38109466949a1217c2bb",
... verify_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
... date="2025-01-15T10:30:00Z",
... source_url="https://huggingface.co/datasets/cais/hle",
... source_name="CAIS HLE",
... source_org="cais",
... notes="no-tools",
... )
SyncOperation
class huggingface_hub.SyncOperation
< 原始碼 >( action: typing.Literal['upload', 'download', 'delete', 'skip'] path: str size: int | None = None reason: str = '' local_mtime: str | None = None remote_mtime: str | None = None bucket_file: huggingface_hub._buckets.BucketFile | None = None )
代表即將執行的同步作業。
SyncPlan
class huggingface_hub.SyncPlan
< 原始碼 >( source: str dest: str timestamp: str operations: list = <factory> )
代表一個完整的同步計畫。
CommitInfo
class huggingface_hub.CommitInfo
< 原始碼 >( *args commit_url: str **kwargs )
參數
- commit_url (
str) — 可找到該提交的網址。 - commit_message (
str) — 已建立提交的摘要(第一行)。 - commit_description (
str) — 已建立提交的描述。可以是空字串。 - oid (
str) — 提交雜湊 ID。範例:"91c54ad1727ee830252e457677f467be0bfd8a57"。 - pr_url (
str, optional) — 若有建立 PR,則為其連結網址。在傳入create_pr=True時會被填入。 - pr_revision (
str, optional) — 若有建立 PR,則為其修訂版本。在傳入create_pr=True時會被填入。範例:"refs/pr/1"。 - pr_num (
int, optional) — 若有建立 PR,則為其討論串編號。在傳入create_pr=True時會被填入。可作為 get_discussion_details() 中的discussion_num參數傳入。範例:1。 - repo_url (
RepoUrl) — 包含 repo_id、repo_type 等資訊的提交儲存庫網址。
包含新建立提交相關資訊的資料結構。
由任何在 Hub 上建立提交的方法回傳:create_commit()、upload_file()、upload_folder()、delete_file()、delete_folder()。為了向後相容,它繼承自 str,但已不建議使用字串相關的方法。
DatasetInfo
class huggingface_hub.DatasetInfo
< 原始碼 >( **kwargs )
參數
- id (
str) — 資料集 ID。 - author (
str) — 資料集作者。 - card_data (
DatasetCardData, optional) — 以 huggingface_hub.repocard_data.DatasetCardData 物件形式表示的資料集卡片詮釋資料。 - citation (
str, optional) — 資料集的引用資訊。 - created_at (
datetime, optional) — 儲存庫在 Hub 上的建立日期。注意最低值為2022-03-02T23:29:04.000Z,對應到我們開始儲存建立日期的日期。 - description (
str, optional) — 資料集描述。 - disabled (
bool, optional) — 儲存庫是否已停用。 - downloads (
int) — 過去 30 天的資料集下載次數。 - downloads_all_time (
int) — 資料集自建立以來的累計下載次數。 - gated (
Literal["auto", "manual", False], optional) — 儲存庫是否設有存取權限控管(gated)。若有,說明是手動還是自動核准。 - last_modified (
datetime, optional) — 儲存庫最後一次提交的日期。 - likes (
int) — 資料集的按讚數。 - main_size (
int, optional) — 資料集主分支的大小(位元組)。 - paperswithcode_id (
str, optional) — 資料集的 Papers with code ID。 - private (
bool) — 儲存庫是否為私有。 - resource_group (
dict, optional) — 資料集的資源群組資訊。 - sha (
str) — 此特定修訂版本的儲存庫 SHA。 - siblings (
list[RepoSibling]) — 組成該資料集的 huggingface_hub.hf_api.RepoSibling 物件列表。 - tags (
list[str]) — 資料集的標籤列表。 - trending_score (
int, optional) — 資料集的趨勢分數。 - used_storage (
int, optional) — Hub 上資料集佔用的儲存空間(位元組)。
包含 Hub 上資料集的相關資訊。此物件由 dataset_info() 及 list_datasets() 回傳。
此類別的大部分屬性皆為選填。這是因為從 Hub 回傳的資料取決於所做的查詢。一般來說,查詢越具體,回傳的資訊就越詳盡。相反地,當使用 list_datasets() 列出資料集時,只會回傳屬性的一個子集。
DryRunFileInfo
class huggingface_hub.DryRunFileInfo
< 原始碼 >( 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
< 原始碼 >( name: str ref: str target_commit: str )
包含 Hub 上儲存庫的 git 參考資訊。
GitCommitInfo
class huggingface_hub.GitCommitInfo
< 原始碼 >( commit_id: str authors: list[str] created_at: datetime title: str message: str formatted_title: str | None formatted_message: str | None )
參數
- commit_id (
str) — 提交的 OID(例如"e7da7f221d5bf496a48136c0cd264e630fe9fcc8")。 - authors (
list[str]) — 該提交的作者列表。 - created_at (
datetime) — 提交建立的日期時間。 - title (
str) — 提交(commit)的標題。這是一個由作者輸入的自由文字欄位。 - message (
str) — 提交的說明。這是一個由作者輸入的自由文字欄位。 - formatted_title (
str) — 以 HTML 格式呈現的提交標題。僅在設定了formatted=True時才會返回。 - formatted_message (
str) — 以 HTML 格式呈現的提交說明。僅在設定了formatted=True時才會返回。
包含有關 Hub 上儲存庫(repo)的 Git 提交資訊。詳情請參閱 list_repo_commits()。
GitRefs
class huggingface_hub.GitRefs
< 原始碼 >( branches: list[GitRefInfo] converts: list[GitRefInfo] tags: list[GitRefInfo] pull_requests: list[GitRefInfo] | None = None )
參數
- branches (
list[GitRefInfo]) — 包含儲存庫中分支資訊的 GitRefInfo 列表。 - converts (
list[GitRefInfo]) — 包含儲存庫中「轉換 (convert)」參照資訊的 GitRefInfo 列表。轉換參照是用於(內部)推播資料集儲存庫中預處理資料的參照。 - tags (
list[GitRefInfo]) — 包含儲存庫中標籤資訊的 GitRefInfo 列表。 - pull_requests (
list[GitRefInfo], 選用) — 包含儲存庫中提取請求(Pull Request)資訊的 GitRefInfo 列表。僅在設定了include_prs=True時才會返回。
包含 Hub 上儲存庫的所有 Git 參照資訊。
此物件由 list_repo_refs() 返回。
InferenceProviderMapping
KernelInfo
class huggingface_hub.KernelInfo
< 原始碼 >( **kwargs )
參數
- id (
str) — Kernel 儲存庫的 ID。 - author (
str, 選用) — Kernel 儲存庫的作者。 - downloads (
int, 選用) — 過去 30 天內該 Kernel 儲存庫的下載次數。 - gated (
Literal["auto", "manual", False], 選用) — 儲存庫是否為受限(gated)。若是,則表示是人工還是自動審核。 - last_modified (
datetime, 選用) — 儲存庫最後一次提交的日期。 - likes (
int, 選用) — 該 Kernel 儲存庫的點讚數。 - private (
bool, 選用) — 儲存庫是否為私有。 - sha (
str, 選用) — 該特定修訂版本下的儲存庫 SHA。
包含有關 Hub 上 Kernel 儲存庫的資訊。此物件由 kernel_info() 返回。
LFSFileInfo
class huggingface_hub.hf_api.LFSFileInfo
< 原始碼 >( **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
< 原始碼 >( **kwargs )
參數
- id (
str) — 模型的 ID。 - author (
str, 選用) — 模型的作者。 - base_models (
list[str], 選用) — 衍生自此模型的基本模型列表。 - card_data (
ModelCardData, 選用) — 以 huggingface_hub.repocard_data.ModelCardData 物件呈現的模型卡元資料。 - children_model_count (
int, 選用) — 從此模型衍生的子模型數量。 - config (
dict, 選用) — 模型設定。 - created_at (
datetime, 選用) — 儲存庫在 Hub 上的建立日期。請注意,最小值為2022-03-02T23:29:04.000Z,對應我們開始儲存建立日期的時間。 - disabled (
bool, 選用) — 儲存庫是否已停用。 - downloads (
int) — 過去 30 天內該模型的下載次數。 - downloads_all_time (
int) — 該模型自建立以來的累計下載次數。 - eval_results (
list[EvalResultEntry], 選用) — 模型的評估結果。 - gated (
Literal["auto", "manual", False], 選用) — 儲存庫是否為受限(gated)。若是,則表示是人工還是自動審核。 - gguf (
dict, 選用) — 模型的 GGUF 資訊。 - inference (
Literal["warm"], 選用) — 模型在推理提供者 (Inference Providers) 上的狀態。若模型由至少一個提供者服務,則為 warm。 - inference_provider_mapping (
list[InferenceProviderMapping], 選用) — 根據使用者偏好的提供者順序排序的InferenceProviderMapping列表。 - last_modified (
datetime, 選用) — 儲存庫最後一次提交的日期。 - library_name (
str, 選用) — 與模型關聯的程式庫。 - likes (
int) — 該模型的點讚數。 - mask_token (
str, 選用) — 模型使用的遮罩 (mask) token。 - model_index (
dict, 選用) — 用於評估的模型索引。 - pipeline_tag (
str, 選用) — 與模型關聯的管線 (pipeline) 標籤。 - private (
bool) — 儲存庫是否為私有。 - resource_group (
dict, 選用) — 模型的資源群組資訊。 - safetensors (
SafeTensorsInfo, 選用) — 模型的 safetensors 資訊。 - security_repo_status (
dict, 選用) — 模型的安全性掃描狀態。 - sha (
str, 選用) — 該特定修訂版本下的儲存庫 SHA。 - siblings (
list[RepoSibling]) — 組成此模型的 huggingface_hub.hf_api.RepoSibling 物件列表。 - spaces (
list[str], 選填) — 使用此模型的空間(Spaces)列表。 - tags (
list[str]) — 此模型的標籤列表。相較於card_data.tags,此處包含由 Hub 計算的額外標籤(例如:支援的函式庫、模型的 arXiv 論文連結等)。 - transformers_info (
TransformersInfo, 選填) — 與此模型相關的 Transformers 特定資訊(自動類別、處理器等)。 - trending_score (
int, 選填) — 此模型的趨勢評分。 - used_storage (
int, 選填) — 模型在 Hub 上所佔用的儲存空間大小(以位元組為單位)。 - widget_data (
Any, 選填) — 與模型相關的 Widget 資料。
包含 Hub 上關於模型資訊的內容。此物件由 model_info() 與 list_models() 所回傳。
此類別的大多數屬性均為選填,這是因為 Hub 回傳的資料取決於所進行的查詢。一般來說,查詢越具體,回傳的資訊就越多。相反地,使用 list_models() 列出模型時,僅會回傳屬性的子集。
RepoSibling
class huggingface_hub.hf_api.RepoSibling
< 來源 >( rfilename: str size: int | None = None blob_id: str | None = None lfs: BlobLfsInfo | None = 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
< 來源 >( **kwargs )
參數
- path (str) — 相對於儲存庫根目錄的檔案路徑。
- size (
int) — 檔案大小(以位元組為單位)。 - blob_id (
str) — 檔案的 git OID。 - lfs (
BlobLfsInfo, 選填) — 檔案的 LFS 中繼資料。 - xet_hash (
str, 選填) — 檔案的 Xet雜湊值。 - last_commit (
LastCommitInfo, 選填) — 檔案的最近一次提交(commit)中繼資料。僅在呼叫 list_repo_tree() 和 get_paths_info() 並將expand設定為True時定義。 - security (
BlobSecurityInfo, 選填) — 檔案的安全性掃描中繼資料。僅在呼叫 list_repo_tree() 和 get_paths_info() 並將expand設定為True時定義。
包含關於 Hub 上檔案的資訊。
RepoUrl
class huggingface_hub.RepoUrl
< 來源 >( url: Any endpoint: str | None = None )
參數
- url (
Any) — 儲存庫網址的字串值。 - endpoint (
str, 選填) — 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
< 來源 >( metadata: dict | None sharded: bool weight_map: dict files_metadata: dict )
參數
- metadata (
dict, 選填) — 包含在 ‘model.safetensors.index.json’ 檔案中的中繼資料(若存在)。僅針對分片(sharded)模型進行填入。 - sharded (
bool) — 儲存庫是否包含分片模型。 - weight_map (
dict[str, str]) — 所有權重映射表。鍵為張量(tensor)名稱,值為包含該張量的檔案名稱。 - 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
< 來源 >( metadata: dict tensors: dict )
Hub 上代管的 Safetensors 檔案中繼資料。
此類別由 parse_safetensors_file_metadata() 回傳。
關於 safetensors 格式的更多詳細資訊,請參閱 https://huggingface.co/docs/safetensors/index#format。
SpaceInfo
class huggingface_hub.SpaceInfo
< 來源 >( **kwargs )
參數
- id (
str) — 空間(Space)的 ID。 - author (
str, 選填) — 空間的作者。 - card_data (
SpaceCardData, 選填) — 以 huggingface_hub.repocard_data.SpaceCardData 物件形式呈現的空間卡片中繼資料。 - created_at (
datetime, 選填) — 儲存庫在 Hub 上的建立日期。注意,最小值為2022-03-02T23:29:04.000Z,對應於我們開始儲存建立日期的時間。 - datasets (
list[str], 選填) — 空間所使用的資料集列表。 - disabled (
bool, 選填) — 空間是否已停用。 - gated (
Literal["auto", "manual", False], 選填) — 儲存庫是否為門控(gated)。若是,則區分為手動或自動審核。 - host (
str, 選填) — 空間的主機網址。 - last_modified (
datetime, 選填) — 儲存庫最近一次提交的日期。 - likes (
int) — 空間的讚數。 - models (
list[str], 選填) — 空間所使用的模型列表。 - private (
bool) — 儲存庫是否為私有。 - resource_group (
dict, 選填) — 空間的資源群組資訊。 - runtime (
SpaceRuntime, 選填) — 以 huggingface_hub.hf_api.SpaceRuntime 物件形式呈現的空間執行時期資訊。 - sdk (
str, 選填) — 空間所使用的 SDK。 - sha (
str, 選填) — 在此特定修訂版(revision)的儲存庫 SHA。 - siblings (
list[RepoSibling]) — 組成此空間的 huggingface_hub.hf_api.RepoSibling 物件列表。 - subdomain (
str, 選填) — 空間的子網域(subdomain)。 - tags (
list[str]) — 空間的標籤列表。 - trending_score (
int, optional) — Space 的熱門程度分數。 - used_storage (
int, optional) — Hub 上該 Space 的儲存空間大小(單位為位元組)。
包含 Hub 上 Space 的相關資訊。此物件由 space_info() 和 list_spaces() 回傳。
此類別的大多數屬性皆為選填。這是因為 Hub 回傳的資料取決於所做的查詢。通常,查詢越具體,回傳的資訊就越詳盡。相反地,使用 list_spaces() 列出 Spaces 時,僅會回傳屬性的一個子集。
SpaceSearchResult
class huggingface_hub.SpaceSearchResult
< 原始碼 >( data: dict )
參數
- id (
str) — Space 的 ID(例如"username/repo-name")。 - author (
str) — Space 的作者。 - title (
str) — Space 的顯示標題。 - emoji (
str或None) — Space 的圖示表情符號。 - sdk (
str或None) — Space 使用的 SDK(例如"gradio"、"docker"、"static")。 - likes (
int) — 按讚次數。 - private (
bool) — Space 是否為私人。 - tags (
list[str]或None) — 標籤列表。 - runtime (SpaceRuntime 或
None) — 執行環境資訊(階段、硬體等)。 - ai_short_description (
str或None) — AI 生成的簡短描述。 - ai_category (
str或None) — AI 生成的類別(例如"Image Generation")。 - semantic_relevancy_score (
float或None) — 相對於搜尋查詢的語意相關性分數 (0-1)。 - trending_score (
int或None) — 熱門程度分數。
Spaces 語意搜尋 API 的單一搜尋結果。
由 HfApi.search_spaces() 回傳。
TensorInfo
class huggingface_hub.utils.TensorInfo
< 原始碼 >( 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
< 原始碼 >( **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) — 使用者建立的 Spaces 數量。 - 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 (
Organization的列表) — 使用者所屬的組織列表。
包含關於 Hub 上使用者的資訊。
UserLikes
class huggingface_hub.UserLikes
< 原始碼 >( user: str total: int datasets: list[str] kernels: list[str] models: list[str] spaces: list[str] )
包含關於 Hub 上使用者按讚資料的資訊。
WebhookInfo
class huggingface_hub.WebhookInfo
< 原始碼 >( id: str url: str | None job: JobSpec | None watched: list[WebhookWatchedItem] domains: list[constants.WEBHOOK_DOMAIN_T] secret: str | None 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 的密鑰。 - disabled (
bool) — Webhook 是否已停用。
包含 Webhook 相關資訊的資料結構。
url 或 job 其中之一會被指定,但不會同時指定兩者。
WebhookWatchedItem
class huggingface_hub.WebhookWatchedItem
< 原始碼 >( type: Literal['dataset', 'model', 'org', 'space', 'user'] name: str )
包含關於 Webhook 所監控項目資訊的資料結構。
CommitOperation
以下是 CommitOperation() 支援的值:
class huggingface_hub.CommitOperationAdd
< 原始碼 >( path_in_repo: str path_or_fileobj: str | pathlib.Path | bytes | typing.BinaryIO )
參數
- path_in_repo (
str) — 儲存庫中的相對檔案路徑,例如:"checkpoints/1fec34a/weights.bin" - path_or_fileobj (
str,Path,bytes, 或BinaryIO) — 可為下列其中之一:- 要上傳的本機檔案路徑 (作為
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
< 原始碼 >( 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
< 原始碼 >( path_in_repo: str is_folder: typing.Union[bool, typing.Literal['auto']] = 'auto' )
儲存從 Hub 儲存庫中刪除檔案或資料夾所需資訊的資料結構。
class huggingface_hub.CommitOperationCopy
< 原始碼 >( src_path_in_repo: str path_in_repo: str src_revision: str | None = None _src_oid: str | None = None _dest_oid: str | None = None )
儲存將檔案複製至 Hub 儲存庫所需資訊的資料結構。
限制
- 僅 LFS 檔案可被複製。若要複製一般檔案,您需要先將其下載至本機再重新上傳。
- 不支援跨儲存庫複製。
注意:您可以結合 CommitOperationCopy 與 CommitOperationDelete 來重新命名 Hub 上的 LFS 檔案。
CommitScheduler
class huggingface_hub.CommitScheduler
< 原始碼 >( repo_id: str folder_path: str | pathlib.Path every: int | float = 5 path_in_repo: str | None = None repo_type: str | None = None revision: str | None = None private: bool | None = None token: str | None = None allow_patterns: list[str] | str | None = None ignore_patterns: list[str] | str | None = None squash_history: bool = False hf_api: typing.Optional[ForwardRef('HfApi')] = None )
參數
- repo_id (
str) — 要提交的儲存庫 ID。 - folder_path (
str或Path) — 要定期上傳的本機資料夾路徑。 - every (
int或float, 選填) — 每次提交之間的間隔分鐘數。預設為 5 分鐘。 - path_in_repo (
str, 選填) — 儲存庫中目錄的相對路徑,例如:"checkpoints/"。預設為儲存庫的根目錄。 - repo_type (
str, 選填) — 要提交的儲存庫類型。預設為model。 - revision (
str, 選填) — 要提交的儲存庫修訂版本。預設為main。 - private (
bool, 選填) — 是否將儲存庫設為私人。若為None(預設),除非組織預設為私人,否則儲存庫將公開。若儲存庫已存在,此值將被忽略。 - token (
str, 選填) — 用於提交至儲存庫的權杖 (token)。預設為本機儲存的權杖。 - allow_patterns (
list[str]或str, 選填) — 若提供,則僅會上傳符合至少一個模式的檔案。 - ignore_patterns (
list[str]或str, 選填) — 若提供,則符合任何模式的檔案將不會被上傳。 - squash_history (
bool, 選填) — 是否在每次提交後壓縮儲存庫的歷史紀錄。預設為False。當儲存庫變得過大時,壓縮提交紀錄有助於避免效能下降。 - hf_api (
HfApi, 選填) — 用於提交至 Hub 的 HfApi 客戶端。可透過自訂設定 (user agent、token 等) 進行配置。
用於定期(例如每 5 分鐘推送至 hub)將本機資料夾上傳至 Hub 的排程器。
建議將排程器作為內容管理器使用。這能確保排程器在指令碼結束時正確停止並觸發最後一次提交。排程器也可以使用 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 的預設行為是假設為僅附加 (append-only) 的資料夾。它會列出資料夾中的所有檔案並僅上傳已變更的檔案。若未發現變更,該方法會直接返回而不提交任何內容。若您想更改此行為,可以繼承 CommitScheduler 並覆寫此方法。例如,這在提交前將資料壓縮為單一檔案時很有用。欲了解更多細節與範例,請查看我們的 整合指南。
觸發 push_to_hub 並回傳一個 future 物件。
此方法會每 every 分鐘自動呼叫一次。您也可以手動呼叫它以立即觸發提交,無需等待下一次預定的提交。