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
< source >( verbosity: int )
设置 HuggingFace Hub 根记录器的级别。
将详细程度设置为 logging.INFO
。
将详细程度设置为 logging.DEBUG
。
将详细程度设置为 logging.WARNING
。
将详细程度设置为 logging.ERROR
。
禁用库日志输出的传播。请注意,默认情况下禁用日志传播。
启用库日志输出的传播。如果根记录器已配置,请禁用 HuggingFace Hub 的默认处理程序以防止重复日志记录。
仓库特定的辅助方法
下面公开的方法与修改 huggingface_hub
库本身的模块相关。如果您使用 huggingface_hub
并且不修改它们,则无需使用这些方法。
huggingface_hub.utils.logging.get_logger
< source >( 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
< source >( 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
环境设置的约束。
Configure HTTP backend
在某些环境中,您可能希望配置 HTTP 调用的方式,例如,如果您正在使用代理。huggingface_hub
允许您使用 configure_http_backend() 全局配置此项。然后,对 Hub 发出的所有请求都将使用您的设置。在底层,huggingface_hub
使用 requests.Session
,因此您可能需要参考 requests
文档,以了解有关可用参数的更多信息。
由于 requests.Session
不能保证线程安全,huggingface_hub
为每个线程创建一个会话实例。使用会话使我们能够在 HTTP 调用之间保持连接打开,并最终节省时间。如果您正在将 huggingface_hub
集成到第三方库中,并且想要对 Hub 进行自定义调用,请使用 get_session() 获取由您的用户配置的 Session(即,将任何 requests.get(...)
调用替换为 get_session().get(...)
)。
huggingface_hub.configure_http_backend
< source >( backend_factory: typing.Callable[[], requests.sessions.Session] = <function _default_backend_factory at 0x7f61ccaa81f0> )
通过提供 backend_factory
来配置 HTTP 后端。huggingface_hub
发出的任何 HTTP 调用都将使用由此工厂实例化的 Session 对象。如果您在需要自定义配置的特定环境中(例如,自定义代理或证书)运行脚本,这将非常有用。
使用 get_session() 获取配置的 Session。由于 requests.Session
不能保证线程安全,因此 huggingface_hub
为每个线程创建 1 个 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
为每个线程创建 1 个 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
。
Raise for status
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
< source >( 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
< source >( 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
< source >( 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
设置为环境变量时引发。
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[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"},
... )
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
... 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
,但不要发出警告(例如,在相应的仓库上手动创建 issue)。步骤 3:经过一段过渡期(例如 6 个月,直到 2023 年 4 月?),我们更新 `huggingface_hub` 以在 `use_auth_token` 上发出警告。 希望影响的用户非常少,因为它应该已经被修复。 此外,`huggingface_hub` 中的单元测试必须进行调整,以预期会发出警告(但仍然像以前一样使用 `use_auth_token`)。
步骤 4:经过正常的弃用周期(3 个版本?),移除此验证器。 `use_auth_token` 将明确不再支持。 此外,我们更新 `huggingface_hub` 中的单元测试,以便在所有地方都使用 `token`。
这已在以下链接中讨论过: