





'''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,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


a__							:							Optional[Any] =logging.get_logger(__name__)


if is_vision_available():
    import PIL

class      snake_case     (    __lowerCamelCase       ):




 """simple docstring"""



 SCREAMING_SNAKE_CASE_	:					Dict					=["pixel_values"]






 def __init__(       self       :							List[Any]							,	__A       :							bool = True							,	__A       :							Dict[str, int] = None							,	__A       :							PILImageResampling = PILImageResampling.BICUBIC							,	__A       :							bool = True							,	__A       :							Dict[str, int] = None							,	__A       :							bool = True							,	__A       :							Union[int, float] = 1 / 2_5_5							,	__A       :							bool = True							,	__A       :							Optional[Union[float, List[float]]] = None							,	__A       :							Optional[Union[float, List[float]]] = None							,	__A       :							bool = True							,	**__A       :							str							,	):
        super().__init__(**__A	)
        __UpperCamelCase       =  size if size is not None else {'shortest_edge': 2_2_4}
        __UpperCamelCase       =  get_size_dict(__A							,	default_to_square=__A	)
        __UpperCamelCase       =  crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4}
        __UpperCamelCase       =  get_size_dict(__A							,	default_to_square=__A							,	param_name='crop_size'	)

        __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 if image_mean is not None else OPENAI_CLIP_MEAN
        __UpperCamelCase       =  image_std if image_std is not None else OPENAI_CLIP_STD
        __UpperCamelCase       =  do_convert_rgb






 def        _lowerCamelCase					(       self       :							Optional[Any]							,	__A       :							np.ndarray							,	__A       :							Dict[str, int]							,	__A       :							PILImageResampling = PILImageResampling.BICUBIC							,	__A       :							Optional[Union[str, ChannelDimension]] = None							,	**__A       :							List[str]							,	):
        __UpperCamelCase       =  get_size_dict(__A							,	default_to_square=__A	)
        if "shortest_edge" not in size:
               raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'''	)
        __UpperCamelCase       =  get_resize_output_image_size(__A							,	size=size['shortest_edge']							,	default_to_square=__A	)
        return resize(__A							,	size=__A							,	resample=__A							,	data_format=__A							,	**__A	)






 def        _lowerCamelCase					(       self       :							str							,	__A       :							np.ndarray							,	__A       :							Dict[str, int]							,	__A       :							Optional[Union[str, ChannelDimension]] = None							,	**__A       :							Optional[int]							,	):
        __UpperCamelCase       =  get_size_dict(__A	)
        if "height" not in size or "width" not in size:
               raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}'''	)
        return center_crop(__A							,	size=(size['height'], size['width'])							,	data_format=__A							,	**__A	)






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






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






 def        _lowerCamelCase					(       self       :							Union[str, Any]							,	__A       :							ImageInput							,	__A       :							bool = None							,	__A       :							Dict[str, int] = None							,	__A       :							PILImageResampling = None							,	__A       :							bool = None							,	__A       :							int = None							,	__A       :							bool = None							,	__A       :							float = None							,	__A       :							bool = None							,	__A       :							Optional[Union[float, List[float]]] = None							,	__A       :							Optional[Union[float, List[float]]] = None							,	__A       :							bool = None							,	__A       :							Optional[Union[str, TensorType]] = None							,	__A       :							Optional[ChannelDimension] = ChannelDimension.FIRST							,	**__A       :							Dict							,	):
        __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(__A							,	param_name='size'							,	default_to_square=__A	)
        __UpperCamelCase       =  resample if resample is not None else self.resample
        __UpperCamelCase       =  do_center_crop if do_center_crop is not None else self.do_center_crop
        __UpperCamelCase       =  crop_size if crop_size is not None else self.crop_size
        __UpperCamelCase       =  get_size_dict(__A							,	param_name='crop_size'							,	default_to_square=__A	)
        __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       =  do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

        __UpperCamelCase       =  make_list_of_images(__A	)

        if not valid_images(__A	):
               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:
               raise ValueError('Size 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.'	)

        # PIL RGBA images are converted to RGB
        if do_convert_rgb:
               __UpperCamelCase       =  [convert_to_rgb(__A	) for image in images]

        # All transformations expect numpy arrays.
        __UpperCamelCase       =  [to_numpy_array(__A	) for image in images]

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

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

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

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

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

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







'''simple docstring'''
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


a__							:							str =logging.get_logger(__name__)

class      snake_case     (    __lowerCamelCase       ):




 """simple docstring"""



 SCREAMING_SNAKE_CASE_	:					str					=["input_features", "attention_mask"]






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






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






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

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

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

        return x






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






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

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

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

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

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

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

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

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

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

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

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

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

        return padded_inputs
