_headers.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. # Copyright 2022-present, the HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Contains utilities to handle headers to send in calls to Huggingface Hub."""
  15. from huggingface_hub.errors import LocalTokenNotFoundError
  16. from .. import constants
  17. from ._auth import get_token
  18. from ._detect_agent import detect_agent
  19. from ._runtime import (
  20. get_hf_hub_version,
  21. get_python_version,
  22. get_torch_version,
  23. is_torch_available,
  24. )
  25. from ._validators import validate_hf_hub_args
  26. @validate_hf_hub_args
  27. def build_hf_headers(
  28. *,
  29. token: bool | str | None = None,
  30. library_name: str | None = None,
  31. library_version: str | None = None,
  32. user_agent: dict | str | None = None,
  33. headers: dict[str, str] | None = None,
  34. ) -> dict[str, str]:
  35. """
  36. Build headers dictionary to send in a HF Hub call.
  37. By default, authorization token is always provided either from argument (explicit
  38. use) or retrieved from the cache (implicit use). To explicitly avoid sending the
  39. token to the Hub, set `token=False` or set the `HF_HUB_DISABLE_IMPLICIT_TOKEN`
  40. environment variable.
  41. In case of an API call that requires write access, an error is thrown if token is
  42. `None` or token is an organization token (starting with `"api_org***"`).
  43. In addition to the auth header, a user-agent is added to provide information about
  44. the installed packages (versions of python, huggingface_hub, torch).
  45. Args:
  46. token (`str`, `bool`, *optional*):
  47. The token to be sent in authorization header for the Hub call:
  48. - if a string, it is used as the Hugging Face token
  49. - if `True`, the token is read from the machine (cache or env variable)
  50. - if `False`, authorization header is not set
  51. - if `None`, the token is read from the machine only except if
  52. `HF_HUB_DISABLE_IMPLICIT_TOKEN` env variable is set.
  53. library_name (`str`, *optional*):
  54. The name of the library that is making the HTTP request. Will be added to
  55. the user-agent header.
  56. library_version (`str`, *optional*):
  57. The version of the library that is making the HTTP request. Will be added
  58. to the user-agent header.
  59. user_agent (`str`, `dict`, *optional*):
  60. The user agent info in the form of a dictionary or a single string. It will
  61. be completed with information about the installed packages.
  62. headers (`dict`, *optional*):
  63. Additional headers to include in the request. Those headers take precedence
  64. over the ones generated by this function.
  65. Returns:
  66. A `dict` of headers to pass in your API call.
  67. Example:
  68. ```py
  69. >>> build_hf_headers(token="hf_***") # explicit token
  70. {"authorization": "Bearer hf_***", "user-agent": ""}
  71. >>> build_hf_headers(token=True) # explicitly use cached token
  72. {"authorization": "Bearer hf_***",...}
  73. >>> build_hf_headers(token=False) # explicitly don't use cached token
  74. {"user-agent": ...}
  75. >>> build_hf_headers() # implicit use of the cached token
  76. {"authorization": "Bearer hf_***",...}
  77. # HF_HUB_DISABLE_IMPLICIT_TOKEN=True # to set as env variable
  78. >>> build_hf_headers() # token is not sent
  79. {"user-agent": ...}
  80. >>> build_hf_headers(library_name="transformers", library_version="1.2.3")
  81. {"authorization": ..., "user-agent": "transformers/1.2.3; hf_hub/0.10.2; python/3.10.4; tensorflow/1.55"}
  82. ```
  83. Raises:
  84. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  85. If organization token is passed and "write" access is required.
  86. [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  87. If "write" access is required but token is not passed and not saved locally.
  88. [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
  89. If `token=True` but token is not saved locally.
  90. """
  91. # Get auth token to send
  92. token_to_send = get_token_to_send(token)
  93. # Combine headers
  94. hf_headers = {
  95. "user-agent": _http_user_agent(
  96. library_name=library_name,
  97. library_version=library_version,
  98. user_agent=user_agent,
  99. )
  100. }
  101. if token_to_send is not None:
  102. hf_headers["authorization"] = f"Bearer {token_to_send}"
  103. if headers is not None:
  104. hf_headers.update(headers)
  105. return hf_headers
  106. def get_token_to_send(token: bool | str | None) -> str | None:
  107. """Select the token to send from either `token` or the cache."""
  108. # Case token is explicitly provided
  109. if isinstance(token, str):
  110. return token
  111. # Case token is explicitly forbidden
  112. if token is False:
  113. return None
  114. # Token is not provided: we get it from local cache
  115. cached_token = get_token()
  116. # Case token is explicitly required
  117. if token is True:
  118. if cached_token is None:
  119. raise LocalTokenNotFoundError(
  120. "Token is required (`token=True`), but no token found. You"
  121. " need to provide a token or be logged in to Hugging Face with"
  122. " `hf auth login` or `huggingface_hub.login`. See"
  123. " https://huggingface.co/settings/tokens."
  124. )
  125. return cached_token
  126. # Case implicit use of the token is forbidden by env variable
  127. if constants.HF_HUB_DISABLE_IMPLICIT_TOKEN:
  128. return None
  129. # Otherwise: we use the cached token as the user has not explicitly forbidden it
  130. return cached_token
  131. def _http_user_agent(
  132. *,
  133. library_name: str | None = None,
  134. library_version: str | None = None,
  135. user_agent: dict | str | None = None,
  136. ) -> str:
  137. """Format a user-agent string containing information about the installed packages.
  138. Args:
  139. library_name (`str`, *optional*):
  140. The name of the library that is making the HTTP request.
  141. library_version (`str`, *optional*):
  142. The version of the library that is making the HTTP request.
  143. user_agent (`str`, `dict`, *optional*):
  144. The user agent info in the form of a dictionary or a single string.
  145. Returns:
  146. The formatted user-agent string.
  147. """
  148. if library_name is not None:
  149. ua = f"{library_name}/{library_version}"
  150. else:
  151. ua = "unknown/None"
  152. ua += f"; hf_hub/{get_hf_hub_version()}"
  153. ua += f"; python/{get_python_version()}"
  154. if not constants.HF_HUB_DISABLE_TELEMETRY:
  155. if is_torch_available():
  156. ua += f"; torch/{get_torch_version()}"
  157. agent = detect_agent()
  158. if agent:
  159. ua += f"; agent/{agent}"
  160. if isinstance(user_agent, dict):
  161. ua += "; " + "; ".join(f"{k}/{v}" for k, v in user_agent.items())
  162. elif isinstance(user_agent, str):
  163. ua += "; " + user_agent
  164. # Retrieve user-agent origin headers from environment variable
  165. origin = constants.HF_HUB_USER_AGENT_ORIGIN
  166. if origin is not None:
  167. ua += "; origin/" + origin
  168. return _deduplicate_user_agent(ua)
  169. def _deduplicate_user_agent(user_agent: str) -> str:
  170. """Deduplicate redundant information in the generated user-agent."""
  171. # Split around ";" > Strip whitespaces > Store as dict keys (ensure unicity) > format back as string
  172. # Order is implicitly preserved by dictionary structure (see https://stackoverflow.com/a/53657523).
  173. return "; ".join({key.strip(): None for key in user_agent.split(";")}.keys())