"""simple docstring"""







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



def       A__    (	lowercase_     :	Any						)  ->							Union[str, 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:
      __lowerCamelCase    		=					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
         ):
            __lowerCamelCase    		=					ClusterConfig
         else:
            __lowerCamelCase    		=					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
         ):
            __lowerCamelCase    		=					ClusterConfig
         else:
            __lowerCamelCase    		=					SageMakerConfig
         return config_class.from_yaml_file(yaml_file=lowercase_						)






@dataclass
class      _SCREAMING_SNAKE_CASE							:



   '''simple docstring'''



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







   def    _A				(	self	):


      '''simple docstring'''

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







   @classmethod
   def    _A				(	cls ,				_SCREAMING_SNAKE_CASE=None	):


      '''simple docstring'''

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







   def    _A				(	self ,				_SCREAMING_SNAKE_CASE	):


      '''simple docstring'''

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







   @classmethod
   def    _A				(	cls ,				_SCREAMING_SNAKE_CASE=None	):


      '''simple docstring'''

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

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







   def    _A				(	self ,				_SCREAMING_SNAKE_CASE	):


      '''simple docstring'''

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







   def    _A				(	self	):


      '''simple docstring'''

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






@dataclass
class      _SCREAMING_SNAKE_CASE							(			UpperCAmelCase				):



   '''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    _A				(	self	):


      '''simple docstring'''

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






@dataclass
class      _SCREAMING_SNAKE_CASE							(			UpperCAmelCase				):



   '''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













"""simple docstring"""




import json
import os
import shutil
import tempfile
import unittest

from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.utils import FEATURE_EXTRACTOR_NAME

from .test_feature_extraction_wavaveca import floats_list




class 					_a		( unittest.TestCase							):






				def 							snake_case      (					self						:       int				)      -> Optional[int]:




										'''simple docstring'''



										_UpperCamelCase     :   List[Any]      =       '''<pad> <s> </s> <unk> | E T A O N I H S R D L U M W C F G Y P B V K \' X J Q Z'''.split(''' '''				)
										_UpperCamelCase     :   Tuple      =       dict(zip(lowerCAmelCase__,					range(len(lowerCAmelCase__				)				)				)				)

										_UpperCamelCase     :   Any      =       {
										    '''pad_token''': '''<pad>''',
										    '''unk_token''': '''<unk>''',
										    '''bos_token''': '''<s>''',
										    '''eos_token''': '''</s>''',
										}
										_UpperCamelCase     :   Optional[int]      =       {
										    '''feature_size''': 1,
										    '''padding_value''': 0.0,
										    '''sampling_rate''': 1_6_0_0_0,
										    '''return_attention_mask''': False,
										    '''do_normalize''': True,
										}

										_UpperCamelCase     :   List[str]      =       tempfile.mkdtemp()
										_UpperCamelCase     :   Any      =       os.path.join(self.tmpdirname,					VOCAB_FILES_NAMES['''vocab_file''']				)
										_UpperCamelCase     :   Optional[int]      =       os.path.join(self.tmpdirname,					lowerCAmelCase__				)
										with open(self.vocab_file,					'''w''',					encoding='''utf-8'''				) as fp:
																fp.write(json.dumps(lowerCAmelCase__				) + '''\n'''				)

										with open(self.feature_extraction_file,					'''w''',					encoding='''utf-8'''				) as fp:
																fp.write(json.dumps(lowerCAmelCase__				) + '''\n'''				)






				def 							snake_case      (					self						:       List[Any],					**lowerCAmelCase__						:       Any				)      -> int:




										'''simple docstring'''



										_UpperCamelCase     :   str      =       self.add_kwargs_tokens_map.copy()
										kwargs.update(lowerCAmelCase__				)
										return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname,					**lowerCAmelCase__				)






				def 							snake_case      (					self						:       Any,					**lowerCAmelCase__						:       Dict				)      -> Optional[int]:




										'''simple docstring'''



										return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname,					**lowerCAmelCase__				)






				def 							snake_case      (					self						:       Dict				)      -> Optional[int]:




										'''simple docstring'''



										shutil.rmtree(self.tmpdirname				)






				def 							snake_case      (					self						:       Optional[Any]				)      -> Optional[int]:




										'''simple docstring'''



										_UpperCamelCase     :   Tuple      =       self.get_tokenizer()
										_UpperCamelCase     :   str      =       self.get_feature_extractor()

										_UpperCamelCase     :   str      =       WavaVecaProcessor(tokenizer=lowerCAmelCase__,					feature_extractor=lowerCAmelCase__				)

										processor.save_pretrained(self.tmpdirname				)
										_UpperCamelCase     :   Optional[Any]      =       WavaVecaProcessor.from_pretrained(self.tmpdirname				)

										self.assertEqual(processor.tokenizer.get_vocab(),					tokenizer.get_vocab()				)
										self.assertIsInstance(processor.tokenizer,					lowerCAmelCase__				)

										self.assertEqual(processor.feature_extractor.to_json_string(),					feature_extractor.to_json_string()				)
										self.assertIsInstance(processor.feature_extractor,					lowerCAmelCase__				)






				def 							snake_case      (					self						:       str				)      -> str:




										'''simple docstring'''



										_UpperCamelCase     :   Dict      =       WavaVecaProcessor(tokenizer=self.get_tokenizer(),					feature_extractor=self.get_feature_extractor()				)
										processor.save_pretrained(self.tmpdirname				)

										_UpperCamelCase     :   Tuple      =       self.get_tokenizer(bos_token='''(BOS)''',					eos_token='''(EOS)'''				)
										_UpperCamelCase     :   Any      =       self.get_feature_extractor(do_normalize=lowerCAmelCase__,					padding_value=1.0				)

										_UpperCamelCase     :   int      =       WavaVecaProcessor.from_pretrained(
										    self.tmpdirname,					bos_token='''(BOS)''',					eos_token='''(EOS)''',					do_normalize=lowerCAmelCase__,					padding_value=1.0				)

										self.assertEqual(processor.tokenizer.get_vocab(),					tokenizer_add_kwargs.get_vocab()				)
										self.assertIsInstance(processor.tokenizer,					lowerCAmelCase__				)

										self.assertEqual(processor.feature_extractor.to_json_string(),					feature_extractor_add_kwargs.to_json_string()				)
										self.assertIsInstance(processor.feature_extractor,					lowerCAmelCase__				)






				def 							snake_case      (					self						:       Optional[Any]				)      -> Tuple:




										'''simple docstring'''



										_UpperCamelCase     :   Union[str, Any]      =       self.get_feature_extractor()
										_UpperCamelCase     :   str      =       self.get_tokenizer()

										_UpperCamelCase     :   Union[str, Any]      =       WavaVecaProcessor(tokenizer=lowerCAmelCase__,					feature_extractor=lowerCAmelCase__				)

										_UpperCamelCase     :   Any      =       floats_list((3, 1_0_0_0)				)

										_UpperCamelCase     :   int      =       feature_extractor(lowerCAmelCase__,					return_tensors='''np'''				)
										_UpperCamelCase     :   List[Any]      =       processor(lowerCAmelCase__,					return_tensors='''np'''				)

										for key in input_feat_extract.keys():
																self.assertAlmostEqual(input_feat_extract[key].sum(),					input_processor[key].sum(),					delta=1e-2				)






				def 							snake_case      (					self						:       Tuple				)      -> Optional[Any]:




										'''simple docstring'''



										_UpperCamelCase     :   int      =       self.get_feature_extractor()
										_UpperCamelCase     :   Tuple      =       self.get_tokenizer()

										_UpperCamelCase     :   Optional[Any]      =       WavaVecaProcessor(tokenizer=lowerCAmelCase__,					feature_extractor=lowerCAmelCase__				)

										_UpperCamelCase     :   List[Any]      =       '''This is a test string'''

										_UpperCamelCase     :   List[Any]      =       processor(text=lowerCAmelCase__				)

										_UpperCamelCase     :   Tuple      =       tokenizer(lowerCAmelCase__				)

										for key in encoded_tok.keys():
																self.assertListEqual(encoded_tok[key],					encoded_processor[key]				)






				def 							snake_case      (					self						:       Dict				)      -> List[str]:




										'''simple docstring'''



										_UpperCamelCase     :   Optional[int]      =       self.get_feature_extractor()
										_UpperCamelCase     :   Dict      =       self.get_tokenizer()

										_UpperCamelCase     :   List[Any]      =       WavaVecaProcessor(tokenizer=lowerCAmelCase__,					feature_extractor=lowerCAmelCase__				)

										_UpperCamelCase     :   List[str]      =       [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

										_UpperCamelCase     :   List[str]      =       processor.batch_decode(lowerCAmelCase__				)
										_UpperCamelCase     :   Any      =       tokenizer.batch_decode(lowerCAmelCase__				)

										self.assertListEqual(lowerCAmelCase__,					lowerCAmelCase__				)






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




										'''simple docstring'''



										_UpperCamelCase     :   Dict      =       self.get_feature_extractor()
										_UpperCamelCase     :   List[Any]      =       self.get_tokenizer()

										_UpperCamelCase     :   Optional[int]      =       WavaVecaProcessor(tokenizer=lowerCAmelCase__,					feature_extractor=lowerCAmelCase__				)

										self.assertListEqual(
										    processor.model_input_names,					feature_extractor.model_input_names,					msg='''`processor` and `feature_extractor` model input names do not match''',					)



