constants.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import os
  2. import re
  3. import typing
  4. from typing import Literal, Optional, Tuple
  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. HF_TRANSFER_CONCURRENCY = 100
  28. MAX_HTTP_DOWNLOAD_SIZE = 50 * 1000 * 1000 * 1000 # 50 GB
  29. # Constants for serialization
  30. PYTORCH_WEIGHTS_FILE_PATTERN = "pytorch_model{suffix}.bin" # Unsafe pickle: use safetensors instead
  31. SAFETENSORS_WEIGHTS_FILE_PATTERN = "model{suffix}.safetensors"
  32. TF2_WEIGHTS_FILE_PATTERN = "tf_model{suffix}.h5"
  33. # Constants for safetensors repos
  34. SAFETENSORS_SINGLE_FILE = "model.safetensors"
  35. SAFETENSORS_INDEX_FILE = "model.safetensors.index.json"
  36. SAFETENSORS_MAX_HEADER_LENGTH = 25_000_000
  37. # Timeout of aquiring file lock and logging the attempt
  38. FILELOCK_LOG_EVERY_SECONDS = 10
  39. # Git-related constants
  40. DEFAULT_REVISION = "main"
  41. REGEX_COMMIT_OID = re.compile(r"[A-Fa-f0-9]{5,40}")
  42. HUGGINGFACE_CO_URL_HOME = "https://huggingface.co/"
  43. _staging_mode = _is_true(os.environ.get("HUGGINGFACE_CO_STAGING"))
  44. _HF_DEFAULT_ENDPOINT = "https://huggingface.co"
  45. _HF_DEFAULT_STAGING_ENDPOINT = "https://hub-ci.huggingface.co"
  46. ENDPOINT = os.getenv("HF_ENDPOINT", _HF_DEFAULT_ENDPOINT).rstrip("/")
  47. HUGGINGFACE_CO_URL_TEMPLATE = ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
  48. if _staging_mode:
  49. ENDPOINT = _HF_DEFAULT_STAGING_ENDPOINT
  50. HUGGINGFACE_CO_URL_TEMPLATE = _HF_DEFAULT_STAGING_ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
  51. HUGGINGFACE_HEADER_X_REPO_COMMIT = "X-Repo-Commit"
  52. HUGGINGFACE_HEADER_X_LINKED_ETAG = "X-Linked-Etag"
  53. HUGGINGFACE_HEADER_X_LINKED_SIZE = "X-Linked-Size"
  54. HUGGINGFACE_HEADER_X_BILL_TO = "X-HF-Bill-To"
  55. INFERENCE_ENDPOINT = os.environ.get("HF_INFERENCE_ENDPOINT", "https://api-inference.huggingface.co")
  56. # See https://huggingface.co/docs/inference-endpoints/index
  57. INFERENCE_ENDPOINTS_ENDPOINT = "https://api.endpoints.huggingface.cloud/v2"
  58. INFERENCE_CATALOG_ENDPOINT = "https://endpoints.huggingface.co/api/catalog"
  59. # See https://api.endpoints.huggingface.cloud/#post-/v2/endpoint/-namespace-
  60. INFERENCE_ENDPOINT_IMAGE_KEYS = [
  61. "custom",
  62. "huggingface",
  63. "huggingfaceNeuron",
  64. "llamacpp",
  65. "tei",
  66. "tgi",
  67. "tgiNeuron",
  68. ]
  69. # Proxy for third-party providers
  70. INFERENCE_PROXY_TEMPLATE = "https://router.huggingface.co/{provider}"
  71. REPO_ID_SEPARATOR = "--"
  72. # ^ this substring is not allowed in repo_ids on hf.co
  73. # and is the canonical one we use for serialization of repo ids elsewhere.
  74. REPO_TYPE_DATASET = "dataset"
  75. REPO_TYPE_SPACE = "space"
  76. REPO_TYPE_MODEL = "model"
  77. REPO_TYPES = [None, REPO_TYPE_MODEL, REPO_TYPE_DATASET, REPO_TYPE_SPACE]
  78. SPACES_SDK_TYPES = ["gradio", "streamlit", "docker", "static"]
  79. REPO_TYPES_URL_PREFIXES = {
  80. REPO_TYPE_DATASET: "datasets/",
  81. REPO_TYPE_SPACE: "spaces/",
  82. }
  83. REPO_TYPES_MAPPING = {
  84. "datasets": REPO_TYPE_DATASET,
  85. "spaces": REPO_TYPE_SPACE,
  86. "models": REPO_TYPE_MODEL,
  87. }
  88. DiscussionTypeFilter = Literal["all", "discussion", "pull_request"]
  89. DISCUSSION_TYPES: Tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionTypeFilter)
  90. DiscussionStatusFilter = Literal["all", "open", "closed"]
  91. DISCUSSION_STATUS: Tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionStatusFilter)
  92. # Webhook subscription types
  93. WEBHOOK_DOMAIN_T = Literal["repo", "discussions"]
  94. # default cache
  95. default_home = os.path.join(os.path.expanduser("~"), ".cache")
  96. HF_HOME = os.path.expandvars(
  97. os.path.expanduser(
  98. os.getenv(
  99. "HF_HOME",
  100. os.path.join(os.getenv("XDG_CACHE_HOME", default_home), "huggingface"),
  101. )
  102. )
  103. )
  104. hf_cache_home = HF_HOME # for backward compatibility. TODO: remove this in 1.0.0
  105. default_cache_path = os.path.join(HF_HOME, "hub")
  106. default_assets_cache_path = os.path.join(HF_HOME, "assets")
  107. # Legacy env variables
  108. HUGGINGFACE_HUB_CACHE = os.getenv("HUGGINGFACE_HUB_CACHE", default_cache_path)
  109. HUGGINGFACE_ASSETS_CACHE = os.getenv("HUGGINGFACE_ASSETS_CACHE", default_assets_cache_path)
  110. # New env variables
  111. HF_HUB_CACHE = os.path.expandvars(
  112. os.path.expanduser(
  113. os.getenv(
  114. "HF_HUB_CACHE",
  115. HUGGINGFACE_HUB_CACHE,
  116. )
  117. )
  118. )
  119. HF_ASSETS_CACHE = os.path.expandvars(
  120. os.path.expanduser(
  121. os.getenv(
  122. "HF_ASSETS_CACHE",
  123. HUGGINGFACE_ASSETS_CACHE,
  124. )
  125. )
  126. )
  127. HF_HUB_OFFLINE = _is_true(os.environ.get("HF_HUB_OFFLINE") or os.environ.get("TRANSFORMERS_OFFLINE"))
  128. # If set, log level will be set to DEBUG and all requests made to the Hub will be logged
  129. # as curl commands for reproducibility.
  130. HF_DEBUG = _is_true(os.environ.get("HF_DEBUG"))
  131. # Opt-out from telemetry requests
  132. HF_HUB_DISABLE_TELEMETRY = (
  133. _is_true(os.environ.get("HF_HUB_DISABLE_TELEMETRY")) # HF-specific env variable
  134. or _is_true(os.environ.get("DISABLE_TELEMETRY"))
  135. or _is_true(os.environ.get("DO_NOT_TRACK")) # https://consoledonottrack.com/
  136. )
  137. HF_TOKEN_PATH = os.path.expandvars(
  138. os.path.expanduser(
  139. os.getenv(
  140. "HF_TOKEN_PATH",
  141. os.path.join(HF_HOME, "token"),
  142. )
  143. )
  144. )
  145. HF_STORED_TOKENS_PATH = os.path.join(os.path.dirname(HF_TOKEN_PATH), "stored_tokens")
  146. if _staging_mode:
  147. # In staging mode, we use a different cache to ensure we don't mix up production and staging data or tokens
  148. # In practice in `huggingface_hub` tests, we monkeypatch these values with temporary directories. The following
  149. # lines are only used in third-party libraries tests (e.g. `transformers`, `diffusers`, etc.).
  150. _staging_home = os.path.join(os.path.expanduser("~"), ".cache", "huggingface_staging")
  151. HUGGINGFACE_HUB_CACHE = os.path.join(_staging_home, "hub")
  152. HF_TOKEN_PATH = os.path.join(_staging_home, "token")
  153. # Here, `True` will disable progress bars globally without possibility of enabling it
  154. # programmatically. `False` will enable them without possibility of disabling them.
  155. # If environment variable is not set (None), then the user is free to enable/disable
  156. # them programmatically.
  157. # TL;DR: env variable has priority over code
  158. __HF_HUB_DISABLE_PROGRESS_BARS = os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS")
  159. HF_HUB_DISABLE_PROGRESS_BARS: Optional[bool] = (
  160. _is_true(__HF_HUB_DISABLE_PROGRESS_BARS) if __HF_HUB_DISABLE_PROGRESS_BARS is not None else None
  161. )
  162. # Disable warning on machines that do not support symlinks (e.g. Windows non-developer)
  163. HF_HUB_DISABLE_SYMLINKS_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_SYMLINKS_WARNING"))
  164. # Disable warning when using experimental features
  165. HF_HUB_DISABLE_EXPERIMENTAL_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_EXPERIMENTAL_WARNING"))
  166. # Disable sending the cached token by default is all HTTP requests to the Hub
  167. HF_HUB_DISABLE_IMPLICIT_TOKEN: bool = _is_true(os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN"))
  168. # Enable fast-download using external dependency "hf_transfer"
  169. # See:
  170. # - https://pypi.org/project/hf-transfer/
  171. # - https://github.com/huggingface/hf_transfer (private)
  172. HF_HUB_ENABLE_HF_TRANSFER: bool = _is_true(os.environ.get("HF_HUB_ENABLE_HF_TRANSFER"))
  173. # UNUSED
  174. # We don't use symlinks in local dir anymore.
  175. HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD: int = (
  176. _as_int(os.environ.get("HF_HUB_LOCAL_DIR_AUTO_SYMLINK_THRESHOLD")) or 5 * 1024 * 1024
  177. )
  178. # Used to override the etag timeout on a system level
  179. HF_HUB_ETAG_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_ETAG_TIMEOUT")) or DEFAULT_ETAG_TIMEOUT
  180. # Used to override the get request timeout on a system level
  181. HF_HUB_DOWNLOAD_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_DOWNLOAD_TIMEOUT")) or DEFAULT_DOWNLOAD_TIMEOUT
  182. # Allows to add information about the requester in the user-agent (eg. partner name)
  183. HF_HUB_USER_AGENT_ORIGIN: Optional[str] = os.environ.get("HF_HUB_USER_AGENT_ORIGIN")
  184. # List frameworks that are handled by the InferenceAPI service. Useful to scan endpoints and check which models are
  185. # deployed and running. Since 95% of the models are using the top 4 frameworks listed below, we scan only those by
  186. # default. We still keep the full list of supported frameworks in case we want to scan all of them.
  187. MAIN_INFERENCE_API_FRAMEWORKS = [
  188. "diffusers",
  189. "sentence-transformers",
  190. "text-generation-inference",
  191. "transformers",
  192. ]
  193. ALL_INFERENCE_API_FRAMEWORKS = MAIN_INFERENCE_API_FRAMEWORKS + [
  194. "adapter-transformers",
  195. "allennlp",
  196. "asteroid",
  197. "bertopic",
  198. "doctr",
  199. "espnet",
  200. "fairseq",
  201. "fastai",
  202. "fasttext",
  203. "flair",
  204. "k2",
  205. "keras",
  206. "mindspore",
  207. "nemo",
  208. "open_clip",
  209. "paddlenlp",
  210. "peft",
  211. "pyannote-audio",
  212. "sklearn",
  213. "spacy",
  214. "span-marker",
  215. "speechbrain",
  216. "stanza",
  217. "timm",
  218. ]
  219. # If OAuth didn't work after 2 redirects, there's likely a third-party cookie issue in the Space iframe view.
  220. # In this case, we redirect the user to the non-iframe view.
  221. OAUTH_MAX_REDIRECTS = 2
  222. # OAuth-related environment variables injected by the Space
  223. OAUTH_CLIENT_ID = os.environ.get("OAUTH_CLIENT_ID")
  224. OAUTH_CLIENT_SECRET = os.environ.get("OAUTH_CLIENT_SECRET")
  225. OAUTH_SCOPES = os.environ.get("OAUTH_SCOPES")
  226. OPENID_PROVIDER_URL = os.environ.get("OPENID_PROVIDER_URL")
  227. # Xet constants
  228. HUGGINGFACE_HEADER_X_XET_ENDPOINT = "X-Xet-Cas-Url"
  229. HUGGINGFACE_HEADER_X_XET_ACCESS_TOKEN = "X-Xet-Access-Token"
  230. HUGGINGFACE_HEADER_X_XET_EXPIRATION = "X-Xet-Token-Expiration"
  231. HUGGINGFACE_HEADER_X_XET_HASH = "X-Xet-Hash"
  232. HUGGINGFACE_HEADER_X_XET_REFRESH_ROUTE = "X-Xet-Refresh-Route"
  233. HUGGINGFACE_HEADER_LINK_XET_AUTH_KEY = "xet-auth"
  234. default_xet_cache_path = os.path.join(HF_HOME, "xet")
  235. HF_XET_CACHE = os.getenv("HF_XET_CACHE", default_xet_cache_path)
  236. HF_HUB_DISABLE_XET: bool = _is_true(os.environ.get("HF_HUB_DISABLE_XET"))