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`。
这已在以下讨论