





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


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

def     UpperCAmelCase_						(						_UpperCAmelCase       :int							)  ->							Any:
     '''simple docstring'''


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





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


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





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


  @classmethod
  def 	__UpperCAmelCase    (       cls   ,__snake_case=None   ):



       """simple docstring"""





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


  def 	__UpperCAmelCase    (       self   ,__snake_case   ):



       """simple docstring"""





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


  @classmethod
  def 	__UpperCAmelCase    (       cls   ,__snake_case=None   ):



       """simple docstring"""





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

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


  def 	__UpperCAmelCase    (       self   ,__snake_case   ):



       """simple docstring"""





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




  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





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





@dataclass
class UpperCAmelCase_							(   _SCREAMING_SNAKE_CASE   ):
  __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   ):



       """simple docstring"""





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





@dataclass
class UpperCAmelCase_							(   _SCREAMING_SNAKE_CASE   ):
  __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










import shutil
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from transformers import SpeechaTextTokenizer, is_speech_available
from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, require_torchaudio
from transformers.utils import FEATURE_EXTRACTOR_NAME

from .test_feature_extraction_speech_to_text import floats_list


if is_speech_available():
      from transformers import SpeechaTextFeatureExtractor, SpeechaTextProcessor


a__			:    Optional[Any]			      =		get_tests_dir('fixtures/test_sentencepiece.model')





@require_torch
@require_torchaudio
@require_sentencepiece
class UpperCAmelCase_							(   unittest.TestCase   ):


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					tempfile.mkdtemp()

       A_					      =					['''<s>''', '''<pad>''', '''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']
       A_					      =					dict(zip(__snake_case   ,range(len(__snake_case   )   )   )   )
       A_					      =					Path(self.tmpdirname   )
       save_json(__snake_case   ,save_dir / VOCAB_FILES_NAMES['''vocab_file''']   )
       if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
            copyfile(__snake_case   ,save_dir / VOCAB_FILES_NAMES['''spm_file''']   )

       A_					      =					SpeechaTextTokenizer.from_pretrained(self.tmpdirname   )
       tokenizer.save_pretrained(self.tmpdirname   )

       A_					      =					{
           '''feature_size''': 2_4,
           '''num_mel_bins''': 2_4,
           '''padding_value''': 0.0,
           '''sampling_rate''': 1_6_0_0_0,
           '''return_attention_mask''': False,
           '''do_normalize''': True,
       }
       save_json(__snake_case   ,save_dir / FEATURE_EXTRACTOR_NAME   )


  def 	__UpperCAmelCase    (       self   ,**__snake_case   ):



       """simple docstring"""





       return SpeechaTextTokenizer.from_pretrained(self.tmpdirname   ,**__snake_case   )


  def 	__UpperCAmelCase    (       self   ,**__snake_case   ):



       """simple docstring"""





       return SpeechaTextFeatureExtractor.from_pretrained(self.tmpdirname   ,**__snake_case   )


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       shutil.rmtree(self.tmpdirname   )


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					self.get_tokenizer()
       A_					      =					self.get_feature_extractor()

       A_					      =					SpeechaTextProcessor(tokenizer=__snake_case   ,feature_extractor=__snake_case   )

       processor.save_pretrained(self.tmpdirname   )
       A_					      =					SpeechaTextProcessor.from_pretrained(self.tmpdirname   )

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

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


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					SpeechaTextProcessor(
           tokenizer=self.get_tokenizer()   ,feature_extractor=self.get_feature_extractor()   )
       processor.save_pretrained(self.tmpdirname   )

       A_					      =					self.get_tokenizer(bos_token='''(BOS)'''   ,eos_token='''(EOS)'''   )
       A_					      =					self.get_feature_extractor(do_normalize=__snake_case   ,padding_value=1.0   )

       A_					      =					SpeechaTextProcessor.from_pretrained(
           self.tmpdirname   ,bos_token='''(BOS)'''   ,eos_token='''(EOS)'''   ,do_normalize=__snake_case   ,padding_value=1.0   )

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

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


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					self.get_feature_extractor()
       A_					      =					self.get_tokenizer()

       A_					      =					SpeechaTextProcessor(tokenizer=__snake_case   ,feature_extractor=__snake_case   )

       A_					      =					floats_list((3, 1_0_0_0)   )

       A_					      =					feature_extractor(__snake_case   ,return_tensors='''np'''   )
       A_					      =					processor(__snake_case   ,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 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					self.get_feature_extractor()
       A_					      =					self.get_tokenizer()

       A_					      =					SpeechaTextProcessor(tokenizer=__snake_case   ,feature_extractor=__snake_case   )

       A_					      =					'''This is a test string'''

       A_					      =					processor(text=__snake_case   )

       A_					      =					tokenizer(__snake_case   )

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


  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					self.get_feature_extractor()
       A_					      =					self.get_tokenizer()

       A_					      =					SpeechaTextProcessor(tokenizer=__snake_case   ,feature_extractor=__snake_case   )

       A_					      =					[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

       A_					      =					processor.batch_decode(__snake_case   )
       A_					      =					tokenizer.batch_decode(__snake_case   )

       self.assertListEqual(__snake_case   ,__snake_case   )




  def 	__UpperCAmelCase    (       self   ):



       """simple docstring"""





       A_					      =					self.get_feature_extractor()
       A_					      =					self.get_tokenizer()

       A_					      =					SpeechaTextProcessor(tokenizer=__snake_case   ,feature_extractor=__snake_case   )

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



