

from math import ceil
from typing import List, Optional, Union

import numpy as np

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


A__						=							logging.get_logger(__name__)

class 				__UpperCamelCase				(					_SCREAMING_SNAKE_CASE			):
	_lowercase  :   Any       				=  ["audio_values", "audio_mask"]







	def __init__(   self: List[str]  , __UpperCamelCase: Optional[Any]=20_48  , __UpperCamelCase: Optional[Any]=1  , __UpperCamelCase: Optional[int]=[16, 16]  , __UpperCamelCase: Tuple=1_28  , __UpperCamelCase: List[str]=4_41_00  , __UpperCamelCase: List[Any]=86  , __UpperCamelCase: Optional[int]=20_48  , __UpperCamelCase: List[Any]=0.0  , **__UpperCamelCase: int  , ):

						'''simple docstring'''





						super().__init__(
						    feature_size=A_  , sampling_rate=A_  , padding_value=A_  , **A_  , )

						__magic_name__							=    spectrogram_length
						__magic_name__							=    num_channels
						__magic_name__							=    patch_size
						__magic_name__							=    feature_size // self.patch_size[1]
						__magic_name__							=    n_fft
						__magic_name__							=    sampling_rate // hop_length_to_sampling_rate
						__magic_name__							=    sampling_rate
						__magic_name__							=    padding_value
						__magic_name__							=    mel_filter_bank(
						    num_frequency_bins=1 + n_fft // 2  , num_mel_filters=A_  , min_frequency=0.0  , max_frequency=2_20_50.0  , sampling_rate=A_  , norm='slaney'  , mel_scale='slaney'  , ).T







	def 	_SCREAMING_SNAKE_CASE							(   self: Any  , __UpperCamelCase: int      ):

						'''simple docstring'''





						__magic_name__							=    spectrogram(
						    A_  , window_function(self.n_fft  , 'hann'      )  , frame_length=self.n_fft  , hop_length=self.hop_length  , power=2.0  , mel_filters=self.mel_filters.T  , log_mel='dB'  , db_range=80.0  , )
						__magic_name__							=    log_spec[:, :-1]
						__magic_name__							=    log_spec - 20.0
						__magic_name__							=    np.clip(log_spec / 40.0  , -2.0  , 0.0      ) + 1.0
						return log_spec







	def __call__(   self: Dict  , __UpperCamelCase: str  , __UpperCamelCase: Optional[Any] = None  , __UpperCamelCase: Any = True  , __UpperCamelCase: Tuple = None  , __UpperCamelCase: Optional[Any] = False  , __UpperCamelCase: List[Any] = False  , **__UpperCamelCase: Union[str, Any]  , ):

						'''simple docstring'''





						if sampling_rate is not None:
											if sampling_rate != self.sampling_rate:
																raise ValueError(
																    'This feature extractor is set to support sampling rate'
																    F' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled'
																    F' 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.'      )

						__magic_name__							=    isinstance(A_  , 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}'      )
						__magic_name__							=    is_batched_numpy or (
						    isinstance(A_  , (list, tuple)      ) and (isinstance(raw_speech[0]  , (np.ndarray, tuple, list)      ))
						)
						if is_batched:
											__magic_name__							=    [np.asarray([speech]  , dtype=np.floataa      ).T for speech in raw_speech]
						elif not is_batched and not isinstance(A_  , np.ndarray      ):
											__magic_name__							=    np.asarray(A_  , dtype=np.floataa      )
						elif isinstance(A_  , np.ndarray      ) and raw_speech.dtype is np.dtype(np.floataa      ):
											__magic_name__							=    raw_speech.astype(np.floataa      )
						# always return batch
						if not is_batched:
											__magic_name__							=    [np.asarray([raw_speech]      ).T]

						# Convert audio signals to log mel spectrograms, truncate by time axis
						__magic_name__							=    [
						    self._np_extract_fbank_features(waveform.squeeze()      ).T[: self.spectrogram_length] for waveform in raw_speech
						]
						if isinstance(audio_features[0]  , A_      ):
											__magic_name__							=    [np.asarray(A_  , dtype=np.floataa      ) for feature in audio_features]

						# Create audio attention mask
						__magic_name__							=    max(
						    [ceil(feature.shape[0] / self.patch_size[0]      ) * self.freq_len for feature in audio_features]      )  # The maximum number of audio patches in a batch
						if return_attention_mask:
											__magic_name__							=    [
											    (ceil(feature.shape[0] / self.patch_size[0]      ) * self.freq_len) * [1]
											    + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]      ) * self.freq_len) * [0]
											    for feature in audio_features
											]
											__magic_name__							=    np.array(A_      ).astype(np.floataa      )

						# convert into correct format for padding
						__magic_name__							=    max_patch_len // self.freq_len * self.patch_size[0]  # The maximum audio size in a batch
						__magic_name__							=    np.ones([len(A_      ), 1, max_time_len, self.feature_size]      ).astype(np.floataa      )
						__magic_name__							=    padded_audio_features * self.padding_value
						for i in range(len(A_      )      ):
											__magic_name__							=    audio_features[i]
											__magic_name__							=    feature

						# return as BatchFeature
						if return_attention_mask:
											__magic_name__							=    {'audio_values': padded_audio_features, 'audio_mask': audio_mask}
						else:
											__magic_name__							=    {'audio_values': padded_audio_features}

						__magic_name__							=    BatchFeature(data=A_  , tensor_type=A_      )
						return encoded_inputs







from typing import Dict, 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, is_vision_available, logging


if is_vision_available():
						import PIL


A__						=							logging.get_logger(__name__)

class 				__UpperCamelCase				(					SCREAMING_SNAKE_CASE			):
	_lowercase  :   Tuple       				=  ["pixel_values"]







	def __init__(   self: Optional[Any]  , __UpperCamelCase: bool = True  , __UpperCamelCase: Dict[str, int] = None  , __UpperCamelCase: int = 0.9  , __UpperCamelCase: PILImageResampling = PILImageResampling.BICUBIC  , __UpperCamelCase: bool = True  , __UpperCamelCase: Dict[str, int] = None  , __UpperCamelCase: Union[int, float] = 1 / 2_55  , __UpperCamelCase: bool = True  , __UpperCamelCase: bool = True  , __UpperCamelCase: Optional[Union[float, List[float]]] = None  , __UpperCamelCase: Optional[Union[float, List[float]]] = None  , **__UpperCamelCase: List[str]  , ):

						'''simple docstring'''





						super().__init__(**__UpperCamelCase      )
						__magic_name__							=    size if size is not None else {'shortest_edge': 2_24}
						__magic_name__							=    get_size_dict(__UpperCamelCase  , default_to_square=__UpperCamelCase      )
						__magic_name__							=    crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24}
						__magic_name__							=    get_size_dict(__UpperCamelCase  , param_name='crop_size'      )

						__magic_name__							=    do_resize
						__magic_name__							=    size
						__magic_name__							=    crop_pct
						__magic_name__							=    resample
						__magic_name__							=    do_center_crop
						__magic_name__							=    crop_size
						__magic_name__							=    do_rescale
						__magic_name__							=    rescale_factor
						__magic_name__							=    do_normalize
						__magic_name__							=    image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
						__magic_name__							=    image_std if image_std is not None else IMAGENET_DEFAULT_STD







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]  , __UpperCamelCase: np.ndarray  , __UpperCamelCase: Dict[str, int]  , __UpperCamelCase: Optional[float] = None  , __UpperCamelCase: PILImageResampling = PILImageResampling.BICUBIC  , __UpperCamelCase: Optional[Union[str, ChannelDimension]] = None  , **__UpperCamelCase: Optional[Any]  , ):

						'''simple docstring'''





						__magic_name__							=    get_size_dict(__UpperCamelCase  , default_to_square=__UpperCamelCase      )
						if "shortest_edge" not in size and ("height" not in size or "width" not in size):
											raise ValueError(F'size must contain \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'      )
						if crop_pct is not None:
											if "shortest_edge" in size:
																__magic_name__							=    int(size['shortest_edge'] / crop_pct      )
											elif "height" in size and "width" in size:
																if size["height"] == size["width"]:
																					__magic_name__							=    int(size['height'] / crop_pct      )
																else:
																					__magic_name__							=    (int(size['height'] / crop_pct      ), int(size['width'] / crop_pct      ))
											else:
																raise ValueError('Invalid size for resize: {}'.format(__UpperCamelCase      )      )

											__magic_name__							=    get_resize_output_image_size(__UpperCamelCase  , size=__UpperCamelCase  , default_to_square=__UpperCamelCase      )
						else:
											if "shortest_edge" in size:
																__magic_name__							=    get_resize_output_image_size(__UpperCamelCase  , size=size['shortest_edge']  , default_to_square=__UpperCamelCase      )
											elif "height" in size and "width" in size:
																__magic_name__							=    (size['height'], size['width'])
											else:
																raise ValueError('Invalid size for resize: {}'.format(__UpperCamelCase      )      )

						return resize(__UpperCamelCase  , size=__UpperCamelCase  , resample=__UpperCamelCase  , data_format=__UpperCamelCase  , **__UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Any  , __UpperCamelCase: np.ndarray  , __UpperCamelCase: Dict[str, int]  , __UpperCamelCase: Optional[Union[str, ChannelDimension]] = None  , **__UpperCamelCase: List[str]  , ):

						'''simple docstring'''





						__magic_name__							=    get_size_dict(__UpperCamelCase      )
						if "height" not in size or "width" not in size:
											raise ValueError(F'size must contain \'height\' and \'width\' as keys. Got {size.keys()}'      )
						return center_crop(__UpperCamelCase  , size=(size['height'], size['width'])  , data_format=__UpperCamelCase  , **__UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]  , __UpperCamelCase: np.ndarray  , __UpperCamelCase: Union[int, float]  , __UpperCamelCase: Optional[Union[str, ChannelDimension]] = None  , **__UpperCamelCase: Optional[Any]  , ):

						'''simple docstring'''





						return rescale(__UpperCamelCase  , scale=__UpperCamelCase  , data_format=__UpperCamelCase  , **__UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Dict  , __UpperCamelCase: np.ndarray  , __UpperCamelCase: Union[float, List[float]]  , __UpperCamelCase: Union[float, List[float]]  , __UpperCamelCase: Optional[Union[str, ChannelDimension]] = None  , **__UpperCamelCase: Optional[int]  , ):

						'''simple docstring'''





						return normalize(__UpperCamelCase  , mean=__UpperCamelCase  , std=__UpperCamelCase  , data_format=__UpperCamelCase  , **__UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Union[str, Any]  , __UpperCamelCase: ImageInput  , __UpperCamelCase: bool = None  , __UpperCamelCase: Dict[str, int] = None  , __UpperCamelCase: int = None  , __UpperCamelCase: PILImageResampling = None  , __UpperCamelCase: bool = None  , __UpperCamelCase: Dict[str, int] = None  , __UpperCamelCase: bool = None  , __UpperCamelCase: float = None  , __UpperCamelCase: bool = None  , __UpperCamelCase: Optional[Union[float, List[float]]] = None  , __UpperCamelCase: Optional[Union[float, List[float]]] = None  , __UpperCamelCase: Optional[Union[str, TensorType]] = None  , __UpperCamelCase: ChannelDimension = ChannelDimension.FIRST  , **__UpperCamelCase: Any  , ):

						'''simple docstring'''





						__magic_name__							=    do_resize if do_resize is not None else self.do_resize
						__magic_name__							=    crop_pct if crop_pct is not None else self.crop_pct
						__magic_name__							=    resample if resample is not None else self.resample
						__magic_name__							=    do_center_crop if do_center_crop is not None else self.do_center_crop
						__magic_name__							=    do_rescale if do_rescale is not None else self.do_rescale
						__magic_name__							=    rescale_factor if rescale_factor is not None else self.rescale_factor
						__magic_name__							=    do_normalize if do_normalize is not None else self.do_normalize
						__magic_name__							=    image_mean if image_mean is not None else self.image_mean
						__magic_name__							=    image_std if image_std is not None else self.image_std

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

						__magic_name__							=    make_list_of_images(__UpperCamelCase      )

						if not valid_images(__UpperCamelCase      ):
											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_center_crop and crop_pct is None:
											raise ValueError('Crop_pct 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.
						__magic_name__							=    [to_numpy_array(__UpperCamelCase      ) for image in images]

						if do_resize:
											__magic_name__							=    [self.resize(image=__UpperCamelCase  , size=__UpperCamelCase  , crop_pct=__UpperCamelCase  , resample=__UpperCamelCase      ) for image in images]

						if do_center_crop:
											__magic_name__							=    [self.center_crop(image=__UpperCamelCase  , size=__UpperCamelCase      ) for image in images]

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

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

						__magic_name__							=    [to_channel_dimension_format(__UpperCamelCase  , __UpperCamelCase      ) for image in images]

						__magic_name__							=    {'pixel_values': images}
						return BatchFeature(data=__UpperCamelCase  , tensor_type=__UpperCamelCase      )




