





import copy
from typing import Any, Dict, List, Optional, Union

import numpy as np
import torch

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


__A							:			Union[str, Any]         =			logging.get_logger(__name__)







class      lowerCamelCase(						__snake_case	):
     '''simple docstring'''


     __magic_name__   =			['input_features', 'is_longer']




     def __init__(    self				,     snake_case_=64				,     snake_case_=4_8000				,     snake_case_=480				,     snake_case_=10				,     snake_case_=1024				,     snake_case_=0.0				,     snake_case_=False				,     snake_case_ = 0				,     snake_case_ = 1_4000				,     snake_case_ = None				,     snake_case_ = "fusion"				,     snake_case_ = "repeatpad"				,     **snake_case_				,     ):
         super().__init__(
             feature_size=snake_case_				,     sampling_rate=snake_case_				,     padding_value=snake_case_				,     return_attention_mask=snake_case_				,     **snake_case_				,     )
         _A     =							top_db
         _A     =							truncation
         _A     =							padding
         _A     =							fft_window_size
         _A     =							(fft_window_size >> 1) + 1
         _A     =							hop_length
         _A     =							max_length_s
         _A     =							max_length_s * sampling_rate
         _A     =							sampling_rate
         _A     =							frequency_min
         _A     =							frequency_max
         _A     =							mel_filter_bank(
             num_frequency_bins=self.nb_frequency_bins				,     num_mel_filters=snake_case_				,     min_frequency=snake_case_				,     max_frequency=snake_case_				,     sampling_rate=snake_case_				,     norm=snake_case_				,     mel_scale='htk'				,     )
         _A     =							mel_filter_bank(
             num_frequency_bins=self.nb_frequency_bins				,     num_mel_filters=snake_case_				,     min_frequency=snake_case_				,     max_frequency=snake_case_				,     sampling_rate=snake_case_				,     norm='slaney'				,     mel_scale='slaney'				,     )




     def        lowerCAmelCase__		(    self							):
         _A     =							copy.deepcopy(self.__dict__							)
         _A     =							self.__class__.__name__
         if "mel_filters" in output:
             del output["mel_filters"]
         if "mel_filters_slaney" in output:
             del output["mel_filters_slaney"]
         return output




     def        lowerCAmelCase__		(    self				,     snake_case_				,     snake_case_ = None							):
         _A     =							spectrogram(
             snake_case_				,     window_function(self.fft_window_size				,     'hann'							)				,     frame_length=self.fft_window_size				,     hop_length=self.hop_length				,     power=2.0				,     mel_filters=snake_case_				,     log_mel='dB'				,     )
         return log_mel_spectrogram.T




     def        lowerCAmelCase__		(    self				,     snake_case_				,     snake_case_				,     snake_case_							):
         _A     =							np.array_split(list(range(0				,     total_frames - chunk_frames + 1							)							)				,     3							)
         if len(ranges[1]							) == 0:
             # if the audio is too short, we just use the first chunk
             _A     =							[0]
         if len(ranges[2]							) == 0:
             # if the audio is too short, we just use the first chunk
             _A     =							[0]
         # randomly choose index for each part
         _A     =							np.random.choice(ranges[0]							)
         _A     =							np.random.choice(ranges[1]							)
         _A     =							np.random.choice(ranges[2]							)

         _A     =							mel[idx_front : idx_front + chunk_frames, :]
         _A     =							mel[idx_middle : idx_middle + chunk_frames, :]
         _A     =							mel[idx_back : idx_back + chunk_frames, :]

         _A     =							torch.tensor(mel[None, None, :]							)
         _A     =							torch.nn.functional.interpolate(
             snake_case_				,     size=[chunk_frames, 64]				,     mode='bilinear'				,     align_corners=snake_case_							)
         _A     =							mel_shrink[0][0].numpy()
         _A     =							np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back]				,     axis=0							)
         return mel_fusion




     def        lowerCAmelCase__		(    self				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_							):
         if waveform.shape[0] > max_length:
             if truncation == "rand_trunc":
                 _A     =							True
                 # random crop to max_length (for compatibility) -> this should be handled by self.pad
                 _A     =							len(snake_case_							) - max_length
                 _A     =							np.random.randint(0				,     overflow + 1							)
                 _A     =							waveform[idx : idx + max_length]
                 _A     =							self._np_extract_fbank_features(snake_case_				,     self.mel_filters_slaney							)[None, :]
             elif truncation == "fusion":
                 _A     =							self._np_extract_fbank_features(snake_case_				,     self.mel_filters							)
                 _A     =							max_length // self.hop_length + 1  # the +1 related to how the spectrogram is computed
                 _A     =							mel.shape[0]
                 if chunk_frames == total_frames:
                     # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
                     # In this case, we just use the whole audio.
                     _A     =							np.stack([mel, mel, mel, mel]				,     axis=0							)
                     _A     =							False
                 else:
                     _A     =							self._random_mel_fusion(snake_case_				,     snake_case_				,     snake_case_							)
                     _A     =							True
             else:
                 raise NotImplementedError(F"data_truncating {truncation} not implemented"							)

         else:
             _A     =							False
             # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
             if waveform.shape[0] < max_length:
                 if padding == "repeat":
                     _A     =							int(max_length / len(snake_case_							)							)
                     _A     =							np.stack(np.tile(snake_case_				,     n_repeat + 1							)							)[:max_length]
                 if padding == "repeatpad":
                     _A     =							int(max_length / len(snake_case_							)							)
                     _A     =							np.stack(np.tile(snake_case_				,     snake_case_							)							)
                 _A     =							np.pad(snake_case_				,     (0, max_length - waveform.shape[0])				,     mode='constant'				,     constant_values=0							)

             if truncation == "fusion":
                 _A     =							self._np_extract_fbank_features(snake_case_				,     self.mel_filters							)
                 _A     =							np.stack([input_mel, input_mel, input_mel, input_mel]				,     axis=0							)
             else:
                 _A     =							self._np_extract_fbank_features(snake_case_				,     self.mel_filters_slaney							)[None, :]

         return input_mel, longer




     def __call__(    self				,     snake_case_				,     snake_case_ = None				,     snake_case_ = None				,     snake_case_ = None				,     snake_case_ = None				,     snake_case_ = None				,     **snake_case_				,     ):
         _A     =							truncation if truncation is not None else self.truncation
         _A     =							padding if padding else self.padding

         if sampling_rate is not None:
             if sampling_rate != self.sampling_rate:
                 raise ValueError(
                     F"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"
                     F" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"
                     F" was sampled with {self.sampling_rate} and not {sampling_rate}."							)
         else:
             logger.warning(
                 'It is strongly recommended to pass the `sampling_rate` argument to this function. '
                 'Failing to do so can result in silent errors that might be hard to debug.'							)

         _A     =							isinstance(snake_case_				,     np.ndarray							) and len(raw_speech.shape							) > 1
         if is_batched_numpy and len(raw_speech.shape							) > 2:
             raise ValueError(F"Only mono-channel audio is supported for input to {self}"							)
         _A     =							is_batched_numpy or (
             isinstance(snake_case_				,     (list, tuple)							) and (isinstance(raw_speech[0]				,     (np.ndarray, tuple, list)							))
         )

         if is_batched:
             _A     =							[np.asarray(snake_case_				,     dtype=np.floataa							) for speech in raw_speech]
         elif not is_batched and not isinstance(snake_case_				,     np.ndarray							):
             _A     =							np.asarray(snake_case_				,     dtype=np.floataa							)
         elif isinstance(snake_case_				,     np.ndarray							) and raw_speech.dtype is np.dtype(np.floataa							):
             _A     =							raw_speech.astype(np.floataa							)

         # always return batch
         if not is_batched:
             _A     =							[np.asarray(snake_case_							)]

         # convert to mel spectrogram, truncate and pad if needed.
         _A     =							[
             self._get_input_mel(snake_case_				,     max_length if max_length else self.nb_max_samples				,     snake_case_				,     snake_case_							)
             for waveform in raw_speech
         ]

         _A     =							[]
         _A     =							[]
         for mel, longer in padded_inputs:
             input_mel.append(snake_case_							)
             is_longer.append(snake_case_							)

         if truncation == "fusion" and sum(snake_case_							) == 0:
             # if no audio is longer than 10s, then randomly select one audio to be longer
             _A     =							np.random.randint(0				,     len(snake_case_							)							)
             _A     =							True

         if isinstance(input_mel[0]				,     snake_case_							):
             _A     =							[np.asarray(snake_case_				,     dtype=np.floataa							) for feature in input_mel]

         # is_longer is a list of bool
         _A     =							[[longer] for longer in is_longer]

         _A     =							{'input_features': input_mel, 'is_longer': is_longer}
         _A     =							BatchFeature(snake_case_							)

         if return_tensors is not None:
             _A     =							input_features.convert_to_tensors(snake_case_							)

         return input_features












import baseaa
import io
import json
import os
from copy import deepcopy

from ..optimizer import AcceleratedOptimizer
from ..scheduler import AcceleratedScheduler





class 				a			:






				def __init__(  self			, _lowerCAmelCase					):

										"""simple docstring"""




										if isinstance(_lowerCAmelCase			, _lowerCAmelCase					):
																# Don't modify user's data should they want to reuse it (e.g. in tests), because once we
																# modified it, it will not be accepted here again, since `auto` values would have been overridden
																__SCREAMING_SNAKE_CASE:				Optional[int]           =   deepcopy(_lowerCAmelCase					)
										elif os.path.exists(_lowerCAmelCase					):
																with io.open(_lowerCAmelCase			, '''r'''			, encoding='''utf-8'''					) as f:
																						__SCREAMING_SNAKE_CASE:				int           =   json.load(_lowerCAmelCase					)
										else:
																try:
																						__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   baseaa.urlsafe_baadecode(_lowerCAmelCase					).decode('''utf-8'''					)
																						__SCREAMING_SNAKE_CASE:				List[Any]           =   json.loads(_lowerCAmelCase					)
																except (UnicodeDecodeError, AttributeError, ValueError):
																						raise ValueError(
																						    f"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}"""					)

										__SCREAMING_SNAKE_CASE:				str           =   config

										self.set_stage_and_offload()






				def 			snake_case_    (  self					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				str           =   self.get_value('''zero_optimization.stage'''			, -1					)

										# offload
										__SCREAMING_SNAKE_CASE:				Dict           =   False
										if self.is_zeroa() or self.is_zeroa():
																__SCREAMING_SNAKE_CASE:				str           =   set(['''cpu''', '''nvme''']					)
																__SCREAMING_SNAKE_CASE:				Tuple           =   set(
																    [
																        self.get_value('''zero_optimization.offload_optimizer.device'''					),
																        self.get_value('''zero_optimization.offload_param.device'''					),
																    ]					)
																if len(offload_devices & offload_devices_valid					) > 0:
																						__SCREAMING_SNAKE_CASE:				Dict           =   True






				def 			snake_case_    (  self			, _lowerCAmelCase					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				int           =   self.config

										# find the config node of interest if it exists
										__SCREAMING_SNAKE_CASE:				Optional[Any]           =   ds_key_long.split('''.'''					)
										__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   nodes.pop()
										for node in nodes:
																__SCREAMING_SNAKE_CASE:				int           =   config.get(_lowerCAmelCase					)
																if config is None:
																						return None, ds_key

										return config, ds_key






				def 			snake_case_    (  self			, _lowerCAmelCase			, _lowerCAmelCase=None					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE:				List[Any]           =   self.find_config_node(_lowerCAmelCase					)
										if config is None:
																return default
										return config.get(_lowerCAmelCase			, _lowerCAmelCase					)






				def 			snake_case_    (  self			, _lowerCAmelCase			, _lowerCAmelCase=False					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				str           =   self.config

										# find the config node of interest if it exists
										__SCREAMING_SNAKE_CASE:				str           =   ds_key_long.split('''.'''					)
										for node in nodes:
																__SCREAMING_SNAKE_CASE:				Tuple           =   config
																__SCREAMING_SNAKE_CASE:				List[str]           =   config.get(_lowerCAmelCase					)
																if config is None:
																						if must_exist:
																												raise ValueError(f"""Can't find {ds_key_long} entry in the config: {self.config}"""					)
																						else:
																												return

        # if found remove it
										if parent_config is not None:
																parent_config.pop(_lowerCAmelCase					)






				def 			snake_case_    (  self			, _lowerCAmelCase					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				Optional[Any]           =   self.get_value(_lowerCAmelCase					)
										return False if value is None else bool(_lowerCAmelCase					)






				def 			snake_case_    (  self			, _lowerCAmelCase					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				Any           =   self.get_value(_lowerCAmelCase					)
										return False if value is None else not bool(_lowerCAmelCase					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										return self._stage == 2






				def 			snake_case_    (  self					):

										"""simple docstring"""




										return self._stage == 3






				def 			snake_case_    (  self					):

										"""simple docstring"""




										return self._offload





class 				a			:






				def __init__(  self			, _lowerCAmelCase					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				Optional[int]           =   engine






				def 			snake_case_    (  self			, _lowerCAmelCase			, **_lowerCAmelCase					):

										"""simple docstring"""




										self.engine.backward(_lowerCAmelCase			, **_lowerCAmelCase					)

										# Deepspeed's `engine.step` performs the following operations:
										# - gradient accumulation check
										# - gradient clipping
										# - optimizer step
										# - zero grad
										# - checking overflow
										# - lr_scheduler step (only if engine.lr_scheduler is not None)
										self.engine.step()
										# and this plugin overrides the above calls with no-ops when Accelerate runs under
										# Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple
										# training loop that works transparently under many training regimes.





class 				a			(      __lowercase			):






				def __init__(  self			, _lowerCAmelCase					):

										"""simple docstring"""




										super().__init__(_lowerCAmelCase			, device_placement=_lowerCAmelCase			, scaler=_lowerCAmelCase					)
										__SCREAMING_SNAKE_CASE:				str           =   hasattr(self.optimizer			, '''overflow'''					)






				def 			snake_case_    (  self			, _lowerCAmelCase=None					):

										"""simple docstring"""




										pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed






				def 			snake_case_    (  self					):

										"""simple docstring"""




										pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed






				@property
				def 			snake_case_    (  self					):

										"""simple docstring"""




										if self.__has_overflow__:
																return self.optimizer.overflow
										return False





class 				a			(      __lowercase			):






				def __init__(  self			, _lowerCAmelCase			, _lowerCAmelCase					):

										"""simple docstring"""




										super().__init__(_lowerCAmelCase			, _lowerCAmelCase					)






				def 			snake_case_    (  self					):

										"""simple docstring"""




										pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed





class 				a			:






				def __init__(  self			, _lowerCAmelCase			, _lowerCAmelCase=0.001			, _lowerCAmelCase=0			, **_lowerCAmelCase					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				str           =   params
										__SCREAMING_SNAKE_CASE:				int           =   lr
										__SCREAMING_SNAKE_CASE:				List[str]           =   weight_decay
										__SCREAMING_SNAKE_CASE:				List[Any]           =   kwargs





class 				a			:






				def __init__(  self			, _lowerCAmelCase			, _lowerCAmelCase=None			, _lowerCAmelCase=0			, **_lowerCAmelCase					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				int           =   optimizer
										__SCREAMING_SNAKE_CASE:				int           =   total_num_steps
										__SCREAMING_SNAKE_CASE:				Optional[int]           =   warmup_num_steps
										__SCREAMING_SNAKE_CASE:				str           =   kwargs



