# 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    lowerCamelCase_   (  _lowercase    )							->	Optional[Any]:
		if config_file is not None:
				if not os.path.isfile(_lowercase    ):
						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:
				__A							:   str	  =				default_config_file
		with open(_lowercase ,     "r" ,     encoding="utf-8"    ) as f:
				if config_file.endswith(".json"    ):
						if (
						    json.load(_lowercase    ).get("compute_environment" ,     ComputeEnvironment.LOCAL_MACHINE    )
						    == ComputeEnvironment.LOCAL_MACHINE
						):
								__A							:   Optional[int]	  =				ClusterConfig
						else:
								__A							:   List[Any]	  =				SageMakerConfig
						return config_class.from_json_file(json_file=_lowercase    )
				else:
						if (
						    yaml.safe_load(_lowercase    ).get("compute_environment" ,     ComputeEnvironment.LOCAL_MACHINE    )
						    == ComputeEnvironment.LOCAL_MACHINE
						):
								__A							:   List[Any]	  =				ClusterConfig
						else:
								__A							:   Tuple	  =				SageMakerConfig
						return config_class.from_yaml_file(yaml_file=_lowercase    )


@dataclass
class _a       :

	'''simple docstring'''



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

	def 					__UpperCAmelCase(       self   ):
			__A							:   Any	  =				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(__UpperCAmelCase							,			__UpperCAmelCase   ):
							__A							:   Union[str, Any]	  =				value.value
					if isinstance(__UpperCAmelCase							,			__UpperCAmelCase   ) and not bool(__UpperCAmelCase   ):
							__A							:   List[Any]	  =				None
			__A							:   List[str]	  =				{k: v for k, v in result.items() if v is not None}
			return result

	@classmethod
	def 					__UpperCAmelCase(       cls							,			__UpperCAmelCase=None   ):
			__A							:   List[str]	  =				default_json_config_file if json_file is None else json_file
			with open(__UpperCAmelCase							,			"r"							,			encoding="utf-8"   ) as f:
					__A							:   Dict	  =				json.load(__UpperCAmelCase   )
			if "compute_environment" not in config_dict:
					__A							:   Tuple	  =				ComputeEnvironment.LOCAL_MACHINE
			if "mixed_precision" not in config_dict:
					__A							:   Optional[Any]	  =				"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.
					__A							:   Optional[Any]	  =				config_dict.pop("dynamo_backend"   )
					__A							:   List[str]	  =				{} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
			if "use_cpu" not in config_dict:
					__A							:   List[str]	  =				False
			return cls(**__UpperCAmelCase   )

	def 					__UpperCAmelCase(       self							,			__UpperCAmelCase   ):
			with open(__UpperCAmelCase							,			"w"							,			encoding="utf-8"   ) as f:
					__A							:   Optional[Any]	  =				json.dumps(self.to_dict()							,			indent=2							,			sort_keys=__UpperCAmelCase   ) + "\n"
					f.write(__UpperCAmelCase   )

	@classmethod
	def 					__UpperCAmelCase(       cls							,			__UpperCAmelCase=None   ):
			__A							:   Tuple	  =				default_yaml_config_file if yaml_file is None else yaml_file
			with open(__UpperCAmelCase							,			"r"							,			encoding="utf-8"   ) as f:
					__A							:   Optional[Any]	  =				yaml.safe_load(__UpperCAmelCase   )
			if "compute_environment" not in config_dict:
					__A							:   List[str]	  =				ComputeEnvironment.LOCAL_MACHINE

			if "mixed_precision" not in config_dict:
					__A							:   Any	  =				"fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None
			if isinstance(config_dict["mixed_precision"]							,			__UpperCAmelCase   ) and not config_dict["mixed_precision"]:
					__A							:   List[str]	  =				"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.
					__A							:   List[Any]	  =				config_dict.pop("dynamo_backend"   )
					__A							:   Any	  =				{} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
			if "use_cpu" not in config_dict:
					__A							:   Union[str, Any]	  =				False
			return cls(**__UpperCAmelCase   )

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







	def 					__UpperCAmelCase(       self   ):
			if isinstance(self.compute_environment							,			__UpperCAmelCase   ):
					__A							:   str	  =				ComputeEnvironment(self.compute_environment   )
			if isinstance(self.distributed_type							,			__UpperCAmelCase   ):
					if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
							__A							:   Optional[int]	  =				SageMakerDistributedType(self.distributed_type   )
					else:
							__A							:   Dict	  =				DistributedType(self.distributed_type   )
			if self.dynamo_config is None:
					__A							:   Union[str, Any]	  =				{}


@dataclass
class _a       (	lowerCAmelCase__ ):

	'''simple docstring'''



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

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

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

	# args for dynamo
	lowerCamelCase_   :      dict       =	None

	def 					__UpperCAmelCase(       self   ):
			if self.deepspeed_config is None:
					__A							:   int	  =				{}
			if self.fsdp_config is None:
					__A							:   Dict	  =				{}
			if self.megatron_lm_config is None:
					__A							:   int	  =				{}
			if self.ipex_config is None:
					__A							:   Optional[int]	  =				{}
			return super().__post_init__()


@dataclass
class _a       (	lowerCAmelCase__ ):

	'''simple docstring'''



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






from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
from PIL import Image

from ...utils import is_torch_available, is_transformers_available


if is_transformers_available() and is_torch_available():
					from .image_encoder import PaintByExampleImageEncoder
					from .pipeline_paint_by_example import PaintByExamplePipeline





