




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

import numpy as np

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


_lowerCamelCase      			=						logging.get_logger(__name__)



class       a					(       UpperCAmelCase_      ):

     '''simple docstring'''





     lowerCAmelCase    :	str       		=  ["""input_values""", """attention_mask"""]
     def __init__(     self       :      Tuple ,   __snake_case       :      int = 1 ,   __snake_case       :      str = 1_60_00 ,   __snake_case       :      Union[str, Any] = 0.0 ,   __snake_case       :      str = False ,   __snake_case       :      Dict = 80 ,   __snake_case       :      Dict = 16 ,   __snake_case       :      str = 64 ,   __snake_case       :      Optional[int] = "hann_window" ,   __snake_case       :      Optional[Any] = 1.0 ,   __snake_case       :      str = 80 ,   __snake_case       :      List[Any] = 76_00 ,   __snake_case       :      str = 1E-10 ,   __snake_case       :      int = 2 ,   __snake_case       :      Union[str, Any] = True ,   **__snake_case       :      List[str] ,   ):
           super().__init__(feature_size=__lowercase ,   sampling_rate=__lowercase ,   padding_value=__lowercase ,   **__lowercase    )
           UpperCAmelCase_										=					do_normalize
           UpperCAmelCase_										=					return_attention_mask

           UpperCAmelCase_										=					num_mel_bins
           UpperCAmelCase_										=					hop_length
           UpperCAmelCase_										=					win_length
           UpperCAmelCase_										=					win_function
           UpperCAmelCase_										=					frame_signal_scale
           UpperCAmelCase_										=					fmin
           UpperCAmelCase_										=					fmax
           UpperCAmelCase_										=					mel_floor
           UpperCAmelCase_										=					reduction_factor

           UpperCAmelCase_										=					win_length * sampling_rate // 10_00
           UpperCAmelCase_										=					hop_length * sampling_rate // 10_00
           UpperCAmelCase_										=					optimal_fft_length(self.sample_size    )
           UpperCAmelCase_										=					(self.n_fft // 2) + 1

           UpperCAmelCase_										=					window_function(window_length=self.sample_size ,   name=self.win_function ,   periodic=__lowercase    )

           UpperCAmelCase_										=					mel_filter_bank(
               num_frequency_bins=self.n_freqs ,   num_mel_filters=self.num_mel_bins ,   min_frequency=self.fmin ,   max_frequency=self.fmax ,   sampling_rate=self.sampling_rate ,   norm='''slaney''' ,   mel_scale='''slaney''' ,   )

           if frame_signal_scale != 1.0:
                 warnings.warn(
                     '''The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers''' ,   __lowercase ,   )
           if reduction_factor != 2.0:
                 warnings.warn(
                     '''The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers''' ,   __lowercase ,   )
     @staticmethod
     # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
     def   lowerCamelCase_       (     __snake_case       :      str ,   __snake_case       :      Tuple ,   __snake_case       :      int = 0.0    ):
           if attention_mask is not None:
                 UpperCAmelCase_										=					np.array(__lowercase ,   np.intaa    )
                 UpperCAmelCase_										=					[]

                 for vector, length in zip(__lowercase ,   attention_mask.sum(-1    )    ):
                       UpperCAmelCase_										=					(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7    )
                       if length < normed_slice.shape[0]:
                             UpperCAmelCase_										=					padding_value

                       normed_input_values.append(__lowercase    )
           else:
                 UpperCAmelCase_										=					[(x - x.mean()) / np.sqrt(x.var() + 1E-7    ) for x in input_values]

           return normed_input_values
     def   lowerCamelCase_       (     self       :      List[Any] ,   __snake_case       :      Optional[Any] ,   ):
           UpperCAmelCase_										=					spectrogram(
               __lowercase ,   window=self.window ,   frame_length=self.sample_size ,   hop_length=self.sample_stride ,   fft_length=self.n_fft ,   mel_filters=self.mel_filters ,   mel_floor=self.mel_floor ,   log_mel='''log10''' ,   )
           return log_mel_spec.T
     def __call__(     self       :      Union[str, Any] ,   __snake_case       :      Dict = None ,   __snake_case       :      str = None ,   __snake_case       :      Dict = False ,   __snake_case       :      Tuple = None ,   __snake_case       :      List[str] = False ,   __snake_case       :      int = None ,   __snake_case       :      List[str] = None ,   __snake_case       :      Optional[int] = None ,   __snake_case       :      Optional[Any] = None ,   **__snake_case       :      List[str] ,   ):
           if audio is None and audio_target is None:
                 raise ValueError('''You must provide either `audio` or `audio_target` values.'''    )

           if sampling_rate is not None:
                 if sampling_rate != self.sampling_rate:
                       raise ValueError(
                           F'The model corresponding to this feature extractor: {self} was trained using a sampling rate of'
                           F' {self.sampling_rate}. Please make sure that the provided audio input was sampled with'
                           F' {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.'''    )

           if audio is not None:
                 UpperCAmelCase_										=					self._process_audio(
                     __lowercase ,   __lowercase ,   __lowercase ,   __lowercase ,   __lowercase ,   __lowercase ,   __lowercase ,   __lowercase ,   **__lowercase ,   )
           else:
                 UpperCAmelCase_										=					None

           if audio_target is not None:
                 UpperCAmelCase_										=					self._process_audio(
                     __lowercase ,   __lowercase ,   __lowercase ,   __lowercase ,   __lowercase ,   __lowercase ,   __lowercase ,   __lowercase ,   **__lowercase ,   )

                 if inputs is None:
                       return inputs_target
                 else:
                       UpperCAmelCase_										=					inputs_target['''input_values''']
                       UpperCAmelCase_										=					inputs_target.get('''attention_mask'''    )
                       if decoder_attention_mask is not None:
                             UpperCAmelCase_										=					decoder_attention_mask

           return inputs
     def   lowerCamelCase_       (     self       :      Tuple ,   __snake_case       :      List[str] ,   __snake_case       :      Any = False ,   __snake_case       :      Optional[Any] = False ,   __snake_case       :      Optional[Any] = None ,   __snake_case       :      Tuple = False ,   __snake_case       :      int = None ,   __snake_case       :      str = None ,   __snake_case       :      Tuple = None ,   **__snake_case       :      Tuple ,   ):
           UpperCAmelCase_										=					isinstance(__lowercase ,   np.ndarray    ) and len(speech.shape    ) > 1
           if is_batched_numpy and len(speech.shape    ) > 2:
                 raise ValueError(F'Only mono-channel audio is supported for input to {self}'    )
           UpperCAmelCase_										=					is_batched_numpy or (
               isinstance(__lowercase ,   (list, tuple)    ) and (isinstance(speech[0] ,   (np.ndarray, tuple, list)    ))
           )

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

           # always return batch
           if not is_batched:
                 UpperCAmelCase_										=					[speech]

           # needed to make pad() work on spectrogram inputs
           UpperCAmelCase_										=					self.feature_size

           # convert into correct format for padding
           if is_target:
                 UpperCAmelCase_										=					[self._extract_mel_features(__lowercase    ) for waveform in speech]
                 UpperCAmelCase_										=					BatchFeature({'''input_values''': features}    )
                 UpperCAmelCase_										=					self.num_mel_bins
           else:
                 UpperCAmelCase_										=					BatchFeature({'''input_values''': speech}    )

           UpperCAmelCase_										=					self.pad(
               __lowercase ,   padding=__lowercase ,   max_length=__lowercase ,   truncation=__lowercase ,   pad_to_multiple_of=__lowercase ,   return_attention_mask=__lowercase ,   **__lowercase ,   )

           UpperCAmelCase_										=					feature_size_hack

           # convert input values to correct format
           UpperCAmelCase_										=					padded_inputs['''input_values''']
           if not isinstance(input_values[0] ,   np.ndarray    ):
                 UpperCAmelCase_										=					[np.asarray(__lowercase ,   dtype=np.floataa    ) for array in input_values]
           elif (
               not isinstance(__lowercase ,   np.ndarray    )
               and isinstance(input_values[0] ,   np.ndarray    )
               and input_values[0].dtype is np.dtype(np.floataa    )
           ):
                 UpperCAmelCase_										=					[array.astype(np.floataa    ) for array in input_values]
           elif isinstance(__lowercase ,   np.ndarray    ) and input_values.dtype is np.dtype(np.floataa    ):
                 UpperCAmelCase_										=					input_values.astype(np.floataa    )

           # convert attention_mask to correct format
           UpperCAmelCase_										=					padded_inputs.get('''attention_mask'''    )
           if attention_mask is not None:
                 UpperCAmelCase_										=					[np.asarray(__lowercase ,   dtype=np.intaa    ) for array in attention_mask]

           # zero-mean and unit-variance normalization
           if not is_target and self.do_normalize:
                 UpperCAmelCase_										=					(
                     attention_mask
                     if self._get_padding_strategies(__lowercase ,   max_length=__lowercase    ) is not PaddingStrategy.DO_NOT_PAD
                     else None
                 )
                 UpperCAmelCase_										=					self.zero_mean_unit_var_norm(
                     padded_inputs['''input_values'''] ,   attention_mask=__lowercase ,   padding_value=self.padding_value    )

           if return_tensors is not None:
                 UpperCAmelCase_										=					padded_inputs.convert_to_tensors(__lowercase    )

           return padded_inputs




     def   lowerCamelCase_       (     self       :      Optional[Any]    ):
           UpperCAmelCase_										=					super().to_dict()

           # Don't serialize these as they are derived from the other properties.
           UpperCAmelCase_										=					['''window''', '''mel_filters''', '''sample_size''', '''sample_stride''', '''n_fft''', '''n_freqs''']
           for name in names:
                 if name in output:
                       del output[name]

           return output











from typing import Dict, Iterable, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


_lowerCamelCase      			=						logging.get_logger(__name__)



class       a					(       _A      ):

     '''simple docstring'''





     lowerCAmelCase    :	List[Any]       		=  ['pixel_values']
     def __init__(     self       :      Any ,   __snake_case       :      bool = True ,   __snake_case       :      Dict[str, int] = None ,   __snake_case       :      PILImageResampling = PILImageResampling.BICUBIC ,   __snake_case       :      bool = True ,   __snake_case       :      Dict[str, int] = None ,   __snake_case       :      bool = True ,   __snake_case       :      Union[int, float] = 1 / 2_55 ,   __snake_case       :      bool = True ,   __snake_case       :      Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN ,   __snake_case       :      Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD ,   **__snake_case       :      Optional[Any] ,   ):
         super().__init__(**__snake_case    )
         UpperCAmelCase_										=					size if size is not None else {'''shortest_edge''': 2_24}
         UpperCAmelCase_										=					get_size_dict(__snake_case ,   default_to_square=__snake_case    )
         UpperCAmelCase_										=					crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
         UpperCAmelCase_										=					get_size_dict(__snake_case ,   param_name='''crop_size'''    )

         UpperCAmelCase_										=					do_resize
         UpperCAmelCase_										=					size
         UpperCAmelCase_										=					resample
         UpperCAmelCase_										=					do_center_crop
         UpperCAmelCase_										=					crop_size
         UpperCAmelCase_										=					do_rescale
         UpperCAmelCase_										=					rescale_factor
         UpperCAmelCase_										=					do_normalize
         UpperCAmelCase_										=					image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
         UpperCAmelCase_										=					image_std if image_std is not None else IMAGENET_DEFAULT_STD
     def   lowerCamelCase_       (     self       :      int ,   __snake_case       :      np.ndarray ,   __snake_case       :      Dict[str, int] ,   __snake_case       :      PILImageResampling = PILImageResampling.BICUBIC ,   __snake_case       :      Optional[Union[str, ChannelDimension]] = None ,   **__snake_case       :      Tuple ,   ):
         UpperCAmelCase_										=					get_size_dict(__snake_case ,   default_to_square=__snake_case    )
         # size_dict is a dict with either keys "height" and "width" or "shortest_edge"
         if "shortest_edge" in size:
             UpperCAmelCase_										=					int((2_56 / 2_24) * size['''shortest_edge''']    )
             UpperCAmelCase_										=					get_resize_output_image_size(__snake_case ,   size=__snake_case ,   default_to_square=__snake_case    )
             UpperCAmelCase_										=					{'''height''': output_size[0], '''width''': output_size[1]}
         if "height" not in size_dict or "width" not in size_dict:
             raise ValueError(
                 F'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}'    )
         return resize(
             __snake_case ,   size=(size_dict['''height'''], size_dict['''width''']) ,   resample=__snake_case ,   data_format=__snake_case ,   **__snake_case    )
     def   lowerCamelCase_       (     self       :      Tuple ,   __snake_case       :      np.ndarray ,   __snake_case       :      Dict[str, int] ,   __snake_case       :      Optional[Union[str, ChannelDimension]] = None ,   **__snake_case       :      Optional[int] ,   ):
         UpperCAmelCase_										=					get_size_dict(__snake_case    )
         if "height" not in size or "width" not in size:
             raise ValueError(F'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}'    )
         return center_crop(__snake_case ,   size=(size['''height'''], size['''width''']) ,   data_format=__snake_case ,   **__snake_case    )
     def   lowerCamelCase_       (     self       :      Optional[Any] ,   __snake_case       :      np.ndarray ,   __snake_case       :      Union[int, float] ,   __snake_case       :      Optional[Union[str, ChannelDimension]] = None ,   **__snake_case       :      List[Any] ,   ):
         return rescale(__snake_case ,   scale=__snake_case ,   data_format=__snake_case ,   **__snake_case    )
     def   lowerCamelCase_       (     self       :      int ,   __snake_case       :      np.ndarray ,   __snake_case       :      Union[float, List[float]] ,   __snake_case       :      Union[float, List[float]] ,   __snake_case       :      Optional[Union[str, ChannelDimension]] = None ,   **__snake_case       :      Union[str, Any] ,   ):
         return normalize(__snake_case ,   mean=__snake_case ,   std=__snake_case ,   data_format=__snake_case ,   **__snake_case    )




     def   lowerCamelCase_       (     self       :      int ,   __snake_case       :      ImageInput ,   __snake_case       :      Optional[bool] = None ,   __snake_case       :      Optional[Dict[str, int]] = None ,   __snake_case       :      PILImageResampling = None ,   __snake_case       :      Optional[bool] = None ,   __snake_case       :      Optional[Dict[str, int]] = None ,   __snake_case       :      Optional[bool] = None ,   __snake_case       :      Optional[float] = None ,   __snake_case       :      Optional[bool] = None ,   __snake_case       :      Optional[Union[float, Iterable[float]]] = None ,   __snake_case       :      Optional[Union[float, Iterable[float]]] = None ,   __snake_case       :      Optional[TensorType] = None ,   __snake_case       :      ChannelDimension = ChannelDimension.FIRST ,   **__snake_case       :      List[str] ,   ):
         UpperCAmelCase_										=					do_resize if do_resize is not None else self.do_resize
         UpperCAmelCase_										=					resample if resample is not None else self.resample
         UpperCAmelCase_										=					do_center_crop if do_center_crop is not None else self.do_center_crop
         UpperCAmelCase_										=					do_rescale if do_rescale is not None else self.do_rescale
         UpperCAmelCase_										=					rescale_factor if rescale_factor is not None else self.rescale_factor
         UpperCAmelCase_										=					do_normalize if do_normalize is not None else self.do_normalize
         UpperCAmelCase_										=					image_mean if image_mean is not None else self.image_mean
         UpperCAmelCase_										=					image_std if image_std is not None else self.image_std

         UpperCAmelCase_										=					size if size is not None else self.size
         UpperCAmelCase_										=					get_size_dict(__snake_case ,   default_to_square=__snake_case    )
         UpperCAmelCase_										=					crop_size if crop_size is not None else self.crop_size
         UpperCAmelCase_										=					get_size_dict(__snake_case ,   param_name='''crop_size'''    )

         UpperCAmelCase_										=					make_list_of_images(__snake_case    )

         if not valid_images(__snake_case    ):
             raise ValueError(
                 '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
                 '''torch.Tensor, tf.Tensor or jax.ndarray.'''    )

         if do_resize and size is None:
             raise ValueError('''Size must be specified if do_resize is True.'''    )

         if do_center_crop and crop_size is None:
             raise ValueError('''Crop size must be specified if do_center_crop is True.'''    )

         if do_rescale and rescale_factor is None:
             raise ValueError('''Rescale factor must be specified if do_rescale is True.'''    )

         if do_normalize and (image_mean is None or image_std is None):
             raise ValueError('''Image mean and std must be specified if do_normalize is True.'''    )

         # All transformations expect numpy arrays.
         UpperCAmelCase_										=					[to_numpy_array(__snake_case    ) for image in images]

         if do_resize:
             UpperCAmelCase_										=					[self.resize(__snake_case ,   __snake_case ,   __snake_case    ) for image in images]

         if do_center_crop:
             UpperCAmelCase_										=					[self.center_crop(__snake_case ,   __snake_case    ) for image in images]

         if do_rescale:
             UpperCAmelCase_										=					[self.rescale(__snake_case ,   __snake_case    ) for image in images]

         if do_normalize:
             UpperCAmelCase_										=					[self.normalize(__snake_case ,   __snake_case ,   __snake_case    ) for image in images]

         UpperCAmelCase_										=					[to_channel_dimension_format(__snake_case ,   __snake_case    ) for image in images]

         UpperCAmelCase_										=					{'''pixel_values''': images}
         return BatchFeature(data=__snake_case ,   tensor_type=__snake_case    )





