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 SCREAMING_SNAKE_CASE_		(			lowerCAmelCase__		):







   @staticmethod
   def 	lowerCamelCase_  (    lowerCamelCase_	:	ArgumentParser							):





    """simple docstring"""


    UpperCamelCase      =			parser.add_parser("""login"""      ,      help="""Log in using the same credentials as on huggingface.co"""							)
    login_parser.set_defaults(func=lambda lowerCamelCase_							: LoginCommand(lowerCAmelCase_							)							)
    UpperCamelCase      =			parser.add_parser("""whoami"""      ,      help="""Find out which huggingface.co account you are logged in as."""							)
    whoami_parser.set_defaults(func=lambda lowerCamelCase_							: WhoamiCommand(lowerCAmelCase_							)							)
    UpperCamelCase      =			parser.add_parser("""logout"""      ,      help="""Log out"""							)
    logout_parser.set_defaults(func=lambda lowerCamelCase_							: LogoutCommand(lowerCAmelCase_							)							)

    # new system: git-based repo system
    UpperCamelCase      =			parser.add_parser(
        """repo"""      ,      help="""Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos."""      ,      )
    UpperCamelCase      =			repo_parser.add_subparsers(
        help="""Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands"""							)
    UpperCamelCase      =			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=lowerCAmelCase_      ,      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=lowerCAmelCase_      ,      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 lowerCamelCase_							: RepoCreateCommand(lowerCAmelCase_							)							)





class SCREAMING_SNAKE_CASE_		:
   __lowerCAmelCase											=							"""\u001b[1m"""
   __lowerCAmelCase											=							"""\u001b[31m"""
   __lowerCAmelCase											=							"""\u001b[90m"""
   __lowerCAmelCase											=							"""\u001b[0m"""







   @classmethod
   def 	lowerCamelCase_  (    cls	:	Optional[int]      ,      lowerCamelCase_	:	Tuple							):





    """simple docstring"""


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







   @classmethod
   def 	lowerCamelCase_  (    cls	:	Union[str, Any]      ,      lowerCamelCase_	:	Tuple							):





    """simple docstring"""


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







   @classmethod
   def 	lowerCamelCase_  (    cls	:	int      ,      lowerCamelCase_	:	List[str]							):





    """simple docstring"""


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





def  lowercase(  UpperCamelCase_       ,				UpperCamelCase_					)		->  str:







 '''simple docstring'''
 UpperCamelCase      =			[max(len(str(UpperCamelCase_					)					) for x in col					) for col in zip(*UpperCamelCase_       ,				UpperCamelCase_					)]
 UpperCamelCase      =			("""{{:{}}} """ * len(UpperCamelCase_					)).format(*UpperCamelCase_					)
 UpperCamelCase      =			[]
 lines.append(row_format.format(*UpperCamelCase_					)					)
 lines.append(row_format.format(*["""-""" * w for w in col_widths]					)					)
 for row in rows:
  lines.append(row_format.format(*UpperCamelCase_					)					)
 return "\n".join(UpperCamelCase_					)
class SCREAMING_SNAKE_CASE_		:







   def __init__(    self	:	int      ,      lowerCamelCase_	:	List[str]							):





    """simple docstring"""


    UpperCamelCase      =			args





class SCREAMING_SNAKE_CASE_		(			lowerCAmelCase__		):







   def 	lowerCamelCase_  (    self	:	Dict							):





    """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 SCREAMING_SNAKE_CASE_		(			lowerCAmelCase__		):







   def 	lowerCamelCase_  (    self	:	List[Any]							):





    """simple docstring"""


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





class SCREAMING_SNAKE_CASE_		(			lowerCAmelCase__		):







   def 	lowerCamelCase_  (    self	:	List[str]							):





    """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 SCREAMING_SNAKE_CASE_		(			lowerCAmelCase__		):







   def 	lowerCamelCase_  (    self	:	Union[str, Any]							):





    """simple docstring"""


    print(
        ANSI.red(
            """WARNING! Managing repositories through transformers-cli is deprecated. """
            """Please use `huggingface-cli` instead."""							)							)
    UpperCamelCase      =			HfFolder.get_token()
    if token is None:
     print("""Not logged in"""							)
     exit(1							)
    try:
     UpperCamelCase      =			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:
     UpperCamelCase      =			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(""""""							)

    UpperCamelCase     ,    UpperCamelCase      =			whoami(lowerCAmelCase_							)
    UpperCamelCase      =			self.args.organization if self.args.organization is not None else user
    UpperCamelCase      =			f"""{namespace}/{self.args.name}"""
    print(f"""You are about to create {ANSI.bold(lowerCAmelCase_							)}"""							)

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

import torch.nn as nn

from .imports import is_fpa_available


if is_fpa_available():
     import transformer_engine.pytorch as te





def  lowercase(  UpperCamelCase_       ,				UpperCamelCase_=True       ,				UpperCamelCase_=True       ,				UpperCamelCase_=True					)		->  int:







 '''simple docstring'''
 if not is_fpa_available():
  raise ImportError("""Using `convert_model` requires transformer_engine to be installed."""					)
 for name, module in model.named_children():
  if isinstance(UpperCamelCase_       ,				nn.Linear					) and to_transformer_engine and _convert_linear:
   # Return early if the linear layer weights are not multiples of 16
   if any(p % 16 != 0 for p in module.weight.shape					):
    return
   UpperCamelCase      =			module.bias is not None
   UpperCamelCase      =			te.Linear(
       module.in_features       ,				module.out_features       ,				bias=UpperCamelCase_       ,				params_dtype=module.weight.dtype					)
   UpperCamelCase      =			module.weight.data.clone()
   if has_bias:
    UpperCamelCase      =			module.bias.data.clone()

   setattr(UpperCamelCase_       ,				UpperCamelCase_       ,				UpperCamelCase_					)
  elif isinstance(UpperCamelCase_       ,				nn.LayerNorm					) and to_transformer_engine and _convert_ln:
   UpperCamelCase      =			te.LayerNorm(module.normalized_shape[0]       ,				eps=module.eps       ,				params_dtype=module.weight.dtype					)
   UpperCamelCase      =			module.weight.data.clone()
   UpperCamelCase      =			module.bias.data.clone()

   setattr(UpperCamelCase_       ,				UpperCamelCase_       ,				UpperCamelCase_					)
  elif isinstance(UpperCamelCase_       ,				te.Linear					) and not to_transformer_engine and _convert_linear:
   UpperCamelCase      =			module.bias is not None
   UpperCamelCase      =			nn.Linear(
       module.in_features       ,				module.out_features       ,				bias=UpperCamelCase_       ,				params_dtype=module.weight.dtype					)
   UpperCamelCase      =			module.weight.data.clone()
   if has_bias:
    UpperCamelCase      =			module.bias.data.clone()

   setattr(UpperCamelCase_       ,				UpperCamelCase_       ,				UpperCamelCase_					)
  elif isinstance(UpperCamelCase_       ,				te.LayerNorm					) and not to_transformer_engine and _convert_ln:
   UpperCamelCase      =			nn.LayerNorm(module.normalized_shape[0]       ,				eps=module.eps       ,				params_dtype=module.weight.dtype					)
   UpperCamelCase      =			module.weight.data.clone()
   UpperCamelCase      =			module.bias.data.clone()

   setattr(UpperCamelCase_       ,				UpperCamelCase_       ,				UpperCamelCase_					)
  else:
   convert_model(
       UpperCamelCase_       ,				to_transformer_engine=UpperCamelCase_       ,				_convert_linear=_convert_linear       ,				_convert_ln=_convert_ln       ,				)





def  lowercase(  UpperCamelCase_					)		->  Any:







 '''simple docstring'''
 if not is_fpa_available():
  raise ImportError("""Using `has_transformer_engine_layers` requires transformer_engine to be installed."""					)
 for m in model.modules():
  if isinstance(UpperCamelCase_       ,				(te.LayerNorm, te.Linear)					):
   return True
 return False
