






"""simple docstring"""





import subprocess
from argparse import ArgumentParser
from typing import List, Union

from huggingface_hub.hf_api import HfFolder, create_repo, whoami
from requests.exceptions import HTTPError

from . import BaseTransformersCLICommand







class 						_a  (		lowercase__       ):





   '''simple docstring'''






   @staticmethod
   def __lowercase							(       UpperCAmelCase_)			->   List[str]:




          '''simple docstring'''




          lowercase__:							List[Any]         =     parser.add_parser("login"					, help="Log in using the same credentials as on huggingface.co")
          login_parser.set_defaults(func=lambda UpperCAmelCase_: LoginCommand(lowercase_))
          lowercase__:							Optional[int]         =     parser.add_parser("whoami"					, help="Find out which huggingface.co account you are logged in as.")
          whoami_parser.set_defaults(func=lambda UpperCAmelCase_: WhoamiCommand(lowercase_))
          lowercase__:							Dict         =     parser.add_parser("logout"					, help="Log out")
          logout_parser.set_defaults(func=lambda UpperCAmelCase_: LogoutCommand(lowercase_))

          # new system: git-based repo system
          lowercase__:							Tuple         =     parser.add_parser(
              "repo"					, help="Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos."					, )
          lowercase__:							str         =     repo_parser.add_subparsers(
              help="Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands")
          lowercase__:							int         =     repo_subparsers.add_parser(
              "create"					, help="Deprecated: use `huggingface-cli` instead. Create a new repo on huggingface.co")
          repo_create_parser.add_argument(
              "name"					, type=lowercase_					, help="Name for your model's repo. Will be namespaced under your username to build the model id."					, )
          repo_create_parser.add_argument("--organization"					, type=lowercase_					, help="Optional: organization namespace.")
          repo_create_parser.add_argument("-y"					, "--yes"					, action="store_true"					, help="Optional: answer Yes to the prompt")
          repo_create_parser.set_defaults(func=lambda UpperCAmelCase_: RepoCreateCommand(lowercase_))







class 						_a  :





   '''simple docstring'''






   UpperCamelCase__     	=							"""\u001b[1m"""
   UpperCamelCase__     	=							"""\u001b[31m"""
   UpperCamelCase__     	=							"""\u001b[90m"""
   UpperCamelCase__     	=							"""\u001b[0m"""





   @classmethod
   def __lowercase							(       cls					, UpperCAmelCase_)			->   Union[str, Any]:




          '''simple docstring'''




          return F"""{cls._bold}{s}{cls._reset}"""





   @classmethod
   def __lowercase							(       cls					, UpperCAmelCase_)			->   Optional[int]:




          '''simple docstring'''




          return F"""{cls._bold}{cls._red}{s}{cls._reset}"""





   @classmethod
   def __lowercase							(       cls					, UpperCAmelCase_)			->   List[str]:




          '''simple docstring'''




          return F"""{cls._gray}{s}{cls._reset}"""







def 							A(    snake_case_		,  snake_case_						):
       """simple docstring"""





       lowercase__:							Optional[Any]         =     [max(len(str(__lowerCamelCase						)						) for x in col						) for col in zip(*__lowerCamelCase		,  __lowerCamelCase						)]
       lowercase__:							Optional[int]         =     ("{{:{}}} " * len(__lowerCamelCase						)).format(*__lowerCamelCase						)
       lowercase__:							List[str]         =     []
       lines.append(row_format.format(*__lowerCamelCase						)						)
       lines.append(row_format.format(*["-" * w for w in col_widths]						)						)
       for row in rows:
              lines.append(row_format.format(*__lowerCamelCase						)						)
       return "\n".join(__lowerCamelCase						)







class 						_a  :





   '''simple docstring'''






   def __init__(       self					, UpperCAmelCase_)			->   int:




          '''simple docstring'''




          lowercase__:							List[str]         =     args







class 						_a  (		lowercase__       ):





   '''simple docstring'''






   def __lowercase							(       self)			->   str:




          '''simple docstring'''




          print(
              ANSI.red(
                  "ERROR! `huggingface-cli login` uses an outdated login mechanism "
                  "that is not compatible with the Hugging Face Hub backend anymore. "
                  "Please use `huggingface-cli login instead."))







class 						_a  (		lowercase__       ):





   '''simple docstring'''






   def __lowercase							(       self)			->   Tuple:




          '''simple docstring'''




          print(
              ANSI.red(
                  "WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use "
                  "`huggingface-cli whoami` instead."))
          lowercase__:							Optional[Any]         =     HfFolder.get_token()
          if token is None:
                 print("Not logged in")
                 exit()
          try:
                 lowercase__:							List[str]         =     whoami(lowercase_)
                 print(lowercase_)
                 if orgs:
                        print(ANSI.bold("orgs: ")					, ",".join(lowercase_))
          except HTTPError as e:
                 print(lowercase_)
                 print(ANSI.red(e.response.text))
                 exit(1)







class 						_a  (		lowercase__       ):





   '''simple docstring'''






   def __lowercase							(       self)			->   List[Any]:




          '''simple docstring'''




          print(
              ANSI.red(
                  "ERROR! `transformers-cli logout` uses an outdated logout mechanism "
                  "that is not compatible with the Hugging Face Hub backend anymore. "
                  "Please use `huggingface-cli logout instead."))







class 						_a  (		lowercase__       ):





   '''simple docstring'''






   def __lowercase							(       self)			->   Tuple:




          '''simple docstring'''




          print(
              ANSI.red(
                  "WARNING! Managing repositories through transformers-cli is deprecated. "
                  "Please use `huggingface-cli` instead."))
          lowercase__:							Any         =     HfFolder.get_token()
          if token is None:
                 print("Not logged in")
                 exit(1)
          try:
                 lowercase__:							List[Any]         =     subprocess.check_output(["git", "--version"]).decode("utf-8")
                 print(ANSI.gray(stdout.strip()))
          except FileNotFoundError:
                 print("Looks like you do not have git installed, please install.")

          try:
                 lowercase__:							Union[str, Any]         =     subprocess.check_output(["git-lfs", "--version"]).decode("utf-8")
                 print(ANSI.gray(stdout.strip()))
          except FileNotFoundError:
                 print(
                     ANSI.red(
                         "Looks like you do not have git-lfs installed, please install."
                         " You can install from https://git-lfs.github.com/."
                         " Then run `git lfs install` (you only have to do this once)."))
          print("")

          lowercase__:							int         =     whoami(lowercase_)
          lowercase__:							int         =     self.args.organization if self.args.organization is not None else user
          lowercase__:							Optional[int]         =     F"""{namespace}/{self.args.name}"""
          print(F"""You are about to create {ANSI.bold(lowercase_)}""")

          if not self.args.yes:
                 lowercase__:							List[str]         =     input("Proceed? [Y/n] ").lower()
                 if not (choice == "" or choice == "y" or choice == "yes"):
                        print("Abort")
                        exit()
          try:
                 lowercase__:							Dict         =     create_repo(lowercase_					, name=self.args.name					, organization=self.args.organization)
          except HTTPError as e:
                 print(lowercase_)
                 print(ANSI.red(e.response.text))
                 exit(1)
          print("\nYour repo now lives at:")
          print(F"""  {ANSI.bold(lowercase_)}""")
          print("\nYou can clone it locally with the command below, and commit/push as usual.")
          print(F"""\n  git clone {url}""")
          print("")








"""simple docstring"""





import math
from timeit import timeit







def       __a	(						__lowerCamelCase    ):
   UpperCAmelCase_   :   Tuple     	=       0
   UpperCAmelCase_   :   Any     	=       abs(__lowerCamelCase    )
   while True:
      UpperCAmelCase_   :   Optional[int]     	=       n // 10
      digits += 1
      if n == 0:
         break
   return digits







def       __a	(						__lowerCamelCase    ):
   return 1 if n == 0 else math.floor(math.log(abs(__lowerCamelCase    ),						10    ) + 1    )







def       __a	(						__lowerCamelCase    ):
   return len(str(abs(__lowerCamelCase    )    )    )







def       __a	(						):
   from collections.abc import Callable

   def benchmark_a_function(__lowerCamelCase,						__lowerCamelCase    ) -> None:
      UpperCAmelCase_   :   Optional[Any]     	=       f"""{func.__name__}({value})"""
      UpperCAmelCase_   :   Optional[int]     	=       timeit(f"""__main__.{call}""",						setup="import __main__"    )
      print(f"""{call}: {func(__lowerCamelCase    )} -- {timing} seconds"""    )

   for value in (26_2144, 1125_8999_0684_2624, 126_7650_6002_2822_9401_4967_0320_5376):
      for func in (num_digits, num_digits_fast, num_digits_faster):
         benchmark_a_function(__lowerCamelCase,						__lowerCamelCase    )
      print()


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    benchmark()


