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.FATAL
huggingface_hub.logging.ERROR
huggingface_hub.logging.WARNING
,huggingface_hub.logging.WARN
huggingface_hub.logging.INFO
huggingface_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
< 源 >( name: typing.Optional[str] = None )
全域性或針對指定組停用進度條。
此函式根據組名更新進度條的狀態。如果未提供組名,則所有進度條都被停用。此操作受 HF_HUB_DISABLE_PROGRESS_BARS
環境變數設定的限制。
enable_progress_bars
huggingface_hub.utils.enable_progress_bars
< 源 >( name: typing.Optional[str] = None )
全域性或針對指定組啟用進度條。
此函式將指定組或全域性(如果未指定組)的進度條設定為啟用狀態。此操作受 HF_HUB_DISABLE_PROGRESS_BARS
環境變數設定的限制。
配置 HTTP 後端
在某些環境中,您可能希望配置 HTTP 呼叫的方式,例如在使用代理時。huggingface_hub
允許您使用 configure_http_backend() 全域性配置此項。然後,所有對 Hub 發出的請求都將使用您的設定。在底層,huggingface_hub
使用 requests.Session
,因此您可能需要參考 requests
文件以瞭解更多可用引數。
由於 requests.Session
不保證是執行緒安全的,huggingface_hub
為每個執行緒建立一個會話例項。使用會話可以讓我們在 HTTP 呼叫之間保持連線開啟,最終節省時間。如果您正在第三方庫中整合 huggingface_hub
並希望對 Hub 進行自定義呼叫,請使用 get_session() 獲取使用者配置的會話(即,將任何 requests.get(...)
呼叫替換為 get_session().get(...)
)。
huggingface_hub.configure_http_backend
< 源 >( backend_factory: typing.Callable[[], requests.sessions.Session] = <function _default_backend_factory at 0x7fd63d769d80> )
透過提供 backend_factory
來配置 HTTP 後端。huggingface_hub
進行的任何 HTTP 呼叫都將使用此工廠例項化的 Session 物件。如果您在需要自定義配置(例如自定義代理或證書)的特定環境中執行指令碼,這會很有用。
使用 get_session() 獲取已配置的 Session。由於 requests.Session
不保證是執行緒安全的,huggingface_hub
為每個執行緒建立一個 Session 例項。它們都使用在 configure_http_backend() 中設定的相同 backend_factory
例項化。LRU 快取用於在呼叫之間快取建立的會話(和連線)。最大大小為 128,以避免在生成數千個執行緒時出現記憶體洩漏。
有關 requests
中的執行緒安全性,請參閱 此問題。
示例
import requests
from huggingface_hub import configure_http_backend, get_session
# Create a factory function that returns a Session with configured proxies
def backend_factory() -> requests.Session:
session = requests.Session()
session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"}
return session
# Set it as the default session factory
configure_http_backend(backend_factory=backend_factory)
# In practice, this is mostly done internally in `huggingface_hub`
session = get_session()
獲取 requests.Session
物件,使用使用者提供的會話工廠。
使用 get_session() 獲取已配置的 Session。由於 requests.Session
不保證是執行緒安全的,huggingface_hub
為每個執行緒建立一個 Session 例項。它們都使用在 configure_http_backend() 中設定的相同 backend_factory
例項化。LRU 快取用於在呼叫之間快取建立的會話(和連線)。最大大小為 128,以避免在生成數千個執行緒時出現記憶體洩漏。
有關 requests
中的執行緒安全性,請參閱 此問題。
示例
import requests
from huggingface_hub import configure_http_backend, get_session
# Create a factory function that returns a Session with configured proxies
def backend_factory() -> requests.Session:
session = requests.Session()
session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"}
return session
# Set it as the default session factory
configure_http_backend(backend_factory=backend_factory)
# In practice, this is mostly done internally in `huggingface_hub`
session = get_session()
處理 HTTP 錯誤
huggingface_hub
定義了自己的 HTTP 錯誤,以使用伺服器返回的附加資訊來完善 requests
引發的 HTTPError
。
引發狀態
hf_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.")
raise
huggingface_hub.utils.hf_raise_for_status
< 源 >( response: Response endpoint_name: typing.Optional[str] = None )
response.raise_for_status()
的內部版本,將完善潛在的 HTTPError。引發的異常將是 HfHubHTTPError
的例項。
此輔助函式旨在作為呼叫 Hugging Face Hub 時唯一的 raise_for_status 方法。
示例
import requests
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
請求失敗時引發
- RepositoryNotFoundError 如果找不到要下載的倉庫。這可能是因為它不存在,因為
repo_type
未正確設定,或者因為倉庫是private
且您沒有訪問許可權。 - GatedRepoError 如果倉庫存在但受到限制,並且使用者不在授權列表中。
- RevisionNotFoundError 如果倉庫存在但找不到修訂版。
- EntryNotFoundError 如果倉庫存在但找不到條目(例如請求的檔案)。
- BadRequestError 如果請求因 HTTP 400 BadRequest 錯誤而失敗。
- HfHubHTTPError 如果請求因上述未列出的原因而失敗。
HTTP 錯誤
以下是 huggingface_hub
中引發的 HTTP 錯誤列表。
HfHubHTTPError
HfHubHTTPError
是任何 HF Hub HTTP 錯誤的父類。它負責解析伺服器響應並格式化錯誤訊息,以便向用戶提供儘可能多的資訊。
class huggingface_hub.errors.HfHubHTTPError
< 源 >( message: str response: typing.Optional[requests.models.Response] = None server_message: typing.Optional[str] = None )
HF Hub 中引發的任何自定義 HTTP 錯誤的 HTTPError 父類。
任何 HTTPError 至少會轉換為 HfHubHTTPError
。如果伺服器返回了一些資訊,它將新增到錯誤訊息中。
新增的詳細資訊
- 如果存在“X-Request-Id”標頭,則為請求 ID。如果不存在,則回退到“X-Amzn-Trace-Id”標頭(如果存在)。
- 來自“X-Error-Message”標頭的伺服器錯誤訊息。
- 如果在響應正文中找到伺服器錯誤訊息。
示例
import requests
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: typing.Optional[requests.models.Response] = None server_message: typing.Optional[str] = None )
嘗試使用無效儲存庫名稱或使用者無權訪問的私有儲存庫名稱訪問 hf.co URL 時引發。
示例
>>> from huggingface_hub import model_info
>>> model_info("<non_existent_repository>")
(...)
huggingface_hub.utils._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: typing.Optional[requests.models.Response] = None server_message: typing.Optional[str] = None )
嘗試訪問使用者不在授權列表中的門控儲存庫時引發。
注意:派生自 `RepositoryNotFoundError` 以確保向後相容性。
示例
>>> from huggingface_hub import model_info
>>> model_info("<gated_repository>")
(...)
huggingface_hub.utils._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: typing.Optional[requests.models.Response] = None 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.utils._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.
EntryNotFoundError
class huggingface_hub.errors.EntryNotFoundError
< source >( message: str response: typing.Optional[requests.models.Response] = None 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.utils._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.
BadRequestError
class huggingface_hub.errors.BadRequestError
< source >( message: str response: typing.Optional[requests.models.Response] = None server_message: typing.Optional[str] = None )
當伺服器返回 HTTP 400 錯誤時,由 `hf_raise_for_status` 引發。
LocalEntryNotFoundError
當停用網路或網路不可用(連線問題)時,嘗試訪問磁碟上不存在的檔案或快照時引發。該條目可能存在於 Hub 上。
注意:`ValueError` 型別是為了確保向後相容性。注意:`LocalEntryNotFoundError` 派生自 `HTTPError`,因為它源於 `EntryNotFoundError`,即使它不是網路問題。
示例
>>> from huggingface_hub import hf_hub_download
>>> hf_hub_download('bert-base-cased', '<non-cached-file>', local_files_only=True)
(...)
huggingface_hub.utils._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` 時,如果發出請求則引發。
遙測
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[typing.Dict, str, NoneType] = 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"},
... )
驗證器
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
... def my_cool_auth_method(token: str):
... print(token)
>>> my_cool_auth_method(token="a token")
"a token"
>>> my_cool_auth_method(use_auth_token="a use_auth_token")
"a use_auth_token"
>>> my_cool_auth_method(token="a token", use_auth_token="a use_auth_token")
UserWarning: Both `token` and `use_auth_token` are passed (...). `use_auth_token` value will be ignored.
"a token"
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"`。名稱空間是使用者名稱或組織。
- smoothly_deprecate_use_auth_token():使用 `token` 代替 `use_auth_token`(僅當裝飾函式不期望 `use_auth_token` 時 - 實際上,在 `huggingface_hub` 中總是如此)。
示例
>>> 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
... def my_cool_auth_method(token: str):
... print(token)
>>> my_cool_auth_method(token="a token")
"a token"
>>> my_cool_auth_method(use_auth_token="a use_auth_token")
"a use_auth_token"
>>> my_cool_auth_method(token="a token", use_auth_token="a use_auth_token")
UserWarning: Both `token` and `use_auth_token` are passed (...)
"a token"
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_use_auth_token
不完全是驗證器,但也執行。
huggingface_hub.utils.smoothly_deprecate_use_auth_token
< source >( fn_name: str has_token: bool kwargs: typing.Dict[str, typing.Any] )
平穩地棄用 `huggingface_hub` 程式碼庫中的 `use_auth_token`。
長期目標是刪除程式碼庫中任何提及 `use_auth_token` 的地方,轉而使用一個唯一且不那麼冗長的 `token` 引數。這將分幾個步驟完成
步驟 0:需要對 Hub 進行讀訪問的方法使用 `use_auth_token` 引數(`str`、`bool` 或 `None`)。需要寫訪問的方法有一個 `token` 引數(`str`、`None`)。此隱式規則是為了在不需要時(`use_auth_token=False`)即使已登入也不傳送令牌。
步驟 1:我們希望統一所有內容併到處使用 `token`(支援只讀方法的 `token=False`)。為了不破壞現有程式碼,如果 `use_auth_token` 傳遞給函式,則 `use_auth_token` 值將作為 `token` 傳遞,不帶任何警告。a. 特殊情況:如果同時傳遞 `use_auth_token` 和 `token` 值,則丟擲警告並忽略 `use_auth_token` 值。
步驟 2:釋出後,我們應儘可能推動下游庫從 `use_auth_token` 切換到 `token`,但不丟擲警告(例如,手動在相應的倉庫上建立問題)。
步驟 3:經過過渡期(例如,6 個月,直到 2023 年 4 月?),我們更新 `huggingface_hub` 以在 `use_auth_token` 上丟擲警告。希望很少有使用者會受到影響,因為它已經修復。此外,`huggingface_hub` 中的單元測試必須適應預期會丟擲警告(但仍像以前一樣使用 `use_auth_token`)。
步驟 4:在正常的棄用週期後(3 個版本?),移除此驗證器。`use_auth_token` 將肯定不受支援。此外,我們更新 `huggingface_hub` 中的單元測試以在所有地方使用 `token`。
這已在以下討論