



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      __lowerCAmelCase       (     snake_case_		):



			@staticmethod
			def        _lowerCamelCase			(		A  :    Union[str, Any])  ->       str:



						"""simple docstring"""






						_UpperCAmelCase									=  parser.add_parser('login'					,						help='Log in using the same credentials as on huggingface.co')
						login_parser.set_defaults(func=lambda A: 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 A: WhoamiCommand(lowerCamelCase_))
						_UpperCAmelCase									=  parser.add_parser('logout'					,						help='Log out')
						logout_parser.set_defaults(func=lambda A: 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 A: RepoCreateCommand(lowerCamelCase_))







class      __lowerCAmelCase       :
			UpperCamelCase     =	'\u001b[1m'
			UpperCamelCase     =	'\u001b[31m'
			UpperCamelCase     =	'\u001b[90m'
			UpperCamelCase     =	'\u001b[0m'



			@classmethod
			def        _lowerCamelCase			(		cls  :    str					,						A  :    Optional[Any])  ->       Dict:



						"""simple docstring"""






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



			@classmethod
			def        _lowerCamelCase			(		cls  :    str					,						A  :    List[str])  ->       str:



						"""simple docstring"""






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



			@classmethod
			def        _lowerCamelCase			(		cls  :    Optional[Any]					,						A  :    int)  ->       Tuple:



						"""simple docstring"""






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





def 				A      (	_UpperCAmelCase							:  int				,  _UpperCAmelCase							:  Union[str, Any]       )							->					Union[str, Any]:







			'''simple docstring'''
			_UpperCAmelCase									=  [max(len(str(_lowerCamelCase       )       ) for x in col       ) for col in zip(*_lowerCamelCase				,  _lowerCamelCase       )]
			_UpperCAmelCase									=  ('{{:{}}} ' * len(_lowerCamelCase       )).format(*_lowerCamelCase       )
			_UpperCAmelCase									=  []
			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      __lowerCAmelCase       :



			def __init__(		self  :    str					,						A  :    Optional[Any])  ->       Any:



						"""simple docstring"""






						_UpperCAmelCase									=  args







class      __lowerCAmelCase       (     snake_case_		):



			def        _lowerCamelCase			(		self  :    Dict)  ->       Tuple:



						"""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      __lowerCAmelCase       (     snake_case_		):



			def        _lowerCamelCase			(		self  :    int)  ->       List[str]:



						"""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									=  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      __lowerCAmelCase       (     snake_case_		):



			def        _lowerCamelCase			(		self  :    str)  ->       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      __lowerCAmelCase       (     snake_case_		):



			def        _lowerCamelCase			(		self  :    Union[str, Any])  ->       Optional[int]:



						"""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									=  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('')








"""simple docstring"""
import torch.nn as nn

from .imports import is_fpa_available


if is_fpa_available():
      import transformer_engine.pytorch as te






def 			lowerCamelCase_    (		_lowerCamelCase     ,  _lowerCamelCase=True     ,  _lowerCamelCase=True     ,  _lowerCamelCase=True							):
 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(_lowerCamelCase     ,  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
   lowerCamelCase__	:     List[Any]								=		module.bias is not None
   lowerCamelCase__	:     Tuple								=		te.Linear(
       module.in_features     ,  module.out_features     ,  bias=_lowerCamelCase     ,  params_dtype=module.weight.dtype							)
   lowerCamelCase__	:     Optional[Any]								=		module.weight.data.clone()
   if has_bias:
    lowerCamelCase__	:     List[str]								=		module.bias.data.clone()

   setattr(_lowerCamelCase     ,  _lowerCamelCase     ,  _lowerCamelCase							)
  elif isinstance(_lowerCamelCase     ,  nn.LayerNorm							) and to_transformer_engine and _convert_ln:
   lowerCamelCase__	:     Tuple								=		te.LayerNorm(module.normalized_shape[0]     ,  eps=module.eps     ,  params_dtype=module.weight.dtype							)
   lowerCamelCase__	:     Tuple								=		module.weight.data.clone()
   lowerCamelCase__	:     Optional[Any]								=		module.bias.data.clone()

   setattr(_lowerCamelCase     ,  _lowerCamelCase     ,  _lowerCamelCase							)
  elif isinstance(_lowerCamelCase     ,  te.Linear							) and not to_transformer_engine and _convert_linear:
   lowerCamelCase__	:     Optional[Any]								=		module.bias is not None
   lowerCamelCase__	:     Union[str, Any]								=		nn.Linear(
       module.in_features     ,  module.out_features     ,  bias=_lowerCamelCase     ,  params_dtype=module.weight.dtype							)
   lowerCamelCase__	:     str								=		module.weight.data.clone()
   if has_bias:
    lowerCamelCase__	:     Optional[int]								=		module.bias.data.clone()

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

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






def 			lowerCamelCase_    (		_lowerCamelCase							):
 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(_lowerCamelCase     ,  (te.LayerNorm, te.Linear)							):
   return True
 return False

