Hub Python 函式庫文件
工具程式
並獲得增強的文件體驗
開始使用
公用程式 (Utilities)
設定記錄層級
huggingface_hub 套件提供了一個 logging 工具,用於控制套件本身的記錄層級。您可以透過以下方式匯入:
from huggingface_hub import logging接著,您可以定義詳細程度(verbosity)來更新您看到的記錄數量。
from huggingface_hub import logging
logging.set_verbosity_error()
logging.set_verbosity_warning()
logging.set_verbosity_info()
logging.set_verbosity_debug()
logging.set_verbosity(...)記錄層級定義如下:
error:僅顯示關於可能導致錯誤或非預期行為之使用的嚴重記錄。warning:顯示非嚴重但可能導致意外行為之使用的記錄。此外,可能會顯示重要的資訊性記錄。info:顯示大多數記錄,包括一些關於底層運作的詳細記錄。如果出現非預期的行為,建議將詳細程度層級切換至此,以取得更多資訊。debug:顯示所有記錄,包括一些可能用於追蹤底層精確運作情形的內部記錄。
傳回 HuggingFace Hub 根記錄器的目前層級。
HuggingFace Hub 具有以下記錄層級:
huggingface_hub.logging.CRITICAL,huggingface_hub.logging.FATALhuggingface_hub.logging.ERRORhuggingface_hub.logging.WARNING,huggingface_hub.logging.WARNhuggingface_hub.logging.INFOhuggingface_hub.logging.DEBUG
huggingface_hub.utils.logging.set_verbosity
< 原始碼 >( verbosity: int )
設定 HuggingFace Hub 根記錄器的層級。
將詳細程度設定為 logging.INFO。
將詳細程度設定為 logging.DEBUG。
將詳細程度設定為 logging.WARNING。
將詳細程度設定為 logging.ERROR。
停用此函式庫記錄輸出的傳播 (propagation)。請注意,記錄傳播預設為停用。
啟用程式庫記錄輸出的傳播(propagation)。如果已設定根記錄器,請停用 HuggingFace Hub 的預設處理常式,以防止重複記錄。
儲存庫專用的輔助方法
以下公開的方法在修改 huggingface_hub 程式庫本身的模組時很有用。如果您只是使用 huggingface_hub 而不進行修改,則不需使用這些方法。
huggingface_hub.utils.logging.get_logger
< 原始碼 >( name: str | None = None )
傳回具有指定名稱的記錄器。此函式不應直接由程式庫使用者存取。
設定進度條
進度條是一種有用的工具,可在執行長時間執行的任務(例如下載或上傳檔案)時向使用者顯示資訊。huggingface_hub 公開了一個 tqdm 包裝器,以便在整個程式庫中以一致的方式顯示進度條。
預設情況下,進度條是啟用的。您可以透過設定 HF_HUB_DISABLE_PROGRESS_BARS 環境變數來全域停用它們。您也可以使用 enable_progress_bars() 和 disable_progress_bars 來啟用/停用它們。如果已設定環境變數,其優先權高於這些輔助函式。
>>> from huggingface_hub import snapshot_download
>>> from huggingface_hub.utils import are_progress_bars_disabled, disable_progress_bars, enable_progress_bars
>>> # Disable progress bars globally
>>> disable_progress_bars()
>>> # Progress bar will not be shown !
>>> snapshot_download("gpt2")
>>> are_progress_bars_disabled()
True
>>> # Re-enable progress bars globally
>>> enable_progress_bars()針對特定群組的進度條控制
您也可以針對特定群組啟用或停用進度條。這使您能夠在應用程式或程式庫的不同部分更細緻地管理進度條的可見性。當為一個群組停用進度條時,除非明確覆寫,否則其下所有的子群組也會受到影響。
# Disable progress bars for a specific group
>>> disable_progress_bars("peft.foo")
>>> assert not are_progress_bars_disabled("peft")
>>> assert not are_progress_bars_disabled("peft.something")
>>> assert are_progress_bars_disabled("peft.foo")
>>> assert are_progress_bars_disabled("peft.foo.bar")
# Re-enable progress bars for a subgroup
>>> enable_progress_bars("peft.foo.bar")
>>> assert are_progress_bars_disabled("peft.foo")
>>> assert not are_progress_bars_disabled("peft.foo.bar")
# Use groups with tqdm
# No progress bar for `name="peft.foo"`
>>> for _ in tqdm(range(5), name="peft.foo"):
... pass
# Progress bar will be shown for `name="peft.foo.bar"`
>>> for _ in tqdm(range(5), name="peft.foo.bar"):
... pass
100%|███████████████████████████████████████| 5/5 [00:00<00:00, 117817.53it/s]are_progress_bars_disabled
huggingface_hub.utils.are_progress_bars_disabled
< 原始碼 >( name: str | None = None ) → bool
檢查進度條是否已全域停用,或是否針對特定群組停用。
此函式會傳回進度條是否已針對特定群組或全域停用。它會先檢查 HF_HUB_DISABLE_PROGRESS_BARS 環境變數,接著檢查程式設計設定。
disable_progress_bars
class huggingface_hub.utils.disable_progress_bars
< 原始碼 >( name: str | None = None )
全域或針對指定群組停用進度條。
此函式會根據群組名稱更新進度條的狀態。如果未提供群組名稱,則會停用所有進度條。此操作會尊重 HF_HUB_DISABLE_PROGRESS_BARS 環境變數的設定。
可作為一般呼叫或內容管理器使用:disable_progress_bars() # 停用直到 enable_progress_bars() 為止;使用 with disable_progress_bars(): # 僅針對該區塊停用,離開時自動重新啟用...
enable_progress_bars
huggingface_hub.utils.enable_progress_bars
< 原始碼 >( name: str | None = None )
全域或針對指定群組啟用進度條。
此函式會將指定群組(或未指定群組時則為全域)的進度條設定為啟用。此操作受 HF_HUB_DISABLE_PROGRESS_BARS 環境設定的限制。
設定 HTTP 後端
在
huggingface_hubv0.x 中,HTTP 請求是透過requests處理的,設定則是透過configure_http_backend完成。由於我們現在使用httpx,設定方式有所不同:您必須提供一個不帶參數且回傳httpx.Client的工廠函式。您可以檢閱預設實作這裡,以查看預設使用哪些參數。
在某些設定中,您可能需要控制 HTTP 請求的發送方式,例如在使用代理伺服器(proxy)時。huggingface_hub 程式庫允許您透過 set_client_factory() 全域設定此項。設定完成後,所有發往 Hub 的請求都將使用您的自訂設定。由於 huggingface_hub 底層依賴 httpx.Client,您可以查看 httpx 文件以取得可用參數的詳細資料。
如果您正在構建第三方程式庫,且需要向 Hub 發出直接請求,請使用 get_session() 來取得正確設定的 httpx 客戶端。請將任何直接的 httpx.get(...) 呼叫替換為 get_session().get(...) 以確保運作正確。
設定 huggingface_hub 使用的 HTTP 客戶端工廠。
客戶端工廠是一個回傳 httpx.Client 物件的方法。在第一次呼叫 get_session() 時,客戶端工廠將被用於建立一個新的 httpx.Client 物件,該物件將在 huggingface_hub 進行的所有呼叫之間共用。
如果您在需要自訂設定(例如自訂代理伺服器或憑證)的特定環境中執行指令碼,這會很有用。
使用 get_session() 來取得正確設定的 httpx.Client。
取得一個 httpx.Client 物件,並使用使用者提供的傳輸工廠(transport factory)。
此客戶端在 huggingface_hub 進行的所有呼叫之間共用。因此,您不應手動關閉它。
使用 set_client_factory() 來定製 httpx.Client。
在極少數情況下,您可能需要手動關閉目前的工作階段(例如在暫時性的 SSLError 之後)。您可以使用 close_session() 來執行此操作。下一次呼叫 get_session() 時會自動建立一個新的工作階段。
當程序結束時,工作階段總是會自動關閉。
對於非同步程式碼,請使用 set_async_client_factory() 來設定 httpx.AsyncClient,並使用 get_async_session() 來檢索一個。
設定 huggingface_hub 使用的 HTTP 非同步客戶端工廠。
非同步客戶端工廠是一個回傳 httpx.AsyncClient 物件的方法。如果您在需要自訂設定(例如自訂代理伺服器或憑證)的特定環境中執行指令碼,這會很有用。使用 get_async_client 來取得正確設定的 httpx.AsyncClient。
與在
huggingface_hub進行的所有呼叫之間共用的httpx.Client不同,httpx.AsyncClient不會被共用。建議使用非同步內容管理器,以確保在離開內容時正確關閉客戶端。
回傳一個 httpx.AsyncClient 物件,並使用使用者提供的傳輸工廠。
使用 set_async_client_factory() 來定製 httpx.AsyncClient。
與在
huggingface_hub進行的所有呼叫之間共用的httpx.Client不同,httpx.AsyncClient不會被共用。建議使用非同步內容管理器,以確保在離開內容時正確關閉客戶端。
與同步客戶端不同,非同步客戶端的生命週期並非自動管理。請使用非同步內容管理器來正確處理它。
處理 HTTP 錯誤
huggingface_hub 定義了自己的 HTTP 錯誤,以使用伺服器傳回的額外資訊來細化 httpx 所引發的 HTTPError。
針對狀態引發錯誤 (Raise for status)
hf_raise_for_status() 旨在作為對發往 Hub 的任何請求進行「針對狀態引發錯誤」的核心方法。它包裝了基礎的 httpx.Response.raise_for_status 以提供額外資訊。任何丟出的 HTTPError 都會轉換為 HfHubHTTPError。
from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError
response = get_session().post(...)
try:
hf_raise_for_status(response)
except HfHubHTTPError as e:
print(str(e)) # formatted message
e.request_id, e.server_message # details returned by server
# Complete the error message with additional information once it's raised
e.append_to_message("\n`create_commit` expects the repository to exist.")
raisehuggingface_hub.hf_raise_for_status
< 原始碼 >( response: Response endpoint_name: str | None = None )
response.raise_for_status() 的內部版本,將細化潛在的 HTTPError。引發的例外將是 HfHubHTTPError 的實例。
此輔助程式旨在成為呼叫 Hugging Face Hub 時引發狀態錯誤的唯一方法。
當請求失敗時引發錯誤:
- RepositoryNotFoundError 如果找不到要從中下載的儲存庫。原因可能是它不存在、
repo_type設定不正確,或是該儲存庫是private而您沒有存取權限。- GatedRepoError 如果儲存庫存在但受到存取限制 (gated),且使用者不在授權名單中。
- RevisionNotFoundError 如果儲存庫存在但找不到修訂版本 (revision)。
- EntryNotFoundError 如果儲存庫存在但找不到該項目(例如請求的檔案)。
- BadRequestError 如果請求失敗並收到 HTTP 400 BadRequest 錯誤。
- HfHubHTTPError 如果請求因上述未列出的原因失敗。
檢查離線模式
您可以使用 is_offline_mode 以程式方式檢查是否啟用了離線模式。離線模式是透過設定 HF_HUB_OFFLINE=1 作為環境變數來啟用的。
傳回 Hub 是否處於離線模式。
啟用離線模式時,所有使用 get_session 發出的 HTTP 請求都將引發 OfflineModeIsEnabled 例外。
HTTP 錯誤
以下是 huggingface_hub 中引發的 HTTP 錯誤列表。
HfHubHTTPError
HfHubHTTPError 是任何 HF Hub HTTP 錯誤的父類別。它負責解析伺服器回應並格式化錯誤訊息,以盡可能為使用者提供更多資訊。
class huggingface_hub.errors.HfHubHTTPError
< 原始碼 >( message: str response: Response server_message: str | None = None )
HTTPError,用於繼承 HF Hub 中引發的任何自訂 HTTP 錯誤。
任何 HTTPError 至少會轉換為 HfHubHTTPError。如果伺服器傳回了一些資訊,它們將被添加到錯誤訊息中。
新增的詳細資料:
- 請求 ID,根據優先順序從標頭來源取得: 「X-Request-Id」、「X-Amzn-Trace-Id」、「X-Amz-Cf-Id」。
- 來自標頭「X-Error-Message」的伺服器錯誤訊息。
- 如果能在回應主體中找到,則為伺服器錯誤訊息。
範例
import httpx
from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError
response = get_session().post(...)
try:
hf_raise_for_status(response)
except HfHubHTTPError as e:
print(str(e)) # formatted message
e.request_id, e.server_message # details returned by server
# Complete the error message with additional information once it's raised
e.append_to_message("
ate_commit` expects the repository to exist.")
raise將其他資訊附加到 HfHubHTTPError 的初始訊息中。
RepositoryNotFoundError
class huggingface_hub.errors.RepositoryNotFoundError
< 原始碼 >( message: str response: Response server_message: str | None = None )
當嘗試使用無效的儲存庫名稱,或使用者無權存取的私人儲存庫名稱存取 hf.co URL 時引發。
範例
>>> from huggingface_hub import model_info
>>> model_info("<non_existent_repository>")
(...)
huggingface_hub.errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP)
Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E.
Please make sure you specified the correct `repo_id` and `repo_type`.
If the repo is private, make sure you are authenticated and your token has the required permissions.
Invalid username or password.GatedRepoError
class huggingface_hub.errors.GatedRepoError
< 原始碼 >( message: str response: Response server_message: str | None = None )
當嘗試存取使用者不在授權名單中的受限儲存庫 (gated repository) 時引發。
注意:衍生自 RepositoryNotFoundError 以確保向後相容性。
範例
>>> from huggingface_hub import model_info
>>> model_info("<gated_repository>")
(...)
huggingface_hub.errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa)
Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model.
Access to model ardent-figment/gated-model is restricted and you are not in the authorized list.
Visit https://huggingface.co/ardent-figment/gated-model to ask for access.RevisionNotFoundError
class huggingface_hub.errors.RevisionNotFoundError
< 原始碼 >( message: str response: Response server_message: str | None = None )
當嘗試存取 hf.co 網址,且該儲存庫有效但修訂版本(revision)無效時觸發。
範例
>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download('bert-base-cased', 'config.json', revision='<non-existent-revision>')
(...)
huggingface_hub.errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX)
Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json.BadRequestError
class huggingface_hub.errors.BadRequestError
< 原始碼 >( message: str response: Response server_message: str | None = None )
當伺服器回傳 HTTP 400 錯誤時,由 hf_raise_for_status 觸發。
EntryNotFoundError
當在本機或遠端找不到項目時觸發。
範例
>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download('bert-base-cased', '<non-existent-file>')
(...)
huggingface_hub.errors.RemoteEntryNotFoundError (...)
>>> hf_hub_download('bert-base-cased', '<non-existent-file>', local_files_only=True)
(...)
huggingface_hub.utils.errors.LocalEntryNotFoundError (...)RemoteEntryNotFoundError
class huggingface_hub.errors.RemoteEntryNotFoundError
< 原始碼 >( message: str response: Response server_message: str | None = None )
當嘗試存取 hf.co 網址,且該儲存庫與修訂版本有效但檔案名稱無效時觸發。
範例
>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download('bert-base-cased', '<non-existent-file>')
(...)
huggingface_hub.errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x)
Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E.LocalEntryNotFoundError
當網路已停用或無法使用(連線問題)時,嘗試存取磁碟上不存在的檔案或快照時觸發。該項目可能存在於 Hub 上。
範例
>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download('bert-base-cased', '<non-cached-file>', local_files_only=True)
(...)
huggingface_hub.errors.LocalEntryNotFoundError: Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable hf.co look-ups and downloads online, set 'local_files_only' to False.OfflineModeIsEnabled
當發出請求但已將環境變數設為 HF_HUB_OFFLINE=1 時觸發。
遙測(Telemetry)
huggingface_hub 包含一個傳送遙測資料的輔助工具。此資訊有助於我們除錯並排定新功能優先順序。使用者可以隨時設定環境變數 HF_HUB_DISABLE_TELEMETRY=1 來停用遙測收集。離線模式(例如設定 HF_HUB_OFFLINE=1)下也會停用遙測。
如果您是第三方函式庫的維護者,傳送遙測資料只需簡單呼叫 send_telemetry 即可。資料會在獨立執行緒中傳送,以盡量減少對使用者的影響。
huggingface_hub.utils.send_telemetry
< 原始碼 >( topic: str library_name: str | None = None library_version: str | None = None user_agent: dict | str | None = None )
傳送有助於追蹤不同 HF 函式庫使用情形的遙測資料。
此使用資料有助於我們除錯並排定新功能優先順序。然而,我們了解並非每個人都願意分享額外資訊,我們尊重您的隱私。您可以透過將環境變數設定為 HF_HUB_DISABLE_TELEMETRY=1 來停用遙測收集。離線模式(即設定 HF_HUB_OFFLINE=1)下也會停用遙測。
遙測收集是在獨立執行緒中執行,以盡量降低對使用者的影響。
範例
>>> from huggingface_hub.utils import send_telemetry
# Send telemetry without library information
>>> send_telemetry("ping")
# Send telemetry to subtopic with library information
>>> send_telemetry("gradio/local_link", library_name="gradio", library_version="3.22.1")
# Send telemetry with additional data
>>> send_telemetry(
... topic="examples",
... library_name="transformers",
... library_version="4.26.0",
... user_agent={"pipeline": "text_classification", "framework": "flax"},
... )驗證器(Validators)
huggingface_hub 包含自訂驗證器,用於自動驗證方法參數。驗證機制靈感來自 Pydantic 的型別提示驗證,但功能較為有限。
通用裝飾器
validate_hf_hub_args() 是一個通用裝飾器,用於封裝參數符合 huggingface_hub 命名規範的方法。預設情況下,所有已實作驗證器功能的參數都將進行驗證。
如果輸入無效,將拋出 HFValidationError。只有第一個無效值會觸發錯誤並停止驗證程序。
用法
>>> from huggingface_hub.utils import validate_hf_hub_args
>>> @validate_hf_hub_args
... def my_cool_method(repo_id: str):
... print(repo_id)
>>> my_cool_method(repo_id="valid_repo_id")
valid_repo_id
>>> my_cool_method("other..repo..id")
huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.
>>> my_cool_method(repo_id="other..repo..id")
huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.validate_hf_hub_args
huggingface_hub.utils.validate_hf_hub_args
< 原始碼 >( fn: ~CallableT )
驗證 huggingface_hub 任何公開方法所接收的參數值。
此裝飾器的目標是統一各處重用的參數驗證。預設情況下,會測試所有已定義的驗證器。
驗證器
- validate_repo_id():
repo_id必須是"repo_name"或"namespace/repo_name"。命名空間(Namespace)為使用者名稱或組織名稱。 ~utils.smoothly_deprecate_legacy_arguments: 下載檔案時忽略proxies(應全域設定)。
範例
>>> from huggingface_hub.utils import validate_hf_hub_args
>>> @validate_hf_hub_args
... def my_cool_method(repo_id: str):
... print(repo_id)
>>> my_cool_method(repo_id="valid_repo_id")
valid_repo_id
>>> my_cool_method("other..repo..id")
huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.
>>> my_cool_method(repo_id="other..repo..id")
huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.HFValidationError
由 huggingface_hub 驗證器拋出的通用例外。
繼承自 ValueError。
參數驗證器
驗證器也可以單獨使用。以下是可以進行驗證的參數清單。
repo_id
驗證 repo_id 是否有效。
此舉並非為了取代 Hub 上進行的正確驗證,而是為了盡可能避免本機不一致的情形(例如:禁止在 repo_id 中傳遞 repo_type)。
規則
- 長度介於 1 到 96 個字元之間。
- 必須為 “repo_name” 或 “namespace/repo_name”。
- [a-zA-Z0-9] 或 “-”、“_”、“.”
- 禁止 “—” 和 “..”
有效範例: "foo", "foo/bar", "123", "Foo-BAR_foo.bar123"
無效範例: "datasets/foo/bar", ".repo_id", "foo--bar", "foo.git"
範例
>>> from huggingface_hub.utils import validate_repo_id
>>> validate_repo_id(repo_id="valid_repo_id")
>>> validate_repo_id(repo_id="other..repo..id")
huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'.討論詳見 https://github.com/huggingface/huggingface_hub/issues/1008。在 moon-landing (內部儲存庫) 中。
smoothly_deprecate_legacy_arguments
並非嚴格意義上的驗證器,但也同樣會執行。
huggingface_hub.utils._validators.smoothly_deprecate_legacy_arguments
< 原始碼 >( fn_name: str kwargs: dict )
平滑地棄用 huggingface_hub 程式碼庫中的遺留參數。
此函式會忽略 kwargs 中的某些已棄用參數,並警告使用者這些參數已被忽略。其目的是在不破壞現有程式碼的同時,引導使用者採用新的方式。
已棄用參數清單
proxies:若要設定代理伺服器(proxies),使用者必須使用 HTTP_PROXY 環境變數,或使用 set_client_factory() 函式手動設定httpx.Client。在 huggingface_hub 0.x 中,
proxies是一個直接傳遞給requests.request的字典。在 huggingface_hub 1.x 中,我們遷移到了httpx,它不支援以相同方式使用proxies。特別是,無法針對單一請求設定代理。解決方案是使用 set_client_factory() 函式或 HTTP_PROXY 環境變數來進行全域設定。更多詳細資訊,請參閱:
resume_download:已棄用,無替代方案。huggingface_hub會在可能的情況下自動續傳下載。force_filename:已棄用,無替代方案。檔案名稱始終與 Hub 上的一致。local_dir_use_symlinks:已棄用,無替代方案。下載至本機目錄不再使用符號連結(symlinks)。