constants.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import os
  2. import re
  3. import typing
  4. from typing import Literal, Optional
  5. # Possible values for env variables
  6. ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}
  7. ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})
  8. def _is_true(value: Optional[str]) -> bool:
  9. if value is None:
  10. return False
  11. return value.upper() in ENV_VARS_TRUE_VALUES
  12. def _as_int(value: Optional[str]) -> Optional[int]:
  13. if value is None:
  14. return None
  15. return int(value)
  16. # Constants for file downloads
  17. PYTORCH_WEIGHTS_NAME = "pytorch_model.bin"
  18. TF2_WEIGHTS_NAME = "tf_model.h5"
  19. TF_WEIGHTS_NAME = "model.ckpt"
  20. FLAX_WEIGHTS_NAME = "flax_model.msgpack"
  21. CONFIG_NAME = "config.json"
  22. REPOCARD_NAME = "README.md"
  23. DEFAULT_ETAG_TIMEOUT = 10
  24. DEFAULT_DOWNLOAD_TIMEOUT = 10
  25. DEFAULT_REQUEST_TIMEOUT = 10
  26. DOWNLOAD_CHUNK_SIZE = 10 * 1024 * 1024
  27. MAX_HTTP_DOWNLOAD_SIZE = 50 * 1000 * 1000 * 1000 # 50 GB
  28. # Constants for serialization
  29. PYTORCH_WEIGHTS_FILE_PATTERN = "pytorch_model{suffix}.bin" # Unsafe pickle: use safetensors instead
  30. SAFETENSORS_WEIGHTS_FILE_PATTERN = "model{suffix}.safetensors"
  31. TF2_WEIGHTS_FILE_PATTERN = "tf_model{suffix}.h5"
  32. # Constants for safetensors repos
  33. SAFETENSORS_SINGLE_FILE = "model.safetensors"
  34. SAFETENSORS_INDEX_FILE = "model.safetensors.index.json"
  35. SAFETENSORS_MAX_HEADER_LENGTH = 25_000_000
  36. # Timeout of aquiring file lock and logging the attempt
  37. FILELOCK_LOG_EVERY_SECONDS = 10
  38. # Git-related constants
  39. DEFAULT_REVISION = "main"
  40. REGEX_COMMIT_OID = re.compile(r"[A-Fa-f0-9]{5,40}")
  41. HUGGINGFACE_CO_URL_HOME = "https://huggingface.co/"
  42. _staging_mode = _is_true(os.environ.get("HUGGINGFACE_CO_STAGING"))
  43. _HF_DEFAULT_ENDPOINT = "https://huggingface.co"
  44. _HF_DEFAULT_STAGING_ENDPOINT = "https://hub-ci.huggingface.co"
  45. ENDPOINT = os.getenv("HF_ENDPOINT", _HF_DEFAULT_ENDPOINT).rstrip("/")
  46. HUGGINGFACE_CO_URL_TEMPLATE = ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
  47. if _staging_mode:
  48. ENDPOINT = _HF_DEFAULT_STAGING_ENDPOINT
  49. HUGGINGFACE_CO_URL_TEMPLATE = _HF_DEFAULT_STAGING_ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
  50. HUGGINGFACE_HEADER_X_REPO_COMMIT = "X-Repo-Commit"
  51. HUGGINGFACE_HEADER_X_LINKED_ETAG = "X-Linked-Etag"
  52. HUGGINGFACE_HEADER_X_LINKED_SIZE = "X-Linked-Size"
  53. HUGGINGFACE_HEADER_X_BILL_TO = "X-HF-Bill-To"
  54. INFERENCE_ENDPOINT = os.environ.get("HF_INFERENCE_ENDPOINT", "https://api-inference.huggingface.co")
  55. # See https://huggingface.co/docs/inference-endpoints/index
  56. INFERENCE_ENDPOINTS_ENDPOINT = "https://api.endpoints.huggingface.cloud/v2"
  57. INFERENCE_CATALOG_ENDPOINT = "https://endpoints.huggingface.co/api/catalog"
  58. # See https://api.endpoints.huggingface.cloud/#post-/v2/endpoint/-namespace-
  59. INFERENCE_ENDPOINT_IMAGE_KEYS = [
  60. "custom",
  61. "huggingface",
  62. "huggingfaceNeuron",
  63. "llamacpp",
  64. "tei",
  65. "tgi",
  66. "tgiNeuron",
  67. ]
  68. # Proxy for third-party providers
  69. INFERENCE_PROXY_TEMPLATE = "https://router.huggingface.co/{provider}"
  70. REPO_ID_SEPARATOR = "--"
  71. # ^ this substring is not allowed in repo_ids on hf.co
  72. # and is the canonical one we use for serialization of repo ids elsewhere.
  73. REPO_TYPE_DATASET = "dataset"
  74. REPO_TYPE_SPACE = "space"
  75. REPO_TYPE_MODEL = "model"
  76. REPO_TYPES = [None, REPO_TYPE_MODEL, REPO_TYPE_DATASET, REPO_TYPE_SPACE]
  77. SPACES_SDK_TYPES = ["gradio", "streamlit", "docker", "static"]
  78. REPO_TYPES_URL_PREFIXES = {
  79. REPO_TYPE_DATASET: "datasets/",
  80. REPO_TYPE_SPACE: "spaces/",
  81. }
  82. REPO_TYPES_MAPPING = {
  83. "datasets": REPO_TYPE_DATASET,
  84. "spaces": REPO_TYPE_SPACE,
  85. "models": REPO_TYPE_MODEL,
  86. }
  87. DiscussionTypeFilter = Literal["all", "discussion", "pull_request"]
  88. DISCUSSION_TYPES: tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionTypeFilter)
  89. DiscussionStatusFilter = Literal["all", "open", "closed"]
  90. DISCUSSION_STATUS: tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionStatusFilter)
  91. # Webhook subscription types
  92. WEBHOOK_DOMAIN_T = Literal["repo", "discussions"]
  93. # default cache
  94. default_home = os.path.join(os.path.expanduser("~"), ".cache")
  95. HF_HOME = os.path.expandvars(
  96. os.path.expanduser(
  97. os.getenv(
  98. "HF_HOME",
  99. os.path.join(os.getenv("XDG_CACHE_HOME", default_home), "huggingface"),
  100. )
  101. )
  102. )
  103. default_cache_path = os.path.join(HF_HOME, "hub")
  104. default_assets_cache_path = os.path.join(HF_HOME, "assets")
  105. # Legacy env variables
  106. HUGGINGFACE_HUB_CACHE = os.getenv("HUGGINGFACE_HUB_CACHE", default_cache_path)
  107. HUGGINGFACE_ASSETS_CACHE = os.getenv("HUGGINGFACE_ASSETS_CACHE", default_assets_cache_path)
  108. # New env variables
  109. HF_HUB_CACHE = os.path.expandvars(
  110. os.path.expanduser(
  111. os.getenv(
  112. "HF_HUB_CACHE",
  113. HUGGINGFACE_HUB_CACHE,
  114. )
  115. )
  116. )
  117. HF_ASSETS_CACHE = os.path.expandvars(
  118. os.path.expanduser(
  119. os.getenv(
  120. "HF_ASSETS_CACHE",
  121. HUGGINGFACE_ASSETS_CACHE,
  122. )
  123. )
  124. )
  125. HF_HUB_OFFLINE = _is_true(os.environ.get("HF_HUB_OFFLINE") or os.environ.get("TRANSFORMERS_OFFLINE"))
  126. def is_offline_mode() -> bool:
  127. """Returns whether we are in offline mode for the Hub.
  128. When offline mode is enabled, all HTTP requests made with `get_session` will raise an `OfflineModeIsEnabled` exception.
  129. Example:
  130. ```py
  131. from huggingface_hub import is_offline_mode
  132. def list_files(repo_id: str):
  133. if is_offline_mode():
  134. ... # list files from local cache (degraded experience but still functional)
  135. else:
  136. ... # list files from Hub (complete experience)
  137. ```
  138. """
  139. return HF_HUB_OFFLINE
  140. # File created to mark that the version check has been done.
  141. # Check is performed once per 24 hours at most.
  142. CHECK_FOR_UPDATE_DONE_PATH = os.path.join(HF_HOME, ".check_for_update_done")
  143. # If set, log level will be set to DEBUG and all requests made to the Hub will be logged
  144. # as curl commands for reproducibility.
  145. HF_DEBUG = _is_true(os.environ.get("HF_DEBUG"))
  146. # Opt-out from telemetry requests
  147. HF_HUB_DISABLE_TELEMETRY = (
  148. _is_true(os.environ.get("HF_HUB_DISABLE_TELEMETRY")) # HF-specific env variable
  149. or _is_true(os.environ.get("DISABLE_TELEMETRY"))
  150. or _is_true(os.environ.get("DO_NOT_TRACK")) # https://consoledonottrack.com/
  151. )
  152. HF_TOKEN_PATH = os.path.expandvars(
  153. os.path.expanduser(
  154. os.getenv(
  155. "HF_TOKEN_PATH",
  156. os.path.join(HF_HOME, "token"),
  157. )
  158. )
  159. )
  160. HF_STORED_TOKENS_PATH = os.path.join(os.path.dirname(HF_TOKEN_PATH), "stored_tokens")
  161. if _staging_mode:
  162. # In staging mode, we use a different cache to ensure we don't mix up production and staging data or tokens
  163. # In practice in `huggingface_hub` tests, we monkeypatch these values with temporary directories. The following
  164. # lines are only used in third-party libraries tests (e.g. `transformers`, `diffusers`, etc.).
  165. _staging_home = os.path.join(os.path.expanduser("~"), ".cache", "huggingface_staging")
  166. HUGGINGFACE_HUB_CACHE = os.path.join(_staging_home, "hub")
  167. HF_TOKEN_PATH = os.path.join(_staging_home, "token")
  168. # Here, `True` will disable progress bars globally without possibility of enabling it
  169. # programmatically. `False` will enable them without possibility of disabling them.
  170. # If environment variable is not set (None), then the user is free to enable/disable
  171. # them programmatically.
  172. # TL;DR: env variable has priority over code
  173. __HF_HUB_DISABLE_PROGRESS_BARS = os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS")
  174. HF_HUB_DISABLE_PROGRESS_BARS: Optional[bool] = (
  175. _is_true(__HF_HUB_DISABLE_PROGRESS_BARS) if __HF_HUB_DISABLE_PROGRESS_BARS is not None else None
  176. )
  177. # Disable warning on machines that do not support symlinks (e.g. Windows non-developer)
  178. HF_HUB_DISABLE_SYMLINKS_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_SYMLINKS_WARNING"))
  179. # Disable warning when using experimental features
  180. HF_HUB_DISABLE_EXPERIMENTAL_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_EXPERIMENTAL_WARNING"))
  181. # Disable sending the cached token by default is all HTTP requests to the Hub
  182. HF_HUB_DISABLE_IMPLICIT_TOKEN: bool = _is_true(os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN"))
  183. HF_XET_HIGH_PERFORMANCE: bool = _is_true(os.environ.get("HF_XET_HIGH_PERFORMANCE"))
  184. # hf_transfer is not used anymore. Let's warn user is case they set the env variable
  185. if _is_true(os.environ.get("HF_HUB_ENABLE_HF_TRANSFER")) and not HF_XET_HIGH_PERFORMANCE:
  186. import warnings
  187. warnings.warn(
  188. "The `HF_HUB_ENABLE_HF_TRANSFER` environment variable is deprecated as 'hf_transfer' is not used anymore. "
  189. "Please use `HF_XET_HIGH_PERFORMANCE` instead to enable high performance transfer with Xet. "
  190. "Visit https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables#hfxethighperformance for more details.",
  191. DeprecationWarning,
  192. )
  193. # Used to override the etag timeout on a system level
  194. HF_HUB_ETAG_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_ETAG_TIMEOUT")) or DEFAULT_ETAG_TIMEOUT
  195. # Used to override the get request timeout on a system level
  196. HF_HUB_DOWNLOAD_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_DOWNLOAD_TIMEOUT")) or DEFAULT_DOWNLOAD_TIMEOUT
  197. # Allows to add information about the requester in the user-agent (e.g. partner name)
  198. HF_HUB_USER_AGENT_ORIGIN: Optional[str] = os.environ.get("HF_HUB_USER_AGENT_ORIGIN")
  199. # If OAuth didn't work after 2 redirects, there's likely a third-party cookie issue in the Space iframe view.
  200. # In this case, we redirect the user to the non-iframe view.
  201. OAUTH_MAX_REDIRECTS = 2
  202. # OAuth-related environment variables injected by the Space
  203. OAUTH_CLIENT_ID = os.environ.get("OAUTH_CLIENT_ID")
  204. OAUTH_CLIENT_SECRET = os.environ.get("OAUTH_CLIENT_SECRET")
  205. OAUTH_SCOPES = os.environ.get("OAUTH_SCOPES")
  206. OPENID_PROVIDER_URL = os.environ.get("OPENID_PROVIDER_URL")
  207. # Xet constants
  208. HUGGINGFACE_HEADER_X_XET_ENDPOINT = "X-Xet-Cas-Url"
  209. HUGGINGFACE_HEADER_X_XET_ACCESS_TOKEN = "X-Xet-Access-Token"
  210. HUGGINGFACE_HEADER_X_XET_EXPIRATION = "X-Xet-Token-Expiration"
  211. HUGGINGFACE_HEADER_X_XET_HASH = "X-Xet-Hash"
  212. HUGGINGFACE_HEADER_X_XET_REFRESH_ROUTE = "X-Xet-Refresh-Route"
  213. HUGGINGFACE_HEADER_LINK_XET_AUTH_KEY = "xet-auth"
  214. default_xet_cache_path = os.path.join(HF_HOME, "xet")
  215. HF_XET_CACHE = os.getenv("HF_XET_CACHE", default_xet_cache_path)
  216. HF_HUB_DISABLE_XET: bool = _is_true(os.environ.get("HF_HUB_DISABLE_XET"))