
from typing import List, Optional, Union

import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


lowercase        =  logging.get_logger(__name__)





class       __A(				UpperCAmelCase       ):
					SCREAMING_SNAKE_CASE			    =    ['''input_features''', '''attention_mask''']

					def __init__(	self					:     int   ,					__UpperCamelCase					:     Union[str, Any]=8_0   ,					__UpperCamelCase					:     Tuple=1_6_0_0_0   ,					__UpperCamelCase					:     str=8_0   ,					__UpperCamelCase					:     Tuple=0.0   ,					__UpperCamelCase					:     Union[str, Any]=True   ,					__UpperCamelCase					:     List[str]=True   ,					__UpperCamelCase					:     Any=True   ,					**__UpperCamelCase					:     Any   ,					):
												super().__init__(feature_size=__UpperCamelCase   ,					sampling_rate=__UpperCamelCase   ,					padding_value=__UpperCamelCase   ,					**__UpperCamelCase   )
												lowerCamelCase_							  =					num_mel_bins
												lowerCamelCase_							  =					do_ceptral_normalize
												lowerCamelCase_							  =					normalize_means
												lowerCamelCase_							  =					normalize_vars
												lowerCamelCase_							  =					True

					def    lowercase__      (	self					:     List[Any]   ,					__UpperCamelCase					:     np.ndarray   ,					):
												lowerCamelCase_							  =					waveform * (2**1_5)  # Kaldi compliance: 16-bit signed integers
												lowerCamelCase_							  =					torch.from_numpy(__UpperCamelCase   ).unsqueeze(0   )
												lowerCamelCase_							  =					ta_kaldi.fbank(__UpperCamelCase   ,					num_mel_bins=self.num_mel_bins   ,					sample_frequency=self.sampling_rate   )
												return features.numpy()

					@staticmethod
					def    lowercase__      (	__UpperCamelCase					:     np.ndarray   ,					__UpperCamelCase					:     int   ,					__UpperCamelCase					:     Optional[bool] = True   ,					__UpperCamelCase					:     Optional[bool] = True   ,					__UpperCamelCase					:     float = 0.0   ,					):
												# make sure we normalize float32 arrays
												if normalize_means:
																			lowerCamelCase_							  =					x[:input_length].mean(axis=0   )
																			lowerCamelCase_							  =					np.subtract(__UpperCamelCase   ,					__UpperCamelCase   )
												if normalize_vars:
																			lowerCamelCase_							  =					x[:input_length].std(axis=0   )
																			lowerCamelCase_							  =					np.divide(__UpperCamelCase   ,					__UpperCamelCase   )

												if input_length < x.shape[0]:
																			lowerCamelCase_							  =					padding_value

												# make sure array is in float32
												lowerCamelCase_							  =					x.astype(np.floataa   )

												return x

					def    lowercase__      (	self					:     Tuple   ,					__UpperCamelCase					:     List[np.ndarray]   ,					__UpperCamelCase					:     Optional[np.ndarray] = None   ):
												lowerCamelCase_							  =					attention_mask.sum(-1   ) if attention_mask is not None else [x.shape[0] for x in input_features]
												return [
												    self.utterance_cmvn(__UpperCamelCase   ,					__UpperCamelCase   ,					self.normalize_means   ,					self.normalize_vars   ,					self.padding_value   )
												    for x, n in zip(__UpperCamelCase   ,					__UpperCamelCase   )
												]



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

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

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

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

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

												# extract fbank features
												lowerCamelCase_							  =					[self._extract_fbank_features(__UpperCamelCase   ) for waveform in raw_speech]

												# convert into correct format for padding
												lowerCamelCase_							  =					BatchFeature({"""input_features""": features}   )

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

												# make sure list is in array format
												lowerCamelCase_							  =					padded_inputs.get("""input_features"""   )
												if isinstance(input_features[0]   ,					__UpperCamelCase   ):
																			lowerCamelCase_							  =					[np.asarray(__UpperCamelCase   ,					dtype=np.floataa   ) for feature in input_features]

												lowerCamelCase_							  =					padded_inputs.get("""attention_mask"""   )
												if attention_mask is not None:
																			lowerCamelCase_							  =					[np.asarray(__UpperCamelCase   ,					dtype=np.intaa   ) for array in attention_mask]

												# Utterance-level cepstral mean and variance normalization
												if self.do_ceptral_normalize:
																			lowerCamelCase_							  =					(
																			    np.array(__UpperCamelCase   ,					dtype=np.intaa   )
																			    if self._get_padding_strategies(__UpperCamelCase   ,					max_length=__UpperCamelCase   ) is not PaddingStrategy.DO_NOT_PAD
																			    else None
																			)
																			lowerCamelCase_							  =					self.normalize(
																			    padded_inputs["""input_features"""]   ,					attention_mask=__UpperCamelCase   )

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

												return padded_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_STANDARD_MEAN,
    IMAGENET_STANDARD_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


lowercase        =  logging.get_logger(__name__)





class       __A(				UpperCAmelCase       ):
					SCREAMING_SNAKE_CASE			    =    ['''pixel_values''']

					def __init__(	self					:     Any   ,					__UpperCamelCase					:     bool = True   ,					__UpperCamelCase					:     Dict[str, int] = None   ,					__UpperCamelCase					:     float = None   ,					__UpperCamelCase					:     PILImageResampling = PILImageResampling.BILINEAR   ,					__UpperCamelCase					:     bool = True   ,					__UpperCamelCase					:     Union[int, float] = 1 / 2_5_5   ,					__UpperCamelCase					:     bool = True   ,					__UpperCamelCase					:     Optional[Union[float, List[float]]] = None   ,					__UpperCamelCase					:     Optional[Union[float, List[float]]] = None   ,					**__UpperCamelCase					:     Optional[int]   ,					):
												super().__init__(**__UpperCamelCase   )
												lowerCamelCase_							  =					size if size is not None else {"""shortest_edge""": 3_8_4}
												lowerCamelCase_							  =					get_size_dict(__UpperCamelCase   ,					default_to_square=__UpperCamelCase   )

												lowerCamelCase_							  =					do_resize
												lowerCamelCase_							  =					size
												# Default value set here for backwards compatibility where the value in config is None
												lowerCamelCase_							  =					crop_pct if crop_pct is not None else 2_2_4 / 2_5_6
												lowerCamelCase_							  =					resample
												lowerCamelCase_							  =					do_rescale
												lowerCamelCase_							  =					rescale_factor
												lowerCamelCase_							  =					do_normalize
												lowerCamelCase_							  =					image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
												lowerCamelCase_							  =					image_std if image_std is not None else IMAGENET_STANDARD_STD

					def    lowercase__      (	self					:     List[Any]   ,					__UpperCamelCase					:     np.ndarray   ,					__UpperCamelCase					:     Dict[str, int]   ,					__UpperCamelCase					:     float   ,					__UpperCamelCase					:     PILImageResampling = PILImageResampling.BICUBIC   ,					__UpperCamelCase					:     Optional[Union[str, ChannelDimension]] = None   ,					**__UpperCamelCase					:     Tuple   ,					):
												lowerCamelCase_							  =					get_size_dict(__UpperCamelCase   ,					default_to_square=__UpperCamelCase   )
												if "shortest_edge" not in size:
																			raise ValueError(F'''Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}'''   )
												lowerCamelCase_							  =					size["""shortest_edge"""]

												if shortest_edge < 3_8_4:
																			# maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
																			lowerCamelCase_							  =					int(shortest_edge / crop_pct   )
																			lowerCamelCase_							  =					get_resize_output_image_size(__UpperCamelCase   ,					size=__UpperCamelCase   ,					default_to_square=__UpperCamelCase   )
																			lowerCamelCase_							  =					resize(image=__UpperCamelCase   ,					size=__UpperCamelCase   ,					resample=__UpperCamelCase   ,					data_format=__UpperCamelCase   ,					**__UpperCamelCase   )
																			# then crop to (shortest_edge, shortest_edge)
																			return center_crop(image=__UpperCamelCase   ,					size=(shortest_edge, shortest_edge)   ,					data_format=__UpperCamelCase   ,					**__UpperCamelCase   )
												else:
																			# warping (no cropping) when evaluated at 384 or larger
																			return resize(
																			    __UpperCamelCase   ,					size=(shortest_edge, shortest_edge)   ,					resample=__UpperCamelCase   ,					data_format=__UpperCamelCase   ,					**__UpperCamelCase   )

					def    lowercase__      (	self					:     str   ,					__UpperCamelCase					:     np.ndarray   ,					__UpperCamelCase					:     Union[int, float]   ,					__UpperCamelCase					:     Optional[Union[str, ChannelDimension]] = None   ,					**__UpperCamelCase					:     int   ,					):
												return rescale(__UpperCamelCase   ,					scale=__UpperCamelCase   ,					data_format=__UpperCamelCase   ,					**__UpperCamelCase   )

					def    lowercase__      (	self					:     List[str]   ,					__UpperCamelCase					:     np.ndarray   ,					__UpperCamelCase					:     Union[float, List[float]]   ,					__UpperCamelCase					:     Union[float, List[float]]   ,					__UpperCamelCase					:     Optional[Union[str, ChannelDimension]] = None   ,					**__UpperCamelCase					:     List[str]   ,					):
												return normalize(__UpperCamelCase   ,					mean=__UpperCamelCase   ,					std=__UpperCamelCase   ,					data_format=__UpperCamelCase   ,					**__UpperCamelCase   )



					def    lowercase__      (	self					:     List[str]   ,					__UpperCamelCase					:     ImageInput   ,					__UpperCamelCase					:     bool = None   ,					__UpperCamelCase					:     Dict[str, int] = None   ,					__UpperCamelCase					:     float = None   ,					__UpperCamelCase					:     PILImageResampling = 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					:     List[str]   ,					):
												lowerCamelCase_							  =					do_resize if do_resize is not None else self.do_resize
												lowerCamelCase_							  =					crop_pct if crop_pct is not None else self.crop_pct
												lowerCamelCase_							  =					resample if resample is not None else self.resample
												lowerCamelCase_							  =					do_rescale if do_rescale is not None else self.do_rescale
												lowerCamelCase_							  =					rescale_factor if rescale_factor is not None else self.rescale_factor
												lowerCamelCase_							  =					do_normalize if do_normalize is not None else self.do_normalize
												lowerCamelCase_							  =					image_mean if image_mean is not None else self.image_mean
												lowerCamelCase_							  =					image_std if image_std is not None else self.image_std

												lowerCamelCase_							  =					size if size is not None else self.size
												lowerCamelCase_							  =					get_size_dict(__UpperCamelCase   ,					default_to_square=__UpperCamelCase   )

												lowerCamelCase_							  =					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_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None:
																			raise ValueError("""crop_pct must be specified if size < 384."""   )

												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.
												lowerCamelCase_							  =					[to_numpy_array(__UpperCamelCase   ) for image in images]

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

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

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

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

												lowerCamelCase_							  =					{"""pixel_values""": images}
												return BatchFeature(data=__UpperCamelCase   ,					tensor_type=__UpperCamelCase   )





