




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


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






def 		_lowercase		(	lowercase_  ):



		'''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:
				_snake_case	       =       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
						):
								_snake_case	       =       ClusterConfig
						else:
								_snake_case	       =       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
						):
								_snake_case	       =       ClusterConfig
						else:
								_snake_case	       =       SageMakerConfig
						return config_class.from_yaml_file(yaml_file=UpperCamelCase_  )





@dataclass
class      lowerCamelCase_							:




					'''simple docstring'''






					lowercase__    = 4_2
					lowercase__    = 4_2
					lowercase__    = 4_2
					lowercase__    = 4_2






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






					@classmethod
					def 				__SCREAMING_SNAKE_CASE	(    cls,  __UpperCamelCase=None ):
							_snake_case	       =       default_json_config_file if json_file is None else json_file
							with open(_UpperCAmelCase,  "r",  encoding="utf-8" ) as f:
									_snake_case	       =       json.load(_UpperCAmelCase )
							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(**_UpperCAmelCase )






					def 				__SCREAMING_SNAKE_CASE	(    self,  __UpperCamelCase ):




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






					@classmethod
					def 				__SCREAMING_SNAKE_CASE	(    cls,  __UpperCamelCase=None ):
							_snake_case	       =       default_yaml_config_file if yaml_file is None else yaml_file
							with open(_UpperCAmelCase,  "r",  encoding="utf-8" ) as f:
									_snake_case	       =       yaml.safe_load(_UpperCAmelCase )
							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"],  _UpperCAmelCase ) 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(**_UpperCAmelCase )






					def 				__SCREAMING_SNAKE_CASE	(    self,  __UpperCamelCase ):




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






					def 				__SCREAMING_SNAKE_CASE	(    self ):




							if isinstance(self.compute_environment,  _UpperCAmelCase ):
									_snake_case	       =       ComputeEnvironment(self.compute_environment )
							if isinstance(self.distributed_type,  _UpperCAmelCase ):
									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'''






					lowercase__    = 4_2
					lowercase__    = 0
					lowercase__    = 1
					lowercase__    = None
					lowercase__    = None
					lowercase__    = None
					lowercase__    = """static"""
					lowercase__    = False
					lowercase__    = """main"""

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

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

					# args for dynamo
					lowercase__    = None






					def 				__SCREAMING_SNAKE_CASE	(    self ):




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






					lowercase__    = 4_2
					lowercase__    = 4_2
					lowercase__    = None
					lowercase__    = None
					lowercase__    = """us-east-1"""
					lowercase__    = 1
					lowercase__    = """all"""
					lowercase__    = F'''accelerate-sagemaker-{num_machines}'''
					lowercase__    = SAGEMAKER_PYTORCH_VERSION
					lowercase__    = SAGEMAKER_TRANSFORMERS_VERSION
					lowercase__    = SAGEMAKER_PYTHON_VERSION
					lowercase__    = None
					lowercase__    = None
					lowercase__    = None
					lowercase__    = None











import numpy as np  # noqa: E402

from ...configuration_utils import ConfigMixin, register_to_config
from ...schedulers.scheduling_utils import SchedulerMixin


try:
	import librosa  # noqa: E402

	_lowerCamelCase					:     Union[str, Any]					  =  True
	_lowerCamelCase					:     Optional[Any]					  =  ""
except Exception as e:
	_lowerCamelCase					:     int					  =  False
	_lowerCamelCase					:     List[str]					  =  (
	    F'''Cannot import librosa because {e}. Make sure to correctly install librosa to be able to install it.'''
	)


from PIL import Image  # noqa: E402
class 				__snake_case     (_a  ,		_a						):
				lowerCAmelCase__			=   "mel_config.json"



				@register_to_config
				def __init__(					self					:						Dict						,		_UpperCAmelCase					:						int = 256						,		_UpperCAmelCase					:						int = 256						,		_UpperCAmelCase					:						int = 2_2050						,		_UpperCAmelCase					:						int = 2048						,		_UpperCAmelCase					:						int = 512						,		_UpperCAmelCase					:						int = 80						,		_UpperCAmelCase					:						int = 32						,		)     ->			List[Any]:





								'''simple docstring'''




								_lowerCAmelCase			:			List[str]        =					hop_length
								_lowerCAmelCase			:			Optional[Any]        =					sample_rate
								_lowerCAmelCase			:			Optional[Any]        =					n_fft
								_lowerCAmelCase			:			Dict        =					top_db
								_lowerCAmelCase			:			List[Any]        =					n_iter
								self.set_resolution(_UpperCAmelCase						,		_UpperCAmelCase					)
								_lowerCAmelCase			:			Optional[int]        =					None

								if not _librosa_can_be_imported:
												raise ValueError(_import_error					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						Optional[int]						,		_UpperCAmelCase					:						int						,		_UpperCAmelCase					:						int					)     ->			List[Any]:





								'''simple docstring'''




								_lowerCAmelCase			:			Dict        =					x_res
								_lowerCAmelCase			:			Union[str, Any]        =					y_res
								_lowerCAmelCase			:			Any        =					self.y_res
								_lowerCAmelCase			:			Optional[Any]        =					self.x_res * self.hop_length - 1



				def 					SCREAMING_SNAKE_CASE				(					self					:						Dict						,		_UpperCAmelCase					:						str = None						,		_UpperCAmelCase					:						np.ndarray = None					)     ->			List[str]:





								'''simple docstring'''




								if audio_file is not None:
												_lowerCAmelCase    ,			_lowerCAmelCase			:			Dict        =					librosa.load(_UpperCAmelCase						,		mono=_UpperCAmelCase						,		sr=self.sr					)
								else:
												_lowerCAmelCase			:			Any        =					raw_audio

								# Pad with silence if necessary.
								if len(self.audio					) < self.x_res * self.hop_length:
												_lowerCAmelCase			:			Optional[Any]        =					np.concatenate([self.audio, np.zeros((self.x_res * self.hop_length - len(self.audio					),)					)]					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						Any					)     ->			int:





								'''simple docstring'''




								return len(self.audio					) // self.slice_size



				def 					SCREAMING_SNAKE_CASE				(					self					:						List[str]						,		_UpperCAmelCase					:						int = 0					)     ->			np.ndarray:





								'''simple docstring'''




								return self.audio[self.slice_size * slice : self.slice_size * (slice + 1)]



				def 					SCREAMING_SNAKE_CASE				(					self					:						List[Any]					)     ->			int:





								'''simple docstring'''




								return self.sr



				def 					SCREAMING_SNAKE_CASE				(					self					:						Dict						,		_UpperCAmelCase					:						int					)     ->			Image.Image:





								'''simple docstring'''




								_lowerCAmelCase			:			Union[str, Any]        =					librosa.feature.melspectrogram(
								    y=self.get_audio_slice(_UpperCAmelCase					)						,		sr=self.sr						,		n_fft=self.n_fft						,		hop_length=self.hop_length						,		n_mels=self.n_mels					)
								_lowerCAmelCase			:			List[Any]        =					librosa.power_to_db(_UpperCAmelCase						,		ref=np.max						,		top_db=self.top_db					)
								_lowerCAmelCase			:			List[Any]        =					(((log_S + self.top_db) * 255 / self.top_db).clip(0						,		255					) + 0.5).astype(np.uinta					)
								_lowerCAmelCase			:			Optional[Any]        =					Image.fromarray(_UpperCAmelCase					)
								return image



				def 					SCREAMING_SNAKE_CASE				(					self					:						Optional[int]						,		_UpperCAmelCase					:						Image.Image					)     ->			np.ndarray:





								'''simple docstring'''




								_lowerCAmelCase			:			Optional[int]        =					np.frombuffer(image.tobytes()						,		dtype="""uint8"""					).reshape((image.height, image.width)					)
								_lowerCAmelCase			:			Optional[int]        =					bytedata.astype("""float"""					) * self.top_db / 255 - self.top_db
								_lowerCAmelCase			:			List[Any]        =					librosa.db_to_power(_UpperCAmelCase					)
								_lowerCAmelCase			:			Optional[int]        =					librosa.feature.inverse.mel_to_audio(
								    _UpperCAmelCase						,		sr=self.sr						,		n_fft=self.n_fft						,		hop_length=self.hop_length						,		n_iter=self.n_iter					)
								return audio

