


# 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


SCREAMING_SNAKE_CASE	:Optional[Any]  		=     os.path.expanduser(
    os.getenv('''HF_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''huggingface'''))
)
SCREAMING_SNAKE_CASE	:Any  		=     os.path.join(hf_cache_home, '''accelerate''')
SCREAMING_SNAKE_CASE	:Tuple  		=     os.path.join(cache_dir, '''default_config.yaml''')
SCREAMING_SNAKE_CASE	:Union[str, Any]  		=     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):
   SCREAMING_SNAKE_CASE	:Tuple  		=     default_yaml_config_file
else:
   SCREAMING_SNAKE_CASE	:Optional[int]  		=     default_json_config_file



def 			_lowerCAmelCase						(							lowerCAmelCase_							:Any							)->str:
   '''simple docstring'''






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


@dataclass
class     __lowerCAmelCase     :






  """simple docstring"""





  _SCREAMING_SNAKE_CASE		    =       42
  _SCREAMING_SNAKE_CASE		    =       42
  _SCREAMING_SNAKE_CASE		    =       42
  _SCREAMING_SNAKE_CASE		    =       42



  def 					lowerCAmelCase__  (     self       :       Tuple  )   -> List[str]:




     """simple docstring"""
     snake_case_					    =					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(_lowerCAmelCase    ,				_lowerCAmelCase  ):
           snake_case_					    =					value.value
        if isinstance(_lowerCAmelCase    ,				_lowerCAmelCase  ) and not bool(_lowerCAmelCase  ):
           snake_case_					    =					None
     snake_case_					    =					{k: v for k, v in result.items() if v is not None}
     return result



  @classmethod
  def 					lowerCAmelCase__  (     cls       :       str    ,				_lowerCAmelCase       :       Optional[Any]=None  )   -> int:




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



  def 					lowerCAmelCase__  (     self       :       str    ,				_lowerCAmelCase       :       Tuple  )   -> str:




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



  @classmethod
  def 					lowerCAmelCase__  (     cls       :       Dict    ,				_lowerCAmelCase       :       int=None  )   -> Dict:




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

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



  def 					lowerCAmelCase__  (     self       :       List[Any]    ,				_lowerCAmelCase       :       Union[str, Any]  )   -> List[Any]:




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



  def 					lowerCAmelCase__  (     self       :       Any  )   -> int:




     """simple docstring"""
     if isinstance(self.compute_environment    ,				_lowerCAmelCase  ):
        snake_case_					    =					ComputeEnvironment(self.compute_environment  )
     if isinstance(self.distributed_type    ,				_lowerCAmelCase  ):
        if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
           snake_case_					    =					SageMakerDistributedType(self.distributed_type  )
        else:
           snake_case_					    =					DistributedType(self.distributed_type  )
     if self.dynamo_config is None:
        snake_case_					    =					{}






@dataclass
class     __lowerCAmelCase     ( a					):






  """simple docstring"""





  _SCREAMING_SNAKE_CASE		    =       42
  _SCREAMING_SNAKE_CASE		    =       0
  _SCREAMING_SNAKE_CASE		    =       1
  _SCREAMING_SNAKE_CASE		    =       None
  _SCREAMING_SNAKE_CASE		    =       None
  _SCREAMING_SNAKE_CASE		    =       None
  _SCREAMING_SNAKE_CASE		    =       "static"
  _SCREAMING_SNAKE_CASE		    =       False
  _SCREAMING_SNAKE_CASE		    =       "main"

  # args for deepspeed_plugin
  _SCREAMING_SNAKE_CASE		    =       None
  # args for fsdp
  _SCREAMING_SNAKE_CASE		    =       None
  # args for megatron_lm
  _SCREAMING_SNAKE_CASE		    =       None
  # args for ipex
  _SCREAMING_SNAKE_CASE		    =       None
  # args for TPU
  _SCREAMING_SNAKE_CASE		    =       False

  # args for TPU pods
  _SCREAMING_SNAKE_CASE		    =       None
  _SCREAMING_SNAKE_CASE		    =       None
  _SCREAMING_SNAKE_CASE		    =       False
  _SCREAMING_SNAKE_CASE		    =       False
  _SCREAMING_SNAKE_CASE		    =       None
  _SCREAMING_SNAKE_CASE		    =       None
  _SCREAMING_SNAKE_CASE		    =       None
  _SCREAMING_SNAKE_CASE		    =       None

  # args for dynamo
  _SCREAMING_SNAKE_CASE		    =       None



  def 					lowerCAmelCase__  (     self       :       Union[str, Any]  )   -> Union[str, Any]:




     """simple docstring"""
     if self.deepspeed_config is None:
        snake_case_					    =					{}
     if self.fsdp_config is None:
        snake_case_					    =					{}
     if self.megatron_lm_config is None:
        snake_case_					    =					{}
     if self.ipex_config is None:
        snake_case_					    =					{}
     return super().__post_init__()






@dataclass
class     __lowerCAmelCase     ( a					):






  """simple docstring"""





  _SCREAMING_SNAKE_CASE		    =       42
  _SCREAMING_SNAKE_CASE		    =       42
  _SCREAMING_SNAKE_CASE		    =       None
  _SCREAMING_SNAKE_CASE		    =       None
  _SCREAMING_SNAKE_CASE		    =       "us-east-1"
  _SCREAMING_SNAKE_CASE		    =       1
  _SCREAMING_SNAKE_CASE		    =       "all"
  _SCREAMING_SNAKE_CASE		    =       f"""accelerate-sagemaker-{num_machines}"""
  _SCREAMING_SNAKE_CASE		    =       SAGEMAKER_PYTORCH_VERSION
  _SCREAMING_SNAKE_CASE		    =       SAGEMAKER_TRANSFORMERS_VERSION
  _SCREAMING_SNAKE_CASE		    =       SAGEMAKER_PYTHON_VERSION
  _SCREAMING_SNAKE_CASE		    =       None
  _SCREAMING_SNAKE_CASE		    =       None
  _SCREAMING_SNAKE_CASE		    =       None
  _SCREAMING_SNAKE_CASE		    =       None








from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_torch_available,
)


SCREAMING_SNAKE_CASE	:List[Any]  		=     {
    '''configuration_speech_to_text_2''': ['''SPEECH_TO_TEXT_2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Speech2Text2Config'''],
    '''processing_speech_to_text_2''': ['''Speech2Text2Processor'''],
    '''tokenization_speech_to_text_2''': ['''Speech2Text2Tokenizer'''],
}


try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   SCREAMING_SNAKE_CASE	:int  		=     [
       '''SPEECH_TO_TEXT_2_PRETRAINED_MODEL_ARCHIVE_LIST''',
       '''Speech2Text2ForCausalLM''',
       '''Speech2Text2PreTrainedModel''',
   ]


if TYPE_CHECKING:
   from .configuration_speech_to_text_a import SPEECH_TO_TEXT_2_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextaConfig
   from .processing_speech_to_text_a import SpeechaTextaProcessor
   from .tokenization_speech_to_text_a import SpeechaTextaTokenizer

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_speech_to_text_a import (
          SPEECH_TO_TEXT_2_PRETRAINED_MODEL_ARCHIVE_LIST,
          SpeechaTextaForCausalLM,
          SpeechaTextaPreTrainedModel,
      )

else:
   import sys

   SCREAMING_SNAKE_CASE	:str  		=     _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)




