






# 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


UpperCAmelCase     				=			os.path.expanduser(
    os.getenv('''HF_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''huggingface'''))
)
UpperCAmelCase     				=			os.path.join(hf_cache_home, '''accelerate''')
UpperCAmelCase     				=			os.path.join(cache_dir, '''default_config.yaml''')
UpperCAmelCase     				=			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):
	UpperCAmelCase     				=			default_yaml_config_file
else:
	UpperCAmelCase     				=			default_json_config_file






def 							UpperCAmelCase_		(							__SCREAMING_SNAKE_CASE							):
	if config_file is not None:
		if not os.path.isfile(__SCREAMING_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:
		lowercase					  =   default_config_file
	with open(__SCREAMING_SNAKE_CASE			,							'r'			,							encoding='utf-8'							) as f:
		if config_file.endswith('.json'							):
			if (
			    json.load(__SCREAMING_SNAKE_CASE							).get('compute_environment'			,							ComputeEnvironment.LOCAL_MACHINE							)
			    == ComputeEnvironment.LOCAL_MACHINE
			):
				lowercase					  =   ClusterConfig
			else:
				lowercase					  =   SageMakerConfig
			return config_class.from_json_file(json_file=__SCREAMING_SNAKE_CASE							)
		else:
			if (
			    yaml.safe_load(__SCREAMING_SNAKE_CASE							).get('compute_environment'			,							ComputeEnvironment.LOCAL_MACHINE							)
			    == ComputeEnvironment.LOCAL_MACHINE
			):
				lowercase					  =   ClusterConfig
			else:
				lowercase					  =   SageMakerConfig
			return config_class.from_yaml_file(yaml_file=__SCREAMING_SNAKE_CASE							)







@dataclass
class 	A_       :




	'''simple docstring'''


	_UpperCamelCase					:					ComputeEnvironment
	_UpperCamelCase					:					Union[DistributedType, SageMakerDistributedType]
	_UpperCamelCase					:					str
	_UpperCamelCase					:					bool





	def      SCREAMING_SNAKE_CASE__						(	self	):
		lowercase					  =   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	):
				lowercase					  =   value.value
			if isinstance(snake_case		,   snake_case	) and not bool(snake_case	):
				lowercase					  =   None
		lowercase					  =   {k: v for k, v in result.items() if v is not None}
		return result





	@classmethod
	def      SCREAMING_SNAKE_CASE__						(	cls		,   snake_case=None	):
		lowercase					  =   default_json_config_file if json_file is None else json_file
		with open(snake_case		,   'r'		,   encoding='utf-8'	) as f:
			lowercase					  =   json.load(snake_case	)
		if "compute_environment" not in config_dict:
			lowercase					  =   ComputeEnvironment.LOCAL_MACHINE
		if "mixed_precision" not in config_dict:
			lowercase					  =   '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.
			lowercase					  =   config_dict.pop('dynamo_backend'	)
			lowercase					  =   {} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
		if "use_cpu" not in config_dict:
			lowercase					  =   False
		return cls(**snake_case	)





	def      SCREAMING_SNAKE_CASE__						(	self		,   snake_case	):
		with open(snake_case		,   'w'		,   encoding='utf-8'	) as f:
			lowercase					  =   json.dumps(self.to_dict()		,   indent=2		,   sort_keys=snake_case	) + '\n'
			f.write(snake_case	)





	@classmethod
	def      SCREAMING_SNAKE_CASE__						(	cls		,   snake_case=None	):
		lowercase					  =   default_yaml_config_file if yaml_file is None else yaml_file
		with open(snake_case		,   'r'		,   encoding='utf-8'	) as f:
			lowercase					  =   yaml.safe_load(snake_case	)
		if "compute_environment" not in config_dict:
			lowercase					  =   ComputeEnvironment.LOCAL_MACHINE

		if "mixed_precision" not in config_dict:
			lowercase					  =   '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"]:
			lowercase					  =   '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.
			lowercase					  =   config_dict.pop('dynamo_backend'	)
			lowercase					  =   {} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
		if "use_cpu" not in config_dict:
			lowercase					  =   False
		return cls(**snake_case	)





	def      SCREAMING_SNAKE_CASE__						(	self		,   snake_case	):
		with open(snake_case		,   'w'		,   encoding='utf-8'	) as f:
			yaml.safe_dump(self.to_dict()		,   snake_case	)





	def      SCREAMING_SNAKE_CASE__						(	self	):
		if isinstance(self.compute_environment		,   snake_case	):
			lowercase					  =   ComputeEnvironment(self.compute_environment	)
		if isinstance(self.distributed_type		,   snake_case	):
			if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
				lowercase					  =   SageMakerDistributedType(self.distributed_type	)
			else:
				lowercase					  =   DistributedType(self.distributed_type	)
		if self.dynamo_config is None:
			lowercase					  =   {}







@dataclass
class 	A_       (      __lowerCamelCase       ):




	'''simple docstring'''


	_UpperCamelCase					:					int
	_UpperCamelCase					:					int										=	0
	_UpperCamelCase					:					int										=	1
	_UpperCamelCase					:					Optional[str]										=	None
	_UpperCamelCase					:					Optional[str]										=	None
	_UpperCamelCase					:					Optional[int]										=	None
	_UpperCamelCase					:					Optional[str]										=	"static"
	_UpperCamelCase					:					Optional[bool]										=	False
	_UpperCamelCase					:					str										=	"main"

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

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

	# args for dynamo
	_UpperCamelCase					:					dict										=	None





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







@dataclass
class 	A_       (      __lowerCamelCase       ):




	'''simple docstring'''


	_UpperCamelCase					:					str
	_UpperCamelCase					:					str
	_UpperCamelCase					:					Optional[str]										=	None
	_UpperCamelCase					:					Optional[str]										=	None
	_UpperCamelCase					:					str										=	"us-east-1"
	_UpperCamelCase					:					int										=	1
	_UpperCamelCase					:					str										=	"all"
	_UpperCamelCase					:					str										=	F"""accelerate-sagemaker-{num_machines}"""
	_UpperCamelCase					:					str										=	SAGEMAKER_PYTORCH_VERSION
	_UpperCamelCase					:					str										=	SAGEMAKER_TRANSFORMERS_VERSION
	_UpperCamelCase					:					str										=	SAGEMAKER_PYTHON_VERSION
	_UpperCamelCase					:					str										=	None
	_UpperCamelCase					:					str										=	None
	_UpperCamelCase					:					dict										=	None
	_UpperCamelCase					:					dict										=	None



from string import ascii_uppercase






def 							UpperCAmelCase_		(							__SCREAMING_SNAKE_CASE			,							__SCREAMING_SNAKE_CASE			,							__SCREAMING_SNAKE_CASE = False			,							__SCREAMING_SNAKE_CASE = ascii_uppercase							):
	lowercase					  =   keyword.upper()
	lowercase					  =   plaintext.upper()
	lowercase					  =   set(__SCREAMING_SNAKE_CASE							)

	# create a list of unique characters in the keyword - their order matters
	# it determines how we will map plaintext characters to the ciphertext
	lowercase					  =   []
	for char in keyword:
		if char in alphabet_set and char not in unique_chars:
			unique_chars.append(__SCREAMING_SNAKE_CASE							)
    # the number of those unique characters will determine the number of rows
	lowercase					  =   len(__SCREAMING_SNAKE_CASE							)

	# create a shifted version of the alphabet
	lowercase					  =   unique_chars + [
	    char for char in alphabet if char not in unique_chars
	]

	# create a modified alphabet by splitting the shifted alphabet into rows
	lowercase					  =   [
	    shifted_alphabet[k : k + num_unique_chars_in_keyword]
	    for k in range(0			,							26			,							__SCREAMING_SNAKE_CASE							)
	]

	# map the alphabet characters to the modified alphabet characters
	# going 'vertically' through the modified alphabet - consider columns first
	lowercase					  =   {}
	lowercase					  =   0
	for column in range(__SCREAMING_SNAKE_CASE							):
		for row in modified_alphabet:
			# if current row (the last one) is too short, break out of loop
			if len(__SCREAMING_SNAKE_CASE							) <= column:
				break

			# map current letter to letter in modified alphabet
			lowercase					  =   row[column]
			letter_index += 1

	if verbose:
		print(__SCREAMING_SNAKE_CASE							)
	# create the encrypted text by mapping the plaintext to the modified alphabet
	return "".join(mapping[char] if char in mapping else char for char in plaintext							)


if __name__ == "__main__":
	# example use
	print(mixed_keyword('''college''', '''UNIVERSITY'''))

