




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			(	UpperCAmelCase__			):







			@staticmethod
			def UpperCamelCase      (	snake_case__   :      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 snake_case__				: LoginCommand(snake_case__				)				)
									_UpperCAmelCase													=					parser.add_parser("whoami"   ,   help="Find out which huggingface.co account you are logged in as."				)
									whoami_parser.set_defaults(func=lambda snake_case__				: WhoamiCommand(snake_case__				)				)
									_UpperCAmelCase													=					parser.add_parser("logout"   ,   help="Log out"				)
									logout_parser.set_defaults(func=lambda snake_case__				: LogoutCommand(snake_case__				)				)

									# 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=snake_case__   ,   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=snake_case__   ,   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 snake_case__				: RepoCreateCommand(snake_case__				)				)






class    __lowerCAmelCase			:
			snake_case_				:			int								=					"\u001b[1m"
			snake_case_				:			Tuple								=					"\u001b[31m"
			snake_case_				:			Tuple								=					"\u001b[90m"
			snake_case_				:			List[Any]								=					"\u001b[0m"







			@classmethod
			def UpperCamelCase      (	cls   :      Optional[Any]   ,   snake_case__   :      int				):




									"""simple docstring"""


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







			@classmethod
			def UpperCamelCase      (	cls   :      Union[str, Any]   ,   snake_case__   :      List[str]				):




									"""simple docstring"""


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







			@classmethod
			def UpperCamelCase      (	cls   :      int   ,   snake_case__   :      str				):




									"""simple docstring"""


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




def 							__SCREAMING_SNAKE_CASE  (      snake_case_     ,   snake_case_						) ->    int:

						'''simple docstring'''


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






class    __lowerCAmelCase			:







			def __init__(	self   :      Union[str, Any]   ,   snake_case__   :      str				):




									"""simple docstring"""


									_UpperCAmelCase													=					args






class    __lowerCAmelCase			(	UpperCAmelCase__			):







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




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







			def UpperCamelCase      (	self   :      Union[str, 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(snake_case__				)
															print(snake_case__				)
															if orgs:
																					print(ANSI.bold("orgs: "				)   ,   ",".join(snake_case__				)				)
									except HTTPError as e:
															print(snake_case__				)
															print(ANSI.red(e.response.text				)				)
															exit(1				)






class    __lowerCAmelCase			(	UpperCAmelCase__			):







			def UpperCamelCase      (	self   :      int				):




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







			def UpperCamelCase      (	self   :      List[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(snake_case__				)
									_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(snake_case__				)}"""				)

									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(snake_case__   ,   name=self.args.name   ,   organization=self.args.organization				)
									except HTTPError as e:
															print(snake_case__				)
															print(ANSI.red(e.response.text				)				)
															exit(1				)
									print("\nYour repo now lives at:"				)
									print(F"""  {ANSI.bold(snake_case__				)}"""				)
									print("\nYou can clone it locally with the command below, and commit/push as usual."				)
									print(F"""\n  git clone {url}"""				)
									print(""				)










# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


lowercase_     :    List[Any]      =			os.path.expanduser(
    os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface'))
)
lowercase_     :    Optional[int]      =			os.path.join(hf_cache_home, 'accelerate')
lowercase_     :    int      =			os.path.join(cache_dir, 'default_config.yaml')
lowercase_     :    int      =			os.path.join(cache_dir, 'default_config.yaml')

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
				lowercase_     :    List[str]      =			default_yaml_config_file
else:
				lowercase_     :    Optional[Any]      =			default_json_config_file


def 							__SCREAMING_SNAKE_CASE  (      snake_case_						):

						'''simple docstring'''


						if config_file is not None:
												if not os.path.isfile(snake_case_						):
																		raise FileNotFoundError(
																		    f"""The passed configuration file `{config_file}` does not exist. """
																		    "Please pass an existing file to `accelerate launch`, or use the the default one "
																		    "created through `accelerate config` and run `accelerate launch` "
																		    "without the `--config_file` argument."						)
						else:
												_UpperCAmelCase													=					default_config_file
						with open(snake_case_     ,   "r"     ,   encoding="utf-8"						) as f:
												if config_file.endswith(".json"						):
																		if (
																		    json.load(snake_case_						).get("compute_environment"     ,   ComputeEnvironment.LOCAL_MACHINE						)
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								_UpperCAmelCase													=					ClusterConfig
																		else:
																								_UpperCAmelCase													=					SageMakerConfig
																		return config_class.from_json_file(json_file=snake_case_						)
												else:
																		if (
																		    yaml.safe_load(snake_case_						).get("compute_environment"     ,   ComputeEnvironment.LOCAL_MACHINE						)
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								_UpperCAmelCase													=					ClusterConfig
																		else:
																								_UpperCAmelCase													=					SageMakerConfig
																		return config_class.from_yaml_file(yaml_file=snake_case_						)






@dataclass
class    __lowerCAmelCase			:
			snake_case_				:			ComputeEnvironment
			snake_case_				:			Union[DistributedType, SageMakerDistributedType]
			snake_case_				:			str
			snake_case_				:			bool







			def UpperCamelCase      (	self   :      int				):




									"""simple docstring"""


									_UpperCAmelCase													=					self.__dict__
									# For serialization, it's best to convert Enums to strings (or their underlying value type).
									for key, value in result.items():
															if isinstance(snake_case__   ,   snake_case__				):
																					_UpperCAmelCase													=					value.value
															if isinstance(snake_case__   ,   snake_case__				) and not bool(snake_case__				):
																					_UpperCAmelCase													=					None
									_UpperCAmelCase													=					{k: v for k, v in result.items() if v is not None}
									return result







			@classmethod
			def UpperCamelCase      (	cls   :      Optional[Any]   ,   snake_case__   :      Optional[Any]=None				):




									"""simple docstring"""


									_UpperCAmelCase													=					default_json_config_file if json_file is None else json_file
									with open(snake_case__   ,   "r"   ,   encoding="utf-8"				) as f:
															_UpperCAmelCase													=					json.load(snake_case__				)
									if "compute_environment" not in config_dict:
															_UpperCAmelCase													=					ComputeEnvironment.LOCAL_MACHINE
									if "mixed_precision" not in config_dict:
															_UpperCAmelCase													=					"fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
									if "fp16" in config_dict:  # Convert the config to the new format.
															del config_dict["fp16"]
									if "dynamo_backend" in config_dict:  # Convert the config to the new format.
															_UpperCAmelCase													=					config_dict.pop("dynamo_backend"				)
															_UpperCAmelCase													=					{} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
									if "use_cpu" not in config_dict:
															_UpperCAmelCase													=					False
									return cls(**snake_case__				)







			def UpperCamelCase      (	self   :      Optional[Any]   ,   snake_case__   :      Tuple				):




									"""simple docstring"""


									with open(snake_case__   ,   "w"   ,   encoding="utf-8"				) as f:
															_UpperCAmelCase													=					json.dumps(self.to_dict()   ,   indent=2   ,   sort_keys=snake_case__				) + "\n"
															f.write(snake_case__				)







			@classmethod
			def UpperCamelCase      (	cls   :      Union[str, Any]   ,   snake_case__   :      List[str]=None				):




									"""simple docstring"""


									_UpperCAmelCase													=					default_yaml_config_file if yaml_file is None else yaml_file
									with open(snake_case__   ,   "r"   ,   encoding="utf-8"				) as f:
															_UpperCAmelCase													=					yaml.safe_load(snake_case__				)
									if "compute_environment" not in config_dict:
															_UpperCAmelCase													=					ComputeEnvironment.LOCAL_MACHINE

									if "mixed_precision" not in config_dict:
															_UpperCAmelCase													=					"fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
									if isinstance(config_dict["mixed_precision"]   ,   snake_case__				) and not config_dict["mixed_precision"]:
															_UpperCAmelCase													=					"no"
									if "fp16" in config_dict:  # Convert the config to the new format.
															del config_dict["fp16"]
									if "dynamo_backend" in config_dict:  # Convert the config to the new format.
															_UpperCAmelCase													=					config_dict.pop("dynamo_backend"				)
															_UpperCAmelCase													=					{} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
									if "use_cpu" not in config_dict:
															_UpperCAmelCase													=					False
									return cls(**snake_case__				)







			def UpperCamelCase      (	self   :      List[str]   ,   snake_case__   :      Dict				):




									"""simple docstring"""


									with open(snake_case__   ,   "w"   ,   encoding="utf-8"				) as f:
															yaml.safe_dump(self.to_dict()   ,   snake_case__				)







			def UpperCamelCase      (	self   :      Tuple				):




									"""simple docstring"""


									if isinstance(self.compute_environment   ,   snake_case__				):
															_UpperCAmelCase													=					ComputeEnvironment(self.compute_environment				)
									if isinstance(self.distributed_type   ,   snake_case__				):
															if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																					_UpperCAmelCase													=					SageMakerDistributedType(self.distributed_type				)
															else:
																					_UpperCAmelCase													=					DistributedType(self.distributed_type				)
									if self.dynamo_config is None:
															_UpperCAmelCase													=					{}






@dataclass
class    __lowerCAmelCase			(	UpperCAmelCase__			):
			snake_case_				:			int
			snake_case_				:			int								=					0
			snake_case_				:			int								=					1
			snake_case_				:			Optional[str]								=					None
			snake_case_				:			Optional[str]								=					None
			snake_case_				:			Optional[int]								=					None
			snake_case_				:			Optional[str]								=					"static"
			snake_case_				:			Optional[bool]								=					False
			snake_case_				:			str								=					"main"

			# args for deepspeed_plugin
			snake_case_				:			dict								=					None
			# args for fsdp
			snake_case_				:			dict								=					None
			# args for megatron_lm
			snake_case_				:			dict								=					None
			# args for ipex
			snake_case_				:			dict								=					None
			# args for TPU
			snake_case_				:			bool								=					False

			# args for TPU pods
			snake_case_				:			str								=					None
			snake_case_				:			str								=					None
			snake_case_				:			bool								=					False
			snake_case_				:			bool								=					False
			snake_case_				:			str								=					None
			snake_case_				:			List[str]								=					None
			snake_case_				:			List[str]								=					None
			snake_case_				:			List[str]								=					None

			# args for dynamo
			snake_case_				:			dict								=					None







			def UpperCamelCase      (	self   :      Optional[Any]				):




									"""simple docstring"""


									if self.deepspeed_config is None:
															_UpperCAmelCase													=					{}
									if self.fsdp_config is None:
															_UpperCAmelCase													=					{}
									if self.megatron_lm_config is None:
															_UpperCAmelCase													=					{}
									if self.ipex_config is None:
															_UpperCAmelCase													=					{}
									return super().__post_init__()






@dataclass
class    __lowerCAmelCase			(	UpperCAmelCase__			):
			snake_case_				:			str
			snake_case_				:			str
			snake_case_				:			Optional[str]								=					None
			snake_case_				:			Optional[str]								=					None
			snake_case_				:			str								=					"us-east-1"
			snake_case_				:			int								=					1
			snake_case_				:			str								=					"all"
			snake_case_				:			str								=					F"""accelerate-sagemaker-{num_machines}"""
			snake_case_				:			str								=					SAGEMAKER_PYTORCH_VERSION
			snake_case_				:			str								=					SAGEMAKER_TRANSFORMERS_VERSION
			snake_case_				:			str								=					SAGEMAKER_PYTHON_VERSION
			snake_case_				:			str								=					None
			snake_case_				:			str								=					None
			snake_case_				:			dict								=					None
			snake_case_				:			dict								=					None




