Hub Python 庫文件
實用工具
並獲得增強的文件體驗
開始使用
工具
配置日誌記錄
huggingface_hub 包提供了一個 logging 工具來控制包本身的日誌級別。您可以像這樣匯入它:
from huggingface_hub import logging然後,您可以定義詳細程度來更新您將看到的日誌量:
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。
停用庫日誌輸出的傳播。請注意,日誌傳播預設是停用的。
啟用庫日誌輸出的傳播。如果已配置根記錄器,請停用 HuggingFace Hub 的預設處理程式以防止重複日誌記錄。
倉庫特定幫助方法
下面提供的方法與修改 huggingface_hub 庫本身的模組時相關。如果您使用 huggingface_hub 並且不修改它們,則不應該需要使用這些方法。
huggingface_hub.utils.logging.get_logger
< 來源 >( name: typing.Optional[str] = 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: typing.Optional[str] = None ) → bool
檢查進度條是否已全域性停用或為特定組停用。
此函式返回進度條是全域性停用還是特定組停用。它首先檢查 HF_HUB_DISABLE_PROGRESS_BARS 環境變數,然後檢查程式化設定。
disable_progress_bars
huggingface_hub.utils.disable_progress_bars
< source >( name: typing.Optional[str] = None )
全域性或為指定組停用進度條。
此函式根據組名更新進度條的狀態。如果未提供組名,則停用所有進度條。該操作會遵循 HF_HUB_DISABLE_PROGRESS_BARS 環境變數的設定。
enable_progress_bars
huggingface_hub.utils.enable_progress_bars
< source >( name: typing.Optional[str] = None )
全域性或為指定組啟用進度條。
此函式將進度條設定為啟用狀態,適用於指定組,或者在未指定組時全域性啟用。該操作受 HF_HUB_DISABLE_PROGRESS_BARS 環境變數設定的影響。
配置 HTTP 後端
在
huggingface_hubv0.x 中,HTTP 請求由requests處理,並透過configure_http_backend進行配置。由於我們現在使用httpx,配置方式有所不同:您必須提供一個不帶引數並返回httpx.Client的工廠函式。您可以 在此處檢視預設實現,瞭解預設使用的引數。
在某些設定中,您可能需要控制 HTTP 請求的傳送方式,例如在代理後面工作時。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_client 時,將使用此客戶端工廠建立一個新的 httpx.Client 物件,該物件將在 huggingface_hub 進行的所有呼叫之間共享。
如果您在需要自定義配置的特定環境中執行指令碼(例如,自定義代理或證書),這會很有用。
使用 get_client 獲取一個已正確配置的 httpx.Client。
獲取一個 httpx.Client 物件,使用使用者提供的傳輸工廠。
此客戶端在 huggingface_hub 進行的所有呼叫之間共享。因此,您不應手動關閉它。
使用 set_client_factory() 來自定義 httpx.Client。
在極少數情況下,您可能需要手動關閉當前會話(例如,在臨時 SSLError 之後)。您可以使用 close_session() 來完成此操作。下次呼叫 get_session() 時會自動建立一個新會話。
會話在程序退出時始終會自動關閉。
對於非同步程式碼,請使用 set_async_client_factory() 配置 httpx.AsyncClient,並使用 get_async_session() 來檢索它。
huggingface_hub.set_async_client_factory
< source >( async_client_factory: typing.Callable[[], httpx.AsyncClient] )
設定 huggingface_hub 使用的 HTTP 非同步客戶端工廠。
非同步客戶端工廠是一個返回 httpx.AsyncClient 物件的函式。如果您在需要自定義配置的特定環境中執行指令碼(例如,自定義代理或證書),這會很有用。使用 get_async_client 獲取一個已正確配置的 httpx.AsyncClient。
與
httpx.Client(在huggingface_hub的所有呼叫之間共享)不同,httpx.AsyncClient不共享。建議使用非同步上下文管理器來確保客戶端在退出上下文時被正確關閉。
返回一個 httpx.AsyncClient 物件,使用使用者提供的傳輸工廠。
使用 set_async_client_factory() 來自定義 httpx.AsyncClient。
與
httpx.Client(在huggingface_hub的所有呼叫之間共享)不同,httpx.AsyncClient不共享。建議使用非同步上下文管理器來確保客戶端在退出上下文時被正確關閉。
與同步客戶端不同,非同步客戶端的生命週期不由系統自動管理。請使用非同步上下文管理器來正確處理它。
處理 HTTP 錯誤
huggingface_hub 定義了自己的 HTTP 錯誤,以完善 requests 丟擲的 HTTPError,幷包含伺服器傳送的其他資訊。
Raise for status
hf_raise_for_status() 是一個用於“raise for status”的中心方法,它適用於向 Hub 發出的任何請求。它封裝了基礎的 requests.raise_for_status,提供了額外的資訊。任何丟擲的 HTTPError 都將被轉換為 HfHubHTTPError。
import requests
from huggingface_hub.utils import hf_raise_for_status, HfHubHTTPError
response = requests.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
< source >( response: Response endpoint_name: typing.Optional[str] = None )
response.raise_for_status() 的內部版本,它將細化可能的 HTTPError。丟擲的異常將是 HfHubHTTPError 的例項。
此輔助函式旨在成為呼叫 Hugging Face Hub 時 raise_for_status 的唯一方法。
請求失敗時引發
- RepositoryNotFoundError 如果找不到要從中下載的儲存庫。這可能是因為它不存在,
repo_type未正確設定,或者儲存庫是private且您無權訪問。- GatedRepoError 如果儲存庫存在但受限制,並且使用者不在授權列表中。
- RevisionNotFoundError 如果儲存庫存在但找不到修訂版本。
- EntryNotFoundError 如果儲存庫存在但找不到條目(例如,請求的檔案)。
- BadRequestError 如果請求因 HTTP 400 BadRequest 錯誤而失敗。
- HfHubHTTPError 如果請求因上述未列出的原因而失敗。
檢查離線模式
您可以透過程式設計方式使用 is_offline_mode 檢查離線模式是否已啟用。透過設定環境變數 HF_HUB_OFFLINE=1 來啟用離線模式。
返回 Hub 是否處於離線模式。
當啟用離線模式時,使用 get_session 進行的所有 HTTP 請求都將引發 OfflineModeIsEnabled 異常。
HTTP errors
以下是 huggingface_hub 中丟擲的 HTTP 錯誤列表。
HfHubHTTPError
HfHubHTTPError 是所有 HF Hub HTTP 錯誤的父類。它負責解析伺服器響應並格式化錯誤訊息,以便為使用者提供儘可能多的資訊。
class huggingface_hub.errors.HfHubHTTPError
< source >( message: str response: Response server_message: typing.Optional[str] = None )
所有在 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
< source >( message: str response: Response server_message: typing.Optional[str] = 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.
Invalid username or password.GatedRepoError
class huggingface_hub.errors.GatedRepoError
< source >( message: str response: Response server_message: typing.Optional[str] = None )
嘗試訪問一個受保護的儲存庫,但使用者不在授權列表中時引發。
注意:為了確保向後相容性,繼承自 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
< source >( message: str response: Response server_message: typing.Optional[str] = None )
嘗試訪問具有有效儲存庫但無效修訂版本的 hf.co URL 時引發。
示例
>>> 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
< source >( message: str response: Response server_message: typing.Optional[str] = None )
當 hf_raise_for_status 引發異常,而伺服器返回 HTTP 400 錯誤時引發。
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
< source >( message: str response: Response server_message: typing.Optional[str] = None )
嘗試訪問具有有效儲存庫和修訂版本但檔名無效的 hf.co URL 時引發。
示例
>>> 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
< source >( topic: str library_name: typing.Optional[str] = None library_version: typing.Optional[str] = None user_agent: typing.Union[dict, str, NoneType] = None )
引數
- topic (
str) — 要監控的主題名稱。主題直接用於構建 URL。如果要監控子主題,請使用“/”分隔。示例:“gradio”,“transformers/examples”,... - library_name (
str, optional) — 發出 HTTP 請求的庫的名稱。將新增到 user-agent 標頭。 - library_version (
str, optional) — 發出 HTTP 請求的庫的版本。將新增到 user-agent 標頭。 - user_agent (
str,dict, optional) — 使用者代理資訊,形式為字典或單個字串。它將與已安裝包的資訊一起填寫。
傳送有助於跟蹤不同 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 的型別提示驗證工作,但功能更有限。
Generic decorator
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
< source >( 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。
Argument validators
驗證器也可以單獨使用。以下是所有可驗證的引數列表。
repo_id
驗證repo_id是否有效。
此函式並非旨在取代Hugging Face 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:要設定代理,使用者必須使用HTTP_PROXY環境變數,或者使用set_client_factory()函式手動配置httpx.Client。在huggingface_hub 0.x中,
proxies是一個直接傳遞給requests.request的字典。在huggingface_hub 1.x中,我們遷移到了httpx,它不支援與requests相同的代理方式。特別是,無法按請求配置代理。解決方案是使用set_client_factory()函式或使用HTTP_PROXY環境變數全域性配置。更多詳情,請參閱
resume_download:已棄用,無替代。huggingface_hub在可能的情況下始終會恢復下載。force_filename:已棄用,無替代。檔名始終與Hugging Face Hub上的相同。local_dir_use_symlinks:已棄用,無替代。現在下載到本地目錄不再使用符號連結。