






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	(	snake_case_    ):
     '''simple docstring'''


     @staticmethod
     def  _A				( UpperCAmelCase_				:		int					):
       SCREAMING_SNAKE_CASE				:					Tuple		  =			parser.add_parser("login"    ,       help="Log in using the same credentials as on huggingface.co"					)
       login_parser.set_defaults(func=lambda UpperCAmelCase_					: LoginCommand(A_					)					)
       SCREAMING_SNAKE_CASE				:					List[str]		  =			parser.add_parser("whoami"    ,       help="Find out which huggingface.co account you are logged in as."					)
       whoami_parser.set_defaults(func=lambda UpperCAmelCase_					: WhoamiCommand(A_					)					)
       SCREAMING_SNAKE_CASE				:					Any		  =			parser.add_parser("logout"    ,       help="Log out"					)
       logout_parser.set_defaults(func=lambda UpperCAmelCase_					: LogoutCommand(A_					)					)

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





class        SCREAMING_SNAKE_CASE	:
     '''simple docstring'''


     UpperCamelCase_							:						List[str]								=		'''\u001b[1m'''
     UpperCamelCase_							:						Tuple								=		'''\u001b[31m'''
     UpperCamelCase_							:						Optional[Any]								=		'''\u001b[90m'''
     UpperCamelCase_							:						Dict								=		'''\u001b[0m'''


     @classmethod
     def  _A				( cls				:		int    ,       UpperCAmelCase_				:		int					):
       return f'''{cls._bold}{s}{cls._reset}'''


     @classmethod
     def  _A				( cls				:		Any    ,       UpperCAmelCase_				:		int					):
       return f'''{cls._bold}{cls._red}{s}{cls._reset}'''






     @classmethod
     def  _A				( cls				:		int    ,       UpperCAmelCase_				:		Dict					):
       return f'''{cls._gray}{s}{cls._reset}'''





def      lowerCamelCase__	(   lowercase  ,   lowercase ):

  """simple docstring"""






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


class        SCREAMING_SNAKE_CASE	:
     '''simple docstring'''


     def __init__( self				:		str    ,       UpperCAmelCase_				:		str					):
       SCREAMING_SNAKE_CASE				:					Dict		  =			args





class        SCREAMING_SNAKE_CASE	(	snake_case_    ):
     '''simple docstring'''


     def  _A				( self				:		str					):
       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	(	snake_case_    ):
     '''simple docstring'''


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





class        SCREAMING_SNAKE_CASE	(	snake_case_    ):
     '''simple docstring'''


     def  _A				( self				:		Optional[Any]					):
       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	(	snake_case_    ):
     '''simple docstring'''


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

       SCREAMING_SNAKE_CASE  ,     SCREAMING_SNAKE_CASE				:					List[str]		  =			whoami(A_					)
       SCREAMING_SNAKE_CASE				:					Union[str, Any]		  =			self.args.organization if self.args.organization is not None else user
       SCREAMING_SNAKE_CASE				:					Dict		  =			f'''{namespace}/{self.args.name}'''
       print(f'''You are about to create {ANSI.bold(A_					)}'''					)

       if not self.args.yes:
         SCREAMING_SNAKE_CASE				:					str		  =			input("Proceed? [Y/n] "					).lower()
         if not (choice == "" or choice == "y" or choice == "yes"):
           print("Abort"					)
           exit()
       try:
         SCREAMING_SNAKE_CASE				:					Optional[Any]		  =			create_repo(A_    ,       name=self.args.name    ,       organization=self.args.organization					)
       except HTTPError as e:
         print(A_					)
         print(ANSI.red(e.response.text					)					)
         exit(1					)
       print("\nYour repo now lives at:"					)
       print(f'''  {ANSI.bold(A_					)}'''					)
       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 random
from typing import List, Optional, Union

import numpy as np
import torch

from ..state import AcceleratorState
from .constants import CUDA_DISTRIBUTED_TYPES
from .dataclasses import DistributedType, RNGType
from .imports import is_npu_available, is_tpu_available, is_xpu_available


if is_tpu_available(check_device=False):
						import torch_xla.core.xla_model as xm







def 						A_(			A		:						int						,			A		:						bool = False):
							if device_specific:
														seed += AcceleratorState().process_index
							random.seed(A)
							np.random.seed(A)
							torch.manual_seed(A)
							if is_xpu_available():
														torch.xpu.manual_seed_all(A)
							elif is_npu_available():
														torch.npu.manual_seed_all(A)
							else:
														torch.cuda.manual_seed_all(A)
							# ^^ safe to call this function even if cuda is not available
							if is_tpu_available():
														xm.set_rng_state(A)







def 						A_(			A		:						Optional[RNGType] = None						,			A		:						Optional[torch.Generator] = None):
							# Get the proper rng state
							if rng_type == RNGType.TORCH:
														UpperCamelCase					       =			torch.get_rng_state()
							elif rng_type == RNGType.CUDA:
														UpperCamelCase					       =			torch.cuda.get_rng_state()
							elif rng_type == RNGType.XLA:
														assert is_tpu_available(), "Can't synchronize XLA seeds on an environment without TPUs."
														UpperCamelCase					       =			torch.tensor(xm.get_rng_state())
							elif rng_type == RNGType.NPU:
														assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs."
														UpperCamelCase					       =			torch.npu.get_rng_state()
							elif rng_type == RNGType.XPU:
														assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs."
														UpperCamelCase					       =			torch.xpu.get_rng_state()
							elif rng_type == RNGType.GENERATOR:
														assert generator is not None, "Need a generator to synchronize its seed."
														UpperCamelCase					       =			generator.get_state()

							# Broadcast the rng state from device 0 to other devices
							UpperCamelCase					       =			AcceleratorState()
							if state.distributed_type == DistributedType.TPU:
														UpperCamelCase					       =			rng_state.to(xm.xla_device())
														xm.collective_broadcast([rng_state])
														xm.mark_step()
														UpperCamelCase					       =			rng_state.cpu()
							elif (
							    state.distributed_type in CUDA_DISTRIBUTED_TYPES
							    or state.distributed_type == DistributedType.MULTI_NPU
							    or state.distributed_type == DistributedType.MULTI_XPU
							):
														UpperCamelCase					       =			rng_state.to(state.device)
														torch.distributed.broadcast(A						,			0)
														UpperCamelCase					       =			rng_state.cpu()
							elif state.distributed_type == DistributedType.MULTI_CPU:
														torch.distributed.broadcast(A						,			0)

							# Set the broadcast rng state
							if rng_type == RNGType.TORCH:
														torch.set_rng_state(A)
							elif rng_type == RNGType.CUDA:
														torch.cuda.set_rng_state(A)
							elif rng_type == RNGType.NPU:
														torch.npu.set_rng_state(A)
							elif rng_type == RNGType.XPU:
														torch.xpu.set_rng_state(A)
							elif rng_type == RNGType.XLA:
														xm.set_rng_state(rng_state.item())
							elif rng_type == RNGType.GENERATOR:
														generator.set_state(A)







def 						A_(			A		:						List[Union[str, RNGType]]						,			A		:						Optional[torch.Generator] = None):
							for rng_type in rng_types:
														synchronize_rng_state(RNGType(A)						,			generator=A)




