


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

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    is_torch_available,
    is_torch_tensor,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_torch_available():
		import torch

if is_vision_available():
		import PIL


lowerCAmelCase__  :List[Any]   			=							logging.get_logger(__name__)

def        lowerCAmelCase__ (			a__:		np.ndarray			,  a__:		Union[int, Iterable[int]]			,  a__:		bool			,  a__:		int       )  ->		Tuple[int, int]:


							'''simple docstring'''





							def constraint_to_multiple_of(a__:		Tuple			,  a__:		Dict			,  a__:		str=0			,  a__:		List[Any]=None       ):
														_UpperCAmelCase 		=			round(val / multiple       ) * multiple

														if max_val is not None and x > max_val:
																					_UpperCAmelCase 		=			math.floor(val / multiple       ) * multiple

														if x < min_val:
																					_UpperCAmelCase 		=			math.ceil(val / multiple       ) * multiple

														return x

							_UpperCAmelCase 		=			(output_size, output_size) if isinstance(A__			,  A__       ) else output_size

							_UpperCAmelCase		,       _UpperCAmelCase 		=			get_image_size(A__       )
							_UpperCAmelCase		,       _UpperCAmelCase 		=			output_size

							# determine new height and width
							_UpperCAmelCase 		=			output_height / input_height
							_UpperCAmelCase 		=			output_width / input_width

							if keep_aspect_ratio:
														# scale as little as possible
														if abs(1 - scale_width       ) < abs(1 - scale_height       ):
																					# fit width
																					_UpperCAmelCase 		=			scale_width
														else:
																					# fit height
																					_UpperCAmelCase 		=			scale_height

							_UpperCAmelCase 		=			constraint_to_multiple_of(scale_height * input_height			,  multiple=A__       )
							_UpperCAmelCase 		=			constraint_to_multiple_of(scale_width * input_width			,  multiple=A__       )

							return (new_height, new_width)







class 		__a      (				UpperCAmelCase			):
		_a	:  Dict				=	['pixel_values']
		def __init__(			self			,    _SCREAMING_SNAKE_CASE = True			,    _SCREAMING_SNAKE_CASE = None			,    _SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR			,    _SCREAMING_SNAKE_CASE = False			,    _SCREAMING_SNAKE_CASE = 1			,    _SCREAMING_SNAKE_CASE = True			,    _SCREAMING_SNAKE_CASE = 1 / 255			,    _SCREAMING_SNAKE_CASE = True			,    _SCREAMING_SNAKE_CASE = None			,    _SCREAMING_SNAKE_CASE = None			,    **_SCREAMING_SNAKE_CASE			,    ) ->       None:




									"""simple docstring"""





									super().__init__(**_SCREAMING_SNAKE_CASE						)
									_UpperCAmelCase 		=			size if size is not None else {'height': 384, 'width': 384}
									_UpperCAmelCase 		=			get_size_dict(_SCREAMING_SNAKE_CASE						)
									_UpperCAmelCase 		=			do_resize
									_UpperCAmelCase 		=			size
									_UpperCAmelCase 		=			keep_aspect_ratio
									_UpperCAmelCase 		=			ensure_multiple_of
									_UpperCAmelCase 		=			resample
									_UpperCAmelCase 		=			do_rescale
									_UpperCAmelCase 		=			rescale_factor
									_UpperCAmelCase 		=			do_normalize
									_UpperCAmelCase 		=			image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
									_UpperCAmelCase 		=			image_std if image_std is not None else IMAGENET_STANDARD_STD
		def 	UpperCAmelCase__				(			self			,    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE = False			,    _SCREAMING_SNAKE_CASE = 1			,    _SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC			,    _SCREAMING_SNAKE_CASE = None			,    **_SCREAMING_SNAKE_CASE			,    ) ->       np.ndarray:




									"""simple docstring"""





									_UpperCAmelCase 		=			get_size_dict(_SCREAMING_SNAKE_CASE						)
									if "height" not in size or "width" not in size:
																raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}'''						)
									_UpperCAmelCase 		=			get_resize_output_image_size(
									    _SCREAMING_SNAKE_CASE			,    output_size=(size['height'], size['width'])			,    keep_aspect_ratio=_SCREAMING_SNAKE_CASE			,    multiple=_SCREAMING_SNAKE_CASE			,    )
									return resize(_SCREAMING_SNAKE_CASE			,    size=_SCREAMING_SNAKE_CASE			,    resample=_SCREAMING_SNAKE_CASE			,    data_format=_SCREAMING_SNAKE_CASE			,    **_SCREAMING_SNAKE_CASE						)
		def 	UpperCAmelCase__				(			self			,    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE = None			,    **_SCREAMING_SNAKE_CASE			,    ) ->       str:




									"""simple docstring"""





									return rescale(_SCREAMING_SNAKE_CASE			,    scale=_SCREAMING_SNAKE_CASE			,    data_format=_SCREAMING_SNAKE_CASE			,    **_SCREAMING_SNAKE_CASE						)
		def 	UpperCAmelCase__				(			self			,    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE = None			,    **_SCREAMING_SNAKE_CASE			,    ) ->       np.ndarray:




									"""simple docstring"""





									return normalize(_SCREAMING_SNAKE_CASE			,    mean=_SCREAMING_SNAKE_CASE			,    std=_SCREAMING_SNAKE_CASE			,    data_format=_SCREAMING_SNAKE_CASE			,    **_SCREAMING_SNAKE_CASE						)
		def 	UpperCAmelCase__				(			self			,    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE = None			,    _SCREAMING_SNAKE_CASE = None			,    _SCREAMING_SNAKE_CASE = None			,    _SCREAMING_SNAKE_CASE = None			,    _SCREAMING_SNAKE_CASE = None			,    _SCREAMING_SNAKE_CASE = None			,    _SCREAMING_SNAKE_CASE = None			,    _SCREAMING_SNAKE_CASE = None			,    _SCREAMING_SNAKE_CASE = None			,    _SCREAMING_SNAKE_CASE = None			,    _SCREAMING_SNAKE_CASE = None			,    _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST			,    **_SCREAMING_SNAKE_CASE			,    ) ->       PIL.Image.Image:




									"""simple docstring"""





									_UpperCAmelCase 		=			do_resize if do_resize is not None else self.do_resize
									_UpperCAmelCase 		=			size if size is not None else self.size
									_UpperCAmelCase 		=			get_size_dict(_SCREAMING_SNAKE_CASE						)
									_UpperCAmelCase 		=			keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
									_UpperCAmelCase 		=			ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
									_UpperCAmelCase 		=			resample if resample is not None else self.resample
									_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 		=			make_list_of_images(_SCREAMING_SNAKE_CASE						)

									if not valid_images(_SCREAMING_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 or resample is None:
																raise ValueError('Size and resample must be specified if do_resize 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(_SCREAMING_SNAKE_CASE						) for image in images]

									if do_resize:
																_UpperCAmelCase 		=			[self.resize(image=_SCREAMING_SNAKE_CASE			,    size=_SCREAMING_SNAKE_CASE			,    resample=_SCREAMING_SNAKE_CASE						) for image in images]

									if do_rescale:
																_UpperCAmelCase 		=			[self.rescale(image=_SCREAMING_SNAKE_CASE			,    scale=_SCREAMING_SNAKE_CASE						) for image in images]

									if do_normalize:
																_UpperCAmelCase 		=			[self.normalize(image=_SCREAMING_SNAKE_CASE			,    mean=_SCREAMING_SNAKE_CASE			,    std=_SCREAMING_SNAKE_CASE						) for image in images]

									_UpperCAmelCase 		=			[to_channel_dimension_format(_SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE						) for image in images]

									_UpperCAmelCase 		=			{'pixel_values': images}
									return BatchFeature(data=_SCREAMING_SNAKE_CASE			,    tensor_type=_SCREAMING_SNAKE_CASE						)






		def 	UpperCAmelCase__				(			self			,    _SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE = None						) ->       List[Any]:




									"""simple docstring"""





									_UpperCAmelCase 		=			outputs.logits

									# Resize logits and compute semantic segmentation maps
									if target_sizes is not None:
																if len(_SCREAMING_SNAKE_CASE						) != len(_SCREAMING_SNAKE_CASE						):
																							raise ValueError(
																							    'Make sure that you pass in as many target sizes as the batch dimension of the logits'						)

																if is_torch_tensor(_SCREAMING_SNAKE_CASE						):
																							_UpperCAmelCase 		=			target_sizes.numpy()

																_UpperCAmelCase 		=			[]

																for idx in range(len(_SCREAMING_SNAKE_CASE						)						):
																							_UpperCAmelCase 		=			torch.nn.functional.interpolate(
																							    logits[idx].unsqueeze(dim=0						)			,    size=target_sizes[idx]			,    mode='bilinear'			,    align_corners=_SCREAMING_SNAKE_CASE						)
																							_UpperCAmelCase 		=			resized_logits[0].argmax(dim=0						)
																							semantic_segmentation.append(_SCREAMING_SNAKE_CASE						)
									else:
																_UpperCAmelCase 		=			logits.argmax(dim=1						)
																_UpperCAmelCase 		=			[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]						)]

									return semantic_segmentation



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

import numpy as np

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


lowercase_									=   logging.get_logger(__name__)





class  __lowerCAmelCase     (					SCREAMING_SNAKE_CASE							):
  _a									=  ["""input_features"""]




  def __init__(				self							,   lowerCAmelCase=80							,   lowerCAmelCase=16_000							,   lowerCAmelCase=160							,   lowerCAmelCase=30							,   lowerCAmelCase=400							,   lowerCAmelCase=0.0							,   lowerCAmelCase=False							,   **lowerCAmelCase							,   )  -> Any:
        '''simple docstring'''






        super().__init__(
            feature_size=lowerCAmelCase							,   sampling_rate=lowerCAmelCase							,   padding_value=lowerCAmelCase							,   return_attention_mask=lowerCAmelCase							,   **lowerCAmelCase							,   )
        _lowercase	       =n_fft
        _lowercase	       =hop_length
        _lowercase	       =chunk_length
        _lowercase	       =chunk_length * sampling_rate
        _lowercase	       =self.n_samples // hop_length
        _lowercase	       =sampling_rate
        _lowercase	       =mel_filter_bank(
            num_frequency_bins=1 + n_fft // 2							,   num_mel_filters=lowerCAmelCase							,   min_frequency=0.0							,   max_frequency=8000.0							,   sampling_rate=lowerCAmelCase							,   norm='slaney'							,   mel_scale='slaney'							,   )




  def   A__     (				self							,   lowerCAmelCase					)  -> np.ndarray:
        '''simple docstring'''






        _lowercase	       =spectrogram(
            lowerCAmelCase							,   window_function(self.n_fft							,   'hann'					)							,   frame_length=self.n_fft							,   hop_length=self.hop_length							,   power=2.0							,   mel_filters=self.mel_filters							,   log_mel='log10'							,   )
        _lowercase	       =log_spec[:, :-1]
        _lowercase	       =np.maximum(lowerCAmelCase							,   log_spec.max() - 8.0					)
        _lowercase	       =(log_spec + 4.0) / 4.0
        return log_spec




  @staticmethod
  # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
  def   A__     (				lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase = 0.0					)  -> List[np.ndarray]:
        '''simple docstring'''






        if attention_mask is not None:
              _lowercase	       =np.array(lowerCAmelCase							,   np.intaa					)
              _lowercase	       =[]

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

                    normed_input_values.append(lowerCAmelCase					)
        else:
              _lowercase	       =[(x - x.mean()) / np.sqrt(x.var() + 1e-7					) for x in input_values]

        return normed_input_values




  def __call__(				self							,   lowerCAmelCase							,   lowerCAmelCase = True							,   lowerCAmelCase = None							,   lowerCAmelCase = None							,   lowerCAmelCase = None							,   lowerCAmelCase = "max_length"							,   lowerCAmelCase = None							,   lowerCAmelCase = None							,   lowerCAmelCase = None							,   **lowerCAmelCase							,   )  -> BatchFeature:
        '''simple docstring'''






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

        _lowercase	       =isinstance(lowerCAmelCase							,   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}'''					)
        _lowercase	       =is_batched_numpy or (
            isinstance(lowerCAmelCase							,   (list, tuple)					) and (isinstance(raw_speech[0]							,   (np.ndarray, tuple, list)					))
        )

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

        # always return batch
        if not is_batched:
              _lowercase	       =[np.asarray([raw_speech]					).T]

        _lowercase	       =BatchFeature({'input_features': raw_speech}					)

        # convert into correct format for padding

        _lowercase	       =self.pad(
            lowerCAmelCase							,   padding=lowerCAmelCase							,   max_length=max_length if max_length else self.n_samples							,   truncation=lowerCAmelCase							,   pad_to_multiple_of=lowerCAmelCase							,   return_attention_mask=return_attention_mask or do_normalize							,   )

        # zero-mean and unit-variance normalization
        if do_normalize:
              _lowercase	       =self.zero_mean_unit_var_norm(
                  padded_inputs['input_features']							,   attention_mask=padded_inputs['attention_mask']							,   padding_value=self.padding_value							,   )
              _lowercase	       =np.stack(padded_inputs['input_features']							,   axis=0					)

        # make sure list is in array format
        _lowercase	       =padded_inputs.get('input_features'					).transpose(2							,   0							,   1					)

        _lowercase	       =[self._np_extract_fbank_features(lowerCAmelCase					) for waveform in input_features[0]]

        if isinstance(input_features[0]							,   lowerCAmelCase					):
              _lowercase	       =[np.asarray(lowerCAmelCase							,   dtype=np.floataa					) for feature in input_features]
        else:
              _lowercase	       =input_features

        if return_attention_mask:
              # rescale from sample (48000) to feature (3000)
              _lowercase	       =padded_inputs['attention_mask'][:, :: self.hop_length]

        if return_tensors is not None:
              _lowercase	       =padded_inputs.convert_to_tensors(lowerCAmelCase					)

        return padded_inputs




  def   A__     (				self					)  -> Dict[str, Any]:
        '''simple docstring'''






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


