




"""simple docstring"""





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      a__				(	__magic_name__   ):
			lowercase_    =	["input_values", "attention_mask"]


			def __init__(      self      :    Union[str, Any]      ,  UpperCamelCase_      :    int = 1      ,  UpperCamelCase_      :    int = 16000      ,  UpperCamelCase_      :    float = 0.0      ,  UpperCamelCase_      :    bool = False      ,  UpperCamelCase_      :    int = 80      ,  UpperCamelCase_      :    int = 16      ,  UpperCamelCase_      :    int = 64      ,  UpperCamelCase_      :    str = "hann_window"      ,  UpperCamelCase_      :    float = 1.0      ,  UpperCamelCase_      :    float = 80      ,  UpperCamelCase_      :    float = 7600      ,  UpperCamelCase_      :    float = 1e-10      ,  UpperCamelCase_      :    int = 2      ,  UpperCamelCase_      :    bool = True      ,  **UpperCamelCase_      :    Union[str, Any]      ,  ):


						"""simple docstring"""




						super().__init__(feature_size=UpperCamelCase_      ,  sampling_rate=UpperCamelCase_      ,  padding_value=UpperCamelCase_      ,  **UpperCamelCase_)
						__UpperCAmelCase	: Optional[int]		=					do_normalize
						__UpperCAmelCase	: int		=					return_attention_mask

						__UpperCAmelCase	: List[Any]		=					num_mel_bins
						__UpperCAmelCase	: int		=					hop_length
						__UpperCAmelCase	: Tuple		=					win_length
						__UpperCAmelCase	: Any		=					win_function
						__UpperCAmelCase	: Union[str, Any]		=					frame_signal_scale
						__UpperCAmelCase	: Optional[int]		=					fmin
						__UpperCAmelCase	: int		=					fmax
						__UpperCAmelCase	: Dict		=					mel_floor
						__UpperCAmelCase	: Optional[int]		=					reduction_factor

						__UpperCAmelCase	: Union[str, Any]		=					win_length * sampling_rate // 1000
						__UpperCAmelCase	: Tuple		=					hop_length * sampling_rate // 1000
						__UpperCAmelCase	: int		=					optimal_fft_length(self.sample_size)
						__UpperCAmelCase	: Tuple		=					(self.n_fft // 2) + 1

						__UpperCAmelCase	: List[Any]		=					window_function(window_length=self.sample_size      ,  name=self.win_function      ,  periodic=UpperCamelCase_)

						__UpperCAmelCase	: Union[str, Any]		=					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"      ,  UpperCamelCase_      ,  )
						if reduction_factor != 2.0:
									warnings.warn(
									    "The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers"      ,  UpperCamelCase_      ,  )


			@staticmethod
			# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
			def       a_     (      UpperCamelCase_      :    List[np.ndarray]      ,  UpperCamelCase_      :    List[np.ndarray]      ,  UpperCamelCase_      :    float = 0.0):


						"""simple docstring"""




						if attention_mask is not None:
									__UpperCAmelCase	: Tuple		=					np.array(UpperCamelCase_      ,  np.intaa)
									__UpperCAmelCase	: int		=					[]

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

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

						return normed_input_values


			def       a_     (      self      :    List[str]      ,  UpperCamelCase_      :    np.ndarray      ,  ):


						"""simple docstring"""




						__UpperCAmelCase	: Any		=					spectrogram(
						    UpperCamelCase_      ,  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      :    int      ,  UpperCamelCase_      :    Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None      ,  UpperCamelCase_      :    Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None      ,  UpperCamelCase_      :    Union[bool, str, PaddingStrategy] = False      ,  UpperCamelCase_      :    Optional[int] = None      ,  UpperCamelCase_      :    bool = False      ,  UpperCamelCase_      :    Optional[int] = None      ,  UpperCamelCase_      :    Optional[bool] = None      ,  UpperCamelCase_      :    Optional[Union[str, TensorType]] = None      ,  UpperCamelCase_      :    Optional[int] = None      ,  **UpperCamelCase_      :    int      ,  ):


						"""simple docstring"""




						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	: List[Any]		=					self._process_audio(
									    UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_      ,  **UpperCamelCase_      ,  )
						else:
									__UpperCAmelCase	: Tuple		=					None

						if audio_target is not None:
									__UpperCAmelCase	: List[str]		=					self._process_audio(
									    UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_      ,  **UpperCamelCase_      ,  )

									if inputs is None:
												return inputs_target
									else:
												__UpperCAmelCase	: Union[str, Any]		=					inputs_target["input_values"]
												__UpperCAmelCase	: Any		=					inputs_target.get("attention_mask")
												if decoder_attention_mask is not None:
															__UpperCAmelCase	: Any		=					decoder_attention_mask

						return inputs


			def       a_     (      self      :    Any      ,  UpperCamelCase_      :    Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]      ,  UpperCamelCase_      :    bool = False      ,  UpperCamelCase_      :    Union[bool, str, PaddingStrategy] = False      ,  UpperCamelCase_      :    Optional[int] = None      ,  UpperCamelCase_      :    bool = False      ,  UpperCamelCase_      :    Optional[int] = None      ,  UpperCamelCase_      :    Optional[bool] = None      ,  UpperCamelCase_      :    Optional[Union[str, TensorType]] = None      ,  **UpperCamelCase_      :    List[Any]      ,  ):


						"""simple docstring"""




						__UpperCAmelCase	: List[Any]		=					isinstance(UpperCamelCase_      ,  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	: int		=					is_batched_numpy or (
						    isinstance(UpperCamelCase_      ,  (list, tuple)) and (isinstance(speech[0]      ,  (np.ndarray, tuple, list)))
						)

						if is_batched:
									__UpperCAmelCase	: int		=					[np.asarray(UpperCamelCase_      ,  dtype=np.floataa) for speech in speech]
						elif not is_batched and not isinstance(UpperCamelCase_      ,  np.ndarray):
									__UpperCAmelCase	: Any		=					np.asarray(UpperCamelCase_      ,  dtype=np.floataa)
						elif isinstance(UpperCamelCase_      ,  np.ndarray) and speech.dtype is np.dtype(np.floataa):
									__UpperCAmelCase	: List[str]		=					speech.astype(np.floataa)

						# always return batch
						if not is_batched:
									__UpperCAmelCase	: Union[str, Any]		=					[speech]

						# needed to make pad() work on spectrogram inputs
						__UpperCAmelCase	: List[Any]		=					self.feature_size

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

						__UpperCAmelCase	: int		=					self.pad(
						    UpperCamelCase_      ,  padding=UpperCamelCase_      ,  max_length=UpperCamelCase_      ,  truncation=UpperCamelCase_      ,  pad_to_multiple_of=UpperCamelCase_      ,  return_attention_mask=UpperCamelCase_      ,  **UpperCamelCase_      ,  )

						__UpperCAmelCase	: Optional[int]		=					feature_size_hack

						# convert input values to correct format
						__UpperCAmelCase	: Tuple		=					padded_inputs["input_values"]
						if not isinstance(input_values[0]      ,  np.ndarray):
									__UpperCAmelCase	: List[str]		=					[np.asarray(UpperCamelCase_      ,  dtype=np.floataa) for array in input_values]
						elif (
						    not isinstance(UpperCamelCase_      ,  np.ndarray)
						    and isinstance(input_values[0]      ,  np.ndarray)
						    and input_values[0].dtype is np.dtype(np.floataa)
						):
									__UpperCAmelCase	: List[Any]		=					[array.astype(np.floataa) for array in input_values]
						elif isinstance(UpperCamelCase_      ,  np.ndarray) and input_values.dtype is np.dtype(np.floataa):
									__UpperCAmelCase	: Union[str, Any]		=					input_values.astype(np.floataa)

						# convert attention_mask to correct format
						__UpperCAmelCase	: Union[str, Any]		=					padded_inputs.get("attention_mask")
						if attention_mask is not None:
									__UpperCAmelCase	: int		=					[np.asarray(UpperCamelCase_      ,  dtype=np.intaa) for array in attention_mask]

						# zero-mean and unit-variance normalization
						if not is_target and self.do_normalize:
									__UpperCAmelCase	: List[Any]		=					(
									    attention_mask
									    if self._get_padding_strategies(UpperCamelCase_      ,  max_length=UpperCamelCase_) is not PaddingStrategy.DO_NOT_PAD
									    else None
									)
									__UpperCAmelCase	: Tuple		=					self.zero_mean_unit_var_norm(
									    padded_inputs["input_values"]      ,  attention_mask=UpperCamelCase_      ,  padding_value=self.padding_value)

						if return_tensors is not None:
									__UpperCAmelCase	: int		=					padded_inputs.convert_to_tensors(UpperCamelCase_)

						return padded_inputs


			def       a_     (      self      :    Optional[Any]):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[Any]		=					super().to_dict()

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

						return output








"""simple docstring"""





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_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_valid_image,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
					import PIL


A   =       logging.get_logger(__name__)

def 					_UpperCamelCase    (			UpperCamelCase							)			->			List[List[ImageInput]]:


			"""simple docstring"""
			if isinstance(UpperCamelCase				,       (list, tuple)							) and isinstance(videos[0]				,       (list, tuple)							) and is_valid_image(videos[0][0]							):
						return videos

			elif isinstance(UpperCamelCase				,       (list, tuple)							) and is_valid_image(videos[0]							):
						return [videos]

			elif is_valid_image(UpperCamelCase							):
						return [[videos]]

			raise ValueError(f"Could not make batched video from {videos}"							)





class      a__				(	__magic_name__   ):
			lowercase_    =	["pixel_values"]


			def __init__(      self      :    Tuple      ,  UpperCamelCase_      :    bool = True      ,  UpperCamelCase_      :    Dict[str, int] = None      ,  UpperCamelCase_      :    PILImageResampling = PILImageResampling.BILINEAR      ,  UpperCamelCase_      :    bool = True      ,  UpperCamelCase_      :    Dict[str, int] = None      ,  UpperCamelCase_      :    bool = True      ,  UpperCamelCase_      :    Union[int, float] = 1 / 255      ,  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_)
						__UpperCAmelCase	: Dict		=					size if size is not None else {"shortest_edge": 224}
						__UpperCAmelCase	: Union[str, Any]		=					get_size_dict(UpperCamelCase_      ,  default_to_square=UpperCamelCase_)
						__UpperCAmelCase	: Optional[int]		=					crop_size if crop_size is not None else {"height": 224, "width": 224}
						__UpperCAmelCase	: List[str]		=					get_size_dict(UpperCamelCase_      ,  param_name="crop_size")

						__UpperCAmelCase	: Optional[Any]		=					do_resize
						__UpperCAmelCase	: Union[str, Any]		=					size
						__UpperCAmelCase	: str		=					do_center_crop
						__UpperCAmelCase	: str		=					crop_size
						__UpperCAmelCase	: Any		=					resample
						__UpperCAmelCase	: List[Any]		=					do_rescale
						__UpperCAmelCase	: Union[str, Any]		=					rescale_factor
						__UpperCAmelCase	: List[Any]		=					do_normalize
						__UpperCAmelCase	: Dict		=					image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
						__UpperCAmelCase	: Tuple		=					image_std if image_std is not None else IMAGENET_STANDARD_STD


			def       a_     (      self      :    int      ,  UpperCamelCase_      :    np.ndarray      ,  UpperCamelCase_      :    Dict[str, int]      ,  UpperCamelCase_      :    PILImageResampling = PILImageResampling.BILINEAR      ,  UpperCamelCase_      :    Optional[Union[str, ChannelDimension]] = None      ,  **UpperCamelCase_      :    List[Any]      ,  ):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[Any]		=					get_size_dict(UpperCamelCase_      ,  default_to_square=UpperCamelCase_)
						if "shortest_edge" in size:
									__UpperCAmelCase	: Dict		=					get_resize_output_image_size(UpperCamelCase_      ,  size["shortest_edge"]      ,  default_to_square=UpperCamelCase_)
						elif "height" in size and "width" in size:
									__UpperCAmelCase	: Dict		=					(size["height"], size["width"])
						else:
									raise ValueError(F"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}")
						return resize(UpperCamelCase_      ,  size=UpperCamelCase_      ,  resample=UpperCamelCase_      ,  data_format=UpperCamelCase_      ,  **UpperCamelCase_)


			def       a_     (      self      :    List[str]      ,  UpperCamelCase_      :    np.ndarray      ,  UpperCamelCase_      :    Dict[str, int]      ,  UpperCamelCase_      :    Optional[Union[str, ChannelDimension]] = None      ,  **UpperCamelCase_      :    Tuple      ,  ):


						"""simple docstring"""




						__UpperCAmelCase	: int		=					get_size_dict(UpperCamelCase_)
						if "height" not in size or "width" not in size:
									raise ValueError(F"Size must have 'height' and 'width' as keys. Got {size.keys()}")
						return center_crop(UpperCamelCase_      ,  size=(size["height"], size["width"])      ,  data_format=UpperCamelCase_      ,  **UpperCamelCase_)


			def       a_     (      self      :    Optional[int]      ,  UpperCamelCase_      :    np.ndarray      ,  UpperCamelCase_      :    Union[int, float]      ,  UpperCamelCase_      :    Optional[Union[str, ChannelDimension]] = None      ,  **UpperCamelCase_      :    Optional[int]      ,  ):


						"""simple docstring"""




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


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


						"""simple docstring"""




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


			def       a_     (      self      :    List[str]      ,  UpperCamelCase_      :    ImageInput      ,  UpperCamelCase_      :    bool = None      ,  UpperCamelCase_      :    Dict[str, 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[ChannelDimension] = ChannelDimension.FIRST      ,  ):


						"""simple docstring"""




						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_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	: List[str]		=					to_numpy_array(UpperCamelCase_)

						if do_resize:
									__UpperCAmelCase	: Tuple		=					self.resize(image=UpperCamelCase_      ,  size=UpperCamelCase_      ,  resample=UpperCamelCase_)

						if do_center_crop:
									__UpperCAmelCase	: str		=					self.center_crop(UpperCamelCase_      ,  size=UpperCamelCase_)

						if do_rescale:
									__UpperCAmelCase	: Union[str, Any]		=					self.rescale(image=UpperCamelCase_      ,  scale=UpperCamelCase_)

						if do_normalize:
									__UpperCAmelCase	: Optional[int]		=					self.normalize(image=UpperCamelCase_      ,  mean=UpperCamelCase_      ,  std=UpperCamelCase_)

						__UpperCAmelCase	: Any		=					to_channel_dimension_format(UpperCamelCase_      ,  UpperCamelCase_)
						return image


			def       a_     (      self      :    List[Any]      ,  UpperCamelCase_      :    ImageInput      ,  UpperCamelCase_      :    bool = None      ,  UpperCamelCase_      :    Dict[str, 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_      :    Optional[int]      ,  ):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[Any]		=					do_resize if do_resize is not None else self.do_resize
						__UpperCAmelCase	: Optional[Any]		=					resample if resample is not None else self.resample
						__UpperCAmelCase	: Any		=					do_center_crop if do_center_crop is not None else self.do_center_crop
						__UpperCAmelCase	: str		=					do_rescale if do_rescale is not None else self.do_rescale
						__UpperCAmelCase	: str		=					rescale_factor if rescale_factor is not None else self.rescale_factor
						__UpperCAmelCase	: Tuple		=					do_normalize if do_normalize is not None else self.do_normalize
						__UpperCAmelCase	: str		=					image_mean if image_mean is not None else self.image_mean
						__UpperCAmelCase	: Optional[Any]		=					image_std if image_std is not None else self.image_std

						__UpperCAmelCase	: Tuple		=					size if size is not None else self.size
						__UpperCAmelCase	: str		=					get_size_dict(UpperCamelCase_      ,  default_to_square=UpperCamelCase_)
						__UpperCAmelCase	: Any		=					crop_size if crop_size is not None else self.crop_size
						__UpperCAmelCase	: int		=					get_size_dict(UpperCamelCase_      ,  param_name="crop_size")

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

						__UpperCAmelCase	: Dict		=					make_batched(UpperCamelCase_)

						__UpperCAmelCase	: List[str]		=					[
						    [
						        self._preprocess_image(
						            image=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=UpperCamelCase_      ,  image_std=UpperCamelCase_      ,  data_format=UpperCamelCase_      ,  )
						        for img in video
						    ]
						    for video in videos
						]

						__UpperCAmelCase	: int		=					{"pixel_values": videos}
						return BatchFeature(data=UpperCamelCase_      ,  tensor_type=UpperCamelCase_)


