user.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. # Copyright 2020 The HuggingFace Team. All rights reserved.
  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 commands to authenticate to the Hugging Face Hub and interact with your repositories.
  15. Usage:
  16. # login and save token locally.
  17. huggingface-cli login --token=hf_*** --add-to-git-credential
  18. # switch between tokens
  19. huggingface-cli auth switch
  20. # list all tokens
  21. huggingface-cli auth list
  22. # logout from a specific token, if no token-name is provided, all tokens will be deleted from your machine.
  23. huggingface-cli logout --token-name=your_token_name
  24. # find out which huggingface.co account you are logged in as
  25. huggingface-cli whoami
  26. """
  27. from argparse import _SubParsersAction
  28. from typing import List, Optional
  29. from requests.exceptions import HTTPError
  30. from huggingface_hub.commands import BaseHuggingfaceCLICommand
  31. from huggingface_hub.constants import ENDPOINT
  32. from huggingface_hub.hf_api import HfApi
  33. from .._login import auth_list, auth_switch, login, logout
  34. from ..utils import get_stored_tokens, get_token, logging
  35. from ._cli_utils import ANSI, show_deprecation_warning
  36. logger = logging.get_logger(__name__)
  37. try:
  38. from InquirerPy import inquirer
  39. from InquirerPy.base.control import Choice
  40. _inquirer_py_available = True
  41. except ImportError:
  42. _inquirer_py_available = False
  43. class UserCommands(BaseHuggingfaceCLICommand):
  44. @staticmethod
  45. def register_subcommand(parser: _SubParsersAction):
  46. login_parser = parser.add_parser("login", help="Log in using a token from huggingface.co/settings/tokens")
  47. login_parser.add_argument(
  48. "--token",
  49. type=str,
  50. help="Token generated from https://huggingface.co/settings/tokens",
  51. )
  52. login_parser.add_argument(
  53. "--add-to-git-credential",
  54. action="store_true",
  55. help="Optional: Save token to git credential helper.",
  56. )
  57. login_parser.set_defaults(func=lambda args: LoginCommand(args))
  58. whoami_parser = parser.add_parser("whoami", help="Find out which huggingface.co account you are logged in as.")
  59. whoami_parser.set_defaults(func=lambda args: WhoamiCommand(args))
  60. logout_parser = parser.add_parser("logout", help="Log out")
  61. logout_parser.add_argument(
  62. "--token-name",
  63. type=str,
  64. help="Optional: Name of the access token to log out from.",
  65. )
  66. logout_parser.set_defaults(func=lambda args: LogoutCommand(args))
  67. auth_parser = parser.add_parser("auth", help="Other authentication related commands")
  68. auth_subparsers = auth_parser.add_subparsers(help="Authentication subcommands")
  69. auth_switch_parser = auth_subparsers.add_parser("switch", help="Switch between access tokens")
  70. auth_switch_parser.add_argument(
  71. "--token-name",
  72. type=str,
  73. help="Optional: Name of the access token to switch to.",
  74. )
  75. auth_switch_parser.add_argument(
  76. "--add-to-git-credential",
  77. action="store_true",
  78. help="Optional: Save token to git credential helper.",
  79. )
  80. auth_switch_parser.set_defaults(func=lambda args: AuthSwitchCommand(args))
  81. auth_list_parser = auth_subparsers.add_parser("list", help="List all stored access tokens")
  82. auth_list_parser.set_defaults(func=lambda args: AuthListCommand(args))
  83. class BaseUserCommand:
  84. def __init__(self, args):
  85. self.args = args
  86. self._api = HfApi()
  87. class LoginCommand(BaseUserCommand):
  88. def run(self):
  89. show_deprecation_warning("huggingface-cli login", "hf auth login")
  90. logging.set_verbosity_info()
  91. login(
  92. token=self.args.token,
  93. add_to_git_credential=self.args.add_to_git_credential,
  94. )
  95. class LogoutCommand(BaseUserCommand):
  96. def run(self):
  97. show_deprecation_warning("huggingface-cli logout", "hf auth logout")
  98. logging.set_verbosity_info()
  99. logout(token_name=self.args.token_name)
  100. class AuthSwitchCommand(BaseUserCommand):
  101. def run(self):
  102. show_deprecation_warning("huggingface-cli auth switch", "hf auth switch")
  103. logging.set_verbosity_info()
  104. token_name = self.args.token_name
  105. if token_name is None:
  106. token_name = self._select_token_name()
  107. if token_name is None:
  108. print("No token name provided. Aborting.")
  109. exit()
  110. auth_switch(token_name, add_to_git_credential=self.args.add_to_git_credential)
  111. def _select_token_name(self) -> Optional[str]:
  112. token_names = list(get_stored_tokens().keys())
  113. if not token_names:
  114. logger.error("No stored tokens found. Please login first.")
  115. return None
  116. if _inquirer_py_available:
  117. return self._select_token_name_tui(token_names)
  118. # if inquirer is not available, use a simpler terminal UI
  119. print("Available stored tokens:")
  120. for i, token_name in enumerate(token_names, 1):
  121. print(f"{i}. {token_name}")
  122. while True:
  123. try:
  124. choice = input("Enter the number of the token to switch to (or 'q' to quit): ")
  125. if choice.lower() == "q":
  126. return None
  127. index = int(choice) - 1
  128. if 0 <= index < len(token_names):
  129. return token_names[index]
  130. else:
  131. print("Invalid selection. Please try again.")
  132. except ValueError:
  133. print("Invalid input. Please enter a number or 'q' to quit.")
  134. def _select_token_name_tui(self, token_names: List[str]) -> Optional[str]:
  135. choices = [Choice(token_name, name=token_name) for token_name in token_names]
  136. try:
  137. return inquirer.select(
  138. message="Select a token to switch to:",
  139. choices=choices,
  140. default=None,
  141. ).execute()
  142. except KeyboardInterrupt:
  143. logger.info("Token selection cancelled.")
  144. return None
  145. class AuthListCommand(BaseUserCommand):
  146. def run(self):
  147. show_deprecation_warning("huggingface-cli auth list", "hf auth list")
  148. logging.set_verbosity_info()
  149. auth_list()
  150. class WhoamiCommand(BaseUserCommand):
  151. def run(self):
  152. show_deprecation_warning("huggingface-cli whoami", "hf auth whoami")
  153. token = get_token()
  154. if token is None:
  155. print("Not logged in")
  156. exit()
  157. try:
  158. info = self._api.whoami(token)
  159. print(info["name"])
  160. orgs = [org["name"] for org in info["orgs"]]
  161. if orgs:
  162. print(ANSI.bold("orgs: "), ",".join(orgs))
  163. if ENDPOINT != "https://huggingface.co":
  164. print(f"Authenticated through private endpoint: {ENDPOINT}")
  165. except HTTPError as e:
  166. print(e)
  167. print(ANSI.red(e.response.text))
  168. exit(1)