
"""simple docstring"""






import numpy as np
from PIL import Image



def      lowerCAmelCase__			(		__magic_name__			,   __magic_name__			,   __magic_name__      )						->Optional[int]:
			__lowercase       =       np.array(lowerCamelCase__      )
			if arr.shape[0] != arr.shape[1]:
						raise ValueError("The input array is not a square matrix"      )
			__lowercase       =       0
			__lowercase       =       0
			__lowercase       =       0
			__lowercase       =       0

			# compute the shape of the output matrix
			__lowercase       =       (arr.shape[0] - size) // stride + 1
			# initialize the output matrix with zeros of shape maxpool_shape
			__lowercase       =       np.zeros((maxpool_shape, maxpool_shape)      )

			while i < arr.shape[0]:
						if i + size > arr.shape[0]:
									# if the end of the matrix is reached, break
									break
						while j < arr.shape[1]:
									# if the end of the matrix is reached, break
									if j + size > arr.shape[1]:
												break
									# compute the maximum of the pooling matrix
									__lowercase       =       np.max(arr[i : i + size, j : j + size]      )
									# shift the pooling matrix by stride of column pixels
									j += stride
									mat_j += 1

						# shift the pooling matrix by stride of row pixels
						i += stride
						mat_i += 1

						# reset the column index to 0
						__lowercase       =       0
						__lowercase       =       0

			return updated_arr



def      lowerCAmelCase__			(		__magic_name__			,   __magic_name__			,   __magic_name__      )						->Union[str, Any]:
			__lowercase       =       np.array(lowerCamelCase__      )
			if arr.shape[0] != arr.shape[1]:
						raise ValueError("The input array is not a square matrix"      )
			__lowercase       =       0
			__lowercase       =       0
			__lowercase       =       0
			__lowercase       =       0

			# compute the shape of the output matrix
			__lowercase       =       (arr.shape[0] - size) // stride + 1
			# initialize the output matrix with zeros of shape avgpool_shape
			__lowercase       =       np.zeros((avgpool_shape, avgpool_shape)      )

			while i < arr.shape[0]:
						# if the end of the matrix is reached, break
						if i + size > arr.shape[0]:
									break
						while j < arr.shape[1]:
									# if the end of the matrix is reached, break
									if j + size > arr.shape[1]:
												break
									# compute the average of the pooling matrix
									__lowercase       =       int(np.average(arr[i : i + size, j : j + size]      )      )
									# shift the pooling matrix by stride of column pixels
									j += stride
									mat_j += 1

						# shift the pooling matrix by stride of row pixels
						i += stride
						mat_i += 1
						# reset the column index to 0
						__lowercase       =       0
						__lowercase       =       0

			return updated_arr


# Main Function
if __name__ == "__main__":
					from doctest import testmod

					testmod(name='''avgpooling''', verbose=True)

					# Loading the image
					_lowercase							=				Image.open('''path_to_image''')

					# Converting the image to numpy array and maxpooling, displaying the result
					# Ensure that the image is a square matrix

					Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()

					# Converting the image to numpy array and averagepooling, displaying the result
					# Ensure that the image is a square matrix

					Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()







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


__A							=logging.get_logger(__name__)




class        _SCREAMING_SNAKE_CASE	( snake_case_		):
	lowerCAmelCase__   =					['input_values', 'attention_mask']



	def __init__(       self		,    lowercase = 1		,    lowercase = 16000		,    lowercase = 0.0		,    lowercase = False		,    lowercase = 80		,    lowercase = 16		,    lowercase = 64		,    lowercase = "hann_window"		,    lowercase = 1.0		,    lowercase = 80		,    lowercase = 7600		,    lowercase = 1e-10		,    lowercase = 2		,    lowercase = True		,    **lowercase		,    )							->			int:
					super().__init__(feature_size=lowercase		,    sampling_rate=lowercase		,    padding_value=lowercase		,    **lowercase					)
					lowerCamelCase_         =     do_normalize
					lowerCamelCase_         =     return_attention_mask

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

					lowerCamelCase_         =     win_length * sampling_rate // 1000
					lowerCamelCase_         =     hop_length * sampling_rate // 1000
					lowerCamelCase_         =     optimal_fft_length(self.sample_size					)
					lowerCamelCase_         =     (self.n_fft // 2) + 1

					lowerCamelCase_         =     window_function(window_length=self.sample_size		,    name=self.win_function		,    periodic=lowercase					)

					lowerCamelCase_         =     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        SCREAMING_SNAKE_CASE_(       lowercase		,    lowercase		,    lowercase = 0.0					)							->			List[np.ndarray]:
					if attention_mask is not None:
									lowerCamelCase_         =     np.array(lowercase		,    np.intaa					)
									lowerCamelCase_         =     []

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

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

					return normed_input_values



	def        SCREAMING_SNAKE_CASE_(       self		,    lowercase		,    )							->			np.ndarray:
					lowerCamelCase_         =     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		,    lowercase = None		,    lowercase = None		,    lowercase = False		,    lowercase = None		,    lowercase = False		,    lowercase = None		,    lowercase = None		,    lowercase = None		,    lowercase = None		,    **lowercase		,    )							->			BatchFeature:
					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:
									lowerCamelCase_         =     self._process_audio(
									    lowercase		,    lowercase		,    lowercase		,    lowercase		,    lowercase		,    lowercase		,    lowercase		,    lowercase		,    **lowercase		,    )
					else:
									lowerCamelCase_         =     None

					if audio_target is not None:
									lowerCamelCase_         =     self._process_audio(
									    lowercase		,    lowercase		,    lowercase		,    lowercase		,    lowercase		,    lowercase		,    lowercase		,    lowercase		,    **lowercase		,    )

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

					return inputs



	def        SCREAMING_SNAKE_CASE_(       self		,    lowercase		,    lowercase = False		,    lowercase = False		,    lowercase = None		,    lowercase = False		,    lowercase = None		,    lowercase = None		,    lowercase = None		,    **lowercase		,    )							->			BatchFeature:
					lowerCamelCase_         =     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}'					)
					lowerCamelCase_         =     is_batched_numpy or (
					    isinstance(lowercase		,    (list, tuple)					) and (isinstance(speech[0]		,    (np.ndarray, tuple, list)					))
					)

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

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

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

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

					lowerCamelCase_         =     self.pad(
					    lowercase		,    padding=lowercase		,    max_length=lowercase		,    truncation=lowercase		,    pad_to_multiple_of=lowercase		,    return_attention_mask=lowercase		,    **lowercase		,    )

					lowerCamelCase_         =     feature_size_hack

					# convert input values to correct format
					lowerCamelCase_         =     padded_inputs["input_values"]
					if not isinstance(input_values[0]		,    np.ndarray					):
									lowerCamelCase_         =     [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					)
					):
									lowerCamelCase_         =     [array.astype(np.floataa					) for array in input_values]
					elif isinstance(lowercase		,    np.ndarray					) and input_values.dtype is np.dtype(np.floataa					):
									lowerCamelCase_         =     input_values.astype(np.floataa					)

					# convert attention_mask to correct format
					lowerCamelCase_         =     padded_inputs.get("attention_mask"					)
					if attention_mask is not None:
									lowerCamelCase_         =     [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:
									lowerCamelCase_         =     (
									    attention_mask
									    if self._get_padding_strategies(lowercase		,    max_length=lowercase					) is not PaddingStrategy.DO_NOT_PAD
									    else None
									)
									lowerCamelCase_         =     self.zero_mean_unit_var_norm(
									    padded_inputs["input_values"]		,    attention_mask=lowercase		,    padding_value=self.padding_value					)

					if return_tensors is not None:
									lowerCamelCase_         =     padded_inputs.convert_to_tensors(lowercase					)

					return padded_inputs



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Dict[str, Any]:
					lowerCamelCase_         =     super().to_dict()

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

					return output


