Hub Python Library documentation

유틸리티

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

유틸리티

로깅 구성

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.utils.logging.get_verbosity

< >

( )

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 )

매개변수

  • verbosity (int) — 로그 레벨, 예: huggingface_hub.logging.DEBUG 및 huggingface_hub.logging.INFO.

HuggingFace Hub의 루트 로거 수준을 설정합니다.

huggingface_hub.utils.logging.set_verbosity_info

< >

( )

로그 수준을 logging.INFO(으)로 설정합니다.

huggingface_hub.utils.logging.set_verbosity_debug

< >

( )

logging.DEBUG로 로그 수준을 설정합니다.

huggingface_hub.utils.logging.set_verbosity_warning

< >

( )

logging.WARNING로 심각도를 설정합니다.

huggingface_hub.utils.logging.set_verbosity_error

< >

( )

logging.ERROR로 로그 수준을 설정합니다.

huggingface_hub.utils.logging.disable_propagation

< >

( )

라이브러리 로그 출력의 전파를 비활성화합니다. 참고로 로그 전파는 기본적으로 비활성화되어 있습니다.

huggingface_hub.utils.logging.enable_propagation

< >

( )

라이브러리 로그 출력의 전파를 활성화합니다. 루트 로거가 설정된 경우 중복 로그를 방지하려면 HuggingFace Hub의 기본 핸들러를 비활성화하세요.

리포지토리별 헬퍼 메서드

huggingface_hub 라이브러리 자체의 모듈을 수정할 때 아래에 공개된 메서드들이 관련됩니다. huggingface_hub를 사용하고 모듈을 수정하지 않는다면 이 메서드들을 사용할 필요가 없습니다.

huggingface_hub.utils.logging.get_logger

< >

( name: str | None = None )

매개변수

  • name (str, 선택 사항) — 가져올 로거의 이름, 보통 파일 이름

지정된 이름을 가진 로거를 반환합니다. 이 함수는 라이브러리 사용자가 직접 접근하도록 의도된 것이 아닙니다.

예:

>>> from huggingface_hub import logging

>>> logger = logging.get_logger(__name__)
>>> logging.set_verbosity_info()

진행률 표시줄 구성

진행 상황 표시줄은 파일 다운로드 또는 업로드와 같이 시간이 오래 걸리는 작업이 실행되는 동안 사용자에게 정보를 표시하는 데 유용한 도구입니다. 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

매개변수

  • name (str, 선택 사항) — 확인할 그룹 이름입니다. None인 경우 전역 설정을 확인합니다.

반환값

bool

진행 표시줄이 비활성화되어 있으면 True, 그렇지 않으면 False입니다.

진행 표시줄이 전역적으로 또는 특정 그룹에 대해 비활성화되어 있는지 확인합니다.

이 함수는 주어진 그룹 또는 전역적으로 진행 표시줄이 비활성화되어 있는지 여부를 반환합니다. HF_HUB_DISABLE_PROGRESS_BARS 환경 변수를 먼저 확인한 후, 프로그래밍 설정을 확인합니다.

disable_progress_bars

class huggingface_hub.utils.disable_progress_bars

< >

( name: str | None = None )

매개변수

  • name (str, 선택 사항) — 진행 표시줄을 비활성화할 그룹의 이름입니다. None인 경우 진행 표시줄이 전역적으로 비활성화됩니다.

다음 예외가 발생합니다

Warning

  • Warning — 환경 변수가 변경을 방지하는 경우.

전역적으로 또는 지정된 그룹에 대해 진행 표시줄을 비활성화합니다.

이 함수는 그룹 이름에 따라 진행 막대의 상태를 업데이트합니다. 그룹 이름이 제공되지 않으면 모든 진행 막대가 비활성화됩니다. 이 작업은 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 )

매개변수

  • name (str, 선택 사항) — 진행 표시줄을 활성화할 그룹의 이름입니다. None인 경우 진행 표시줄이 전역적으로 활성화됩니다.

다음 예외가 발생합니다

Warning

  • Warning — 환경 변수가 변경을 방지하는 경우.

전역적으로 또는 지정된 그룹에 대해 진행 표시줄을 활성화합니다.

이 함수는 지정된 그룹에 대해 진행 표시줄을 활성화 상태로 설정하며, 그룹이 지정되지 않으면 전역적으로 활성화합니다. 이 작업은 HF_HUB_DISABLE_PROGRESS_BARS 환경 설정에 따라 달라집니다.

HTTP 백엔드 구성

huggingface_hub v0.x에서는 HTTP 요청을 requests로 처리하고 configure_http_backend를 통해 설정을 수행했습니다. 이제 httpx2를 사용하므로 설정 방식이 달라졌습니다. 인자를 받지 않고 httpx2.Client를 반환하는 팩토리 함수를 제공해야 합니다. 기본적으로 사용되는 매개변수를 확인하려면 기본 구현을 참고하세요.

일부 환경에서는 프록시 뒤에서 작업하는 경우와 같이 HTTP 요청이 어떻게 이루어지는지 제어해야 할 수 있습니다. huggingface_hub 라이브러리는 set_client_factory()를 사용하여 이를 전역으로 구성할 수 있습니다. 구성이 완료되면 Hub에 대한 모든 요청이 사용자 정의 설정을 사용합니다. huggingface_hub는 내부적으로 httpx2.Client에 의존하므로, 사용 가능한 매개변수에 대한 자세한 내용은 httpx2 문서를 참고하세요.

서드파티 라이브러리를 개발하고 Hub에 직접 요청을 보내야 하는 경우, get_session()을 사용하여 올바르게 구성된 httpx2 클라이언트를 가져오세요. 올바른 동작을 보장하기 위해 모든 직접적인 httpx2.get(...) 호출을 get_session().get(...)으로 교체하세요.

huggingface_hub.set_client_factory

< >

( client_factory: Callable )

huggingface_hub에서 사용할 HTTP 클라이언트 팩토리를 설정합니다.

client factory는 httpx2.Client 객체를 반환하는 메서드입니다. get_session()이 처음 호출되면 client factory가 사용되어 huggingface_hub에 의해 수행되는 모든 호출 간에 공유되는 새로운 httpx2.Client 객체가 생성됩니다.

특정 환경에서 스크립트를 실행하고 있으며, 해당 환경에 커스텀 구성(예: 커스텀 프록시 또는 인증서)이 필요한 경우 유용할 수 있습니다.

httpx2.Client을 올바르게 구성하려면 get_session()를 사용하세요.

huggingface_hub.get_session

< >

( )

사용자의 transport factory를 사용하여 httpx2.Client 객체를 가져옵니다.

이 클라이언트는 huggingface_hub이 수행하는 모든 호출 사이에 공유됩니다. 따라서 수동으로 닫지 않아야 합니다.

httpx2.Client를 사용자 정의하려면 set_client_factory()를 사용하세요.

드물게 현재 세션을 수동으로 닫아야 할 수 있습니다(예: 일시적인 SSLError 발생 후). close_session()을 사용하면 됩니다. 다음 get_session() 호출 시 새 세션이 자동으로 생성됩니다.

세션은 프로세스가 종료되면 항상 자동으로 닫힙니다.

huggingface_hub.close_session

< >

( )

huggingface_hub에서 사용하는 전역 httpx2.Client를 닫습니다.

Client가 닫힌 경우, 다음 get_session() 호출 시 다시 생성됩니다.

SSL 인증서가 업데이트된 경우와 같이 유용할 수 있습니다.

비동기 코드의 경우 set_async_client_factory()를 사용하여 httpx2.AsyncClient를 구성하고 get_async_session()을 사용하여 인스턴스를 가져옵니다.

huggingface_hub.set_async_client_factory

< >

( async_client_factory: Callable )

huggingface_hub에서 사용할 HTTP 비동기 클라이언트 팩토리를 설정합니다.

async client factory는 httpx2.AsyncClient 객체를 반환하는 메서드입니다. 스크립트를 커스텀 구성(예: 커스텀 프록시 또는 인증서)이 필요한 특정 환경에서 실행하는 경우 유용할 수 있습니다. 올바르게 구성된 httpx2.AsyncClient를 가져오려면 get_async_session()을 사용하세요.

huggingface_hub가 수행하는 모든 호출에서 공유되는 httpx2.Client와 달리, httpx2.AsyncClient는 공유되지 않습니다. 컨텍스트가 종료될 때 클라이언트가 올바르게 닫히도록 보장하기 위해 async 컨텍스트 매니저를 사용하는 것이 권장됩니다.

huggingface_hub.get_async_session

< >

( )

사용자의 transport factory를 사용하여 httpx2.AsyncClient 객체를 반환합니다.

httpx2.AsyncClient를 사용자 정의하려면 set_async_client_factory()를 사용하세요.

huggingface_hub가 수행하는 모든 호출에서 공유되는 httpx2.Client와 달리, httpx2.AsyncClient는 공유되지 않습니다. 컨텍스트가 종료될 때 클라이언트가 올바르게 닫히도록 보장하기 위해 async 컨텍스트 매니저를 사용하는 것이 권장됩니다.

동기 클라이언트와 달리 비동기 클라이언트의 라이프사이클은 자동으로 관리되지 않습니다. 이를 적절히 처리하려면 비동기 컨텍스트 매니저를 사용하세요.

httpx 모듈

huggingface_hub는 내부적으로 사용하는 HTTP 라이브러리를 huggingface_hub.utils.httpx로 재수출합니다:

from huggingface_hub.utils import httpx

try:
    ...
except httpx.HTTPError:
    ...

이 기능은 주로 huggingface_hub 위에 구축된 서드파티 라이브러리에서 유용합니다. huggingface_hub v1.x는 httpx 기반으로 구축된 반면, v2.x는 httpx2(독립된 패키지로 배포되는 후속 버전) 기반으로 구축되었습니다. httpx를 직접 가져오지 않고 huggingface_hub.utils에서 모듈을 가져오면 huggingface_hub가 실제로 사용하는 버전을 항상 사용할 수 있으며, 라이브러리가 두 주요 버전 모두와 호환되도록 유지됩니다. 마이그레이션 계획에 대한 자세한 내용은 이 이슈를 참조하세요.

httpx 타입이나 예외(예: 오류를 잡기 위해)가 필요한 경우에만 이 방법을 사용하세요. Hub에 요청을 보내려면 위에서 설명한 대로 get_session()을 사용하세요.

HTTP 오류 처리

huggingface_hub은 서버가 반환하는 추가 정보를 포함하여 httpx2가 발생시키는 HTTPError를 세분화하기 위해 자체 HTTP 오류를 정의합니다.

상태에 대한 예외 발생

hf_raise_for_status()는 Hub에 대한 모든 요청에서 “상태에 따라 예외를 발생”시키는 중심 메서드로 설계되었습니다. 추가 정보를 제공하기 위해 기본 httpx2.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.")
    raise

huggingface_hub.hf_raise_for_status

< >

( response: Responseendpoint_name: str | None = None )

매개변수

  • response (Response) — 서버에서 반환된 응답입니다.
  • endpoint_name (str, 선택 사항) — 호출된 엔드포인트의 이름입니다. 지정된 경우, 오류 메시지가 더 완전해집니다.

잠재적 HTTPError를 정제하는 response.raise_for_status()의 내부 버전입니다. raise되는 예외는 HfHubHTTPError의 인스턴스입니다.

This helper is meant to be the unique method to raise_for_status when making a call to the Hugging Face Hub.

요청이 실패하면 발생:

  • RepositoryNotFoundError 다운로드할 저장소를 찾을 수 없는 경우 발생합니다. 이는 해당 저장소가 존재하지 않거나, repo_type이 올바르게 설정되지 않았거나, 저장소가 private이고 액세스 권한이 없는 경우일 수 있습니다.
  • GatedRepoError 저장소가 존재하지만 게이트가 설정되어 있고 사용자가 승인된 목록에 없는 경우.
  • RevisionNotFoundError 저장소는 존재하지만 리비전을 찾을 수 없는 경우.
  • EntryNotFoundError 저장소는 존재하지만 항목(예: 요청된 파일)을 찾을 수 없는 경우.
  • 요청이 HTTP 400 BadRequest 오류로 실패한 경우 BadRequestError
  • HfHubHTTPError 위에서 나열되지 않은 이유로 요청이 실패한 경우.

오프라인 모드 확인

is_offline_mode를 사용하여 오프라인 모드가 활성화되어 있는지 프로그래밍 방식으로 확인할 수 있습니다. 환경 변수로 HF_HUB_OFFLINE=1을 설정하면 오프라인 모드가 활성화됩니다.

huggingface_hub.is_offline_mode

< >

( )

Hub의 오프라인 모드인지 여부를 반환합니다.

오프라인 모드가 활성화되면 get_session으로发出的 모든 HTTP 요청은 OfflineModeIsEnabled 예외를 발생시킵니다.

예:

from huggingface_hub import is_offline_mode

def list_files(repo_id: str):
    if is_offline_mode():
        ... # list files from local cache (degraded experience but still functional)
    else:
        ... # list files from Hub (complete experience)

HTTP 오류

huggingface_hub에서 발생 가능한 HTTP 오류 목록입니다.

HfHubHTTPError

HfHubHTTPError는 HF Hub HTTP 오류의 상위 클래스입니다. 서버 응답을 파싱하고 오류 메시지를 포맷팅하여 사용자에게 가능한 한 많은 정보를 제공합니다.

클래스 huggingface_hub.errors.HfHubHTTPError

< >

( message: strresponse: Responseserver_message: str | None = None )

HF Hub에서 발생하는 모든 사용자 정의 HTTP 오류를 상속하기 위한 HTTPError.

모든 HTTPError는 최소한 HfHubHTTPError로 변환됩니다. 서버가 일부 정보를 반환하는 경우, 해당 정보가 오류 메시지에 추가됩니다.

추가된 세부 정보:

  • 요청 ID는 우선순위 순서대로 헤더에서 가져옵니다: “X-Request-Id”, “X-Amzn-Trace-Id”, “X-Amz-Cf-Id”.
  • 헤더 “X-Error-Message”의 서버 오류 메시지.
  • 응답 본문에서 서버 오류 메시지를 찾을 수 있는 경우 해당 메시지를 반환합니다.

예:

    import httpx2
    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

append_to_message

< >

( additional_message: str )

HfHubHTTPError 초기 메시지에 추가 정보를 붙입니다.

RepositoryNotFoundError

클래스 huggingface_hub.errors.RepositoryNotFoundError

< >

( message: strresponse: Responseserver_message: str | None = None )

매개변수

  • repo_id (str 또는 None) — 요청 URL에서 결정할 수 있는 경우, 찾을 수 없었던 저장소 ID입니다.
  • repo_type (str 또는 None) — 요청 URL에서 판단할 수 있는 경우, 저장소 유형("model", "dataset", 또는 "space").

잘못된 저장소 이름으로 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

클래스 huggingface_hub.errors.GatedRepoError

< >

( message: strresponse: Responseserver_message: str | None = 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

클래스 huggingface_hub.errors.RevisionNotFoundError

< >

( message: strresponse: Responseserver_message: str | None = None )

매개변수

  • repo_id (str 또는 None) — 요청 URL에서 결정할 수 있는 경우의 저장소 ID입니다.
  • repo_type (str 또는 None) — 요청 URL에서 판단할 수 있는 경우, 저장소 유형("model", "dataset", 또는 "space").

유효한 저장소이지만 잘못된 revision으로 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.

RevisionResolutionError

클래스 huggingface_hub.errors.RevisionResolutionError

< >

( )

HfApi.resolve_revision()에서 리비전이 커밋 해시로 해석되지 못할 때 발생: Hub에 접근할 수 없는 경우(오프라인 모드, 연결 오류, 타임아웃, Hub 장애 등)이고 로컬 캐시에서 일치하는 항목을 찾지 못한 경우입니다.

BadRequestError

클래스 huggingface_hub.errors.BadRequestError

< >

( message: strresponse: Responseserver_message: str | None = None )

서버가 HTTP 400 오류를 반환할 때 hf_raise_for_status에 의해 발생됩니다.

예:

>>> resp = httpx2.post("hf.co/api/check", ...)
>>> hf_raise_for_status(resp, endpoint_name="check")
huggingface_hub.errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX)

EntryNotFoundError

클래스 huggingface_hub.errors.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

클래스 huggingface_hub.errors.RemoteEntryNotFoundError

< >

( message: strresponse: Responseserver_message: str | None = None )

매개변수

  • repo_id (str 또는 None) — 요청 URL에서 결정할 수 있는 경우의 저장소 ID입니다.
  • repo_type (str 또는 None) — 요청 URL에서 판단할 수 있는 경우, 저장소 유형("model", "dataset", 또는 "space").

유효한 저장소와 리비전이 있는 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

class huggingface_hub.errors.LocalEntryNotFoundError

< >

( message: str )

네트워크가 비활성화되었거나 사용할 수 없는 경우(연결 문제) 디스크에 없는 파일 또는 스냅샷에 액세스하려고 할 때 발생하며, 해당 항목은 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.

IncompleteSnapshotError

클래스 huggingface_hub.errors.IncompleteSnapshotError

< >

( message: strsnapshot_path: str )

Hub에 연결할 수 없는 경우(오프라인, 연결 문제 또는 local_files_only=True)에 snapshot_download()가 발생시키며, 캐시된 스냅샷이 불완전한 것으로 알려진 상황에서 발생합니다: 저장소의 캐시된 트리 목록에 나열된 일부 파일이 로컬 스냅샷에서 누락되어 있습니다.

이것은 하위 호환성을 위해 LocalEntryNotFoundError의 하위 클래스입니다.

snapshot_path 속성은 불완전한 로컬 스냅샷의 경로를 저장하므로, 해당 파일들이 불완전하다는 것이 알려져 있더라도 하위 라이브러리가 최신 캐시된 파일을 찾을 수 있습니다.

CachedRepoTreeNotFoundError

클래스 huggingface_hub.errors.CachedRepoTreeNotFoundError

< >

( )

요청된 리비전의 트리 목록이 캐시에 없을 때 get_cached_repo_tree()에서 발생됩니다.

트리 목록은 snapshot_download()의 부수 효과로 생성됩니다.

OfflineModeIsEnabled

class huggingface_hub.errors.OfflineModeIsEnabled

< >

( )

요청이 이루어졌지만 환경 변수로 HF_HUB_OFFLINE=1이 설정된 경우 발생합니다.

텔레메트리

huggingface_hub에는 텔레메트리 데이터를 전송하는 헬퍼가 포함되어 있습니다. 이 정보는 문제를 디버깅하고 새로운 기능을 우선순위에 두는 데 도움이 됩니다. 사용자는 HF_HUB_DISABLE_TELEMETRY=1 환경 변수를 설정하여 언제든지 텔레메트리 수집을 비활성화할 수 있습니다. 오프라인 모드(즉, HF_HUB_OFFLINE=1을 설정한 경우)에서도 텔레메트리가 비활성화됩니다.

세 번째 당사 라이브러리의 유지보수자라면, send_telemetry를 호출하는 것만으로 텔레메트리 데이터를 전송할 수 있습니다. 데이터는 별도의 스레드에서 전송되어 사용자에 미치는 영향을 최대한 줄입니다.

huggingface_hub.utils.send_telemetry

< >

( topic: strlibrary_name: str | None = Nonelibrary_version: str | None = Noneuser_agent: dict | str | None = None )

매개변수

  • topic (str) — 모니터링할 토픽의 이름입니다. 토픽은 URL을 구성하는 데 직접 사용됩니다. 서브토픽을 모니터링하려면 “/”로 구분하여 사용하세요. 예: “gradio”, “transformers/examples”,…
  • library_name (str, 선택 사항) — HTTP 요청을 보내는 라이브러리의 이름입니다. user-agent 헤더에 추가됩니다.
  • library_version (str, 선택 사항) — HTTP 요청을 보내는 라이브러리의 버전입니다. user-agent 헤더에 추가됩니다.
  • user_agent (str, dict, 선택 사항) — 사전 또는 단일 문자열 형태의 사용자 에이전트 정보입니다. 설치된 패키지에 대한 정보로 보완됩니다.

각종 HF 라이브러리의 사용량을 추적하는 데 도움이 되는 텔레메트리를 전송합니다.

이 사용 데이터는 문제를 디버깅하고 새로운 기능을 우선순위에 두는 데 도움이 됩니다. 그러나 모든 사용자가 추가 정보를 공유하기를 원하지는 않는다는 점을 이해하며, 여러분의 프라이버시를 존중합니다. HF_HUB_DISABLE_TELEMETRY=1을 환경 변수로 설정하여 텔레메트리 수집을 비활성화할 수 있습니다. 오프라인 모드(즉, HF_HUB_OFFLINE=1을 설정한 경우)에서도 텔레메트리가 비활성화됩니다.

Telemetry collection은 사용자에 대한 영향을 최소화하기 위해 별도의 스레드에서 실행됩니다.

예:

>>> 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

huggingface_hub.utils.validate_hf_hub_args

< >

( fn: ~CallableT )

다음 예외가 발생합니다

HFValidationError

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.errors.HFValidationError

< >

( )

huggingface_hub 검증기가 throw하는 일반적인 예외입니다.

ValueError에서 상속됩니다.

인수 검증기

Validators는 개별적으로도 사용할 수 있습니다. 아래는 검증할 수 있는 모든 인수의 목록입니다.

repo_id

huggingface_hub.utils.validate_repo_id

< >

( repo_id: str | None )

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: strkwargs: dict )

huggingface_hub 코드베이스에서 레거시 인수를 부드럽게 비활성화합니다.

이 함수는 kwargs에서 일부 비추천(deprecated)된 인수를 무시하고, 해당 인수가 무시됨을 사용자에게 경고합니다. 기존 코드의 동작을 깨뜨리지 않으면서도 사용자에게 새로운 사용법을 안내하는 것이 목표입니다.

비추천 인자 목록:

  • proxies: 프록시를 설정하려면 사용자는 HTTP_PROXY 환경 변수를 사용하거나 set_client_factory() 함수를 사용하여 httpx2.Client를 수동으로 구성해야 합니다.

    huggingface_hub 0.x에서는 proxies가 requests.request에 직접 전달되는 사전(dictionary)이었습니다. huggingface_hub 1.x부터 요청별 proxies는 더 이상 지원되지 않습니다. 특히, 요청별로 프록시를 구성할 수 없습니다. set_client_factory() 함수를 사용하거나 HTTP_PROXY 환경 변수를 사용하여 전역으로 구성하는 것이 해결책입니다.

    자세한 내용은 다음을 참조하세요:

  • resume_download: 대체 항목 없이 비추천으로 변경되었습니다. huggingface_hub는 항상 가능한 경우 다운로드를 재개합니다.

  • force_filename: 대체 항목 없이 비활성화되었습니다. 파일 이름은 항상 Hub와 동일합니다.

  • local_dir_use_symlinks: 대체 수단 없이 비활성화되었습니다. 로컬 디렉터리로 다운로드할 때 더 이상 심볼릭 링크를 사용하지 않습니다.

Update on GitHub