





import math
from typing import Dict, Iterable, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    is_torch_available,
    is_torch_tensor,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_torch_available():
     import torch

if is_vision_available():
     import PIL


__lowercase  :   str						      =logging.get_logger(__name__)




def     a__ (					lowercase__  ,    lowercase__  ,    lowercase__  ,    lowercase__  ):






   '''simple docstring'''






   def constraint_to_multiple_of(lowercase__  ,    lowercase__  ,    lowercase__=0  ,    lowercase__=None  ):
      UpperCAmelCase_											=round(val / multiple  ) * multiple

      if max_val is not None and x > max_val:
         UpperCAmelCase_											=math.floor(val / multiple  ) * multiple

      if x < min_val:
         UpperCAmelCase_											=math.ceil(val / multiple  ) * multiple

      return x

   UpperCAmelCase_											=(output_size, output_size) if isinstance(lowercase__  ,    lowercase__  ) else output_size

   UpperCAmelCase_						,       UpperCAmelCase_											=get_image_size(lowercase__  )
   UpperCAmelCase_						,       UpperCAmelCase_											=output_size

   # determine new height and width
   UpperCAmelCase_											=output_height / input_height
   UpperCAmelCase_											=output_width / input_width

   if keep_aspect_ratio:
      # scale as little as possible
      if abs(1 - scale_width  ) < abs(1 - scale_height  ):
         # fit width
         UpperCAmelCase_											=scale_width
      else:
         # fit height
         UpperCAmelCase_											=scale_height

   UpperCAmelCase_											=constraint_to_multiple_of(scale_height * input_height  ,    multiple=lowercase__  )
   UpperCAmelCase_											=constraint_to_multiple_of(scale_width * input_width  ,    multiple=lowercase__  )

   return (new_height, new_width)





class      A       (	__lowercase						):
      _snake_case							     =['''pixel_values''']



      def __init__(	self:						Tuple		,  _lowerCAmelCase:						bool = True		,  _lowerCAmelCase:						Dict[str, int] = None		,  _lowerCAmelCase:						PILImageResampling = PILImageResampling.BILINEAR		,  _lowerCAmelCase:						bool = False		,  _lowerCAmelCase:						int = 1		,  _lowerCAmelCase:						bool = True		,  _lowerCAmelCase:						Union[int, float] = 1 / 255		,  _lowerCAmelCase:						bool = True		,  _lowerCAmelCase:						Optional[Union[float, List[float]]] = None		,  _lowerCAmelCase:						Optional[Union[float, List[float]]] = None		,  **_lowerCAmelCase:						List[Any]		,  )						->    None:
         '''simple docstring'''

         super().__init__(**_lowerCAmelCase       )
         UpperCAmelCase_											=size if size is not None else {"height": 384, "width": 384}
         UpperCAmelCase_											=get_size_dict(_lowerCAmelCase       )
         UpperCAmelCase_											=do_resize
         UpperCAmelCase_											=size
         UpperCAmelCase_											=keep_aspect_ratio
         UpperCAmelCase_											=ensure_multiple_of
         UpperCAmelCase_											=resample
         UpperCAmelCase_											=do_rescale
         UpperCAmelCase_											=rescale_factor
         UpperCAmelCase_											=do_normalize
         UpperCAmelCase_											=image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
         UpperCAmelCase_											=image_std if image_std is not None else IMAGENET_STANDARD_STD



      def 	lowerCAmelCase__    (	self:						str		,  _lowerCAmelCase:						np.ndarray		,  _lowerCAmelCase:						Dict[str, int]		,  _lowerCAmelCase:						bool = False		,  _lowerCAmelCase:						int = 1		,  _lowerCAmelCase:						PILImageResampling = PILImageResampling.BICUBIC		,  _lowerCAmelCase:						Optional[Union[str, ChannelDimension]] = None		,  **_lowerCAmelCase:						Optional[Any]		,  )						->    np.ndarray:
         '''simple docstring'''

         UpperCAmelCase_											=get_size_dict(_lowerCAmelCase       )
         if "height" not in size or "width" not in size:
            raise ValueError(F'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}'       )
         UpperCAmelCase_											=get_resize_output_image_size(
             _lowerCAmelCase		,  output_size=(size["height"], size["width"])		,  keep_aspect_ratio=_lowerCAmelCase		,  multiple=_lowerCAmelCase		,  )
         return resize(_lowerCAmelCase		,  size=_lowerCAmelCase		,  resample=_lowerCAmelCase		,  data_format=_lowerCAmelCase		,  **_lowerCAmelCase       )



      def 	lowerCAmelCase__    (	self:						Any		,  _lowerCAmelCase:						np.ndarray		,  _lowerCAmelCase:						Union[int, float]		,  _lowerCAmelCase:						Optional[Union[str, ChannelDimension]] = None		,  **_lowerCAmelCase:						List[Any]		,  )						->    int:
         '''simple docstring'''

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



      def 	lowerCAmelCase__    (	self:						List[str]		,  _lowerCAmelCase:						np.ndarray		,  _lowerCAmelCase:						Union[float, List[float]]		,  _lowerCAmelCase:						Union[float, List[float]]		,  _lowerCAmelCase:						Optional[Union[str, ChannelDimension]] = None		,  **_lowerCAmelCase:						Union[str, Any]		,  )						->    np.ndarray:
         '''simple docstring'''

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



      def 	lowerCAmelCase__    (	self:						Optional[Any]		,  _lowerCAmelCase:						ImageInput		,  _lowerCAmelCase:						bool = None		,  _lowerCAmelCase:						int = None		,  _lowerCAmelCase:						bool = None		,  _lowerCAmelCase:						int = None		,  _lowerCAmelCase:						PILImageResampling = None		,  _lowerCAmelCase:						bool = None		,  _lowerCAmelCase:						float = None		,  _lowerCAmelCase:						bool = None		,  _lowerCAmelCase:						Optional[Union[float, List[float]]] = None		,  _lowerCAmelCase:						Optional[Union[float, List[float]]] = None		,  _lowerCAmelCase:						Optional[Union[str, TensorType]] = None		,  _lowerCAmelCase:						ChannelDimension = ChannelDimension.FIRST		,  **_lowerCAmelCase:						str		,  )						->    PIL.Image.Image:
         '''simple docstring'''

         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(_lowerCAmelCase       )
         UpperCAmelCase_											=keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
         UpperCAmelCase_											=ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
         UpperCAmelCase_											=resample if resample is not None else self.resample
         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_											=make_list_of_images(_lowerCAmelCase       )

         if not valid_images(_lowerCAmelCase       ):
            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_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_											=[to_numpy_array(_lowerCAmelCase       ) for image in images]

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

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

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

         UpperCAmelCase_											=[to_channel_dimension_format(_lowerCAmelCase		,  _lowerCAmelCase       ) for image in images]

         UpperCAmelCase_											={"pixel_values": images}
         return BatchFeature(data=_lowerCAmelCase		,  tensor_type=_lowerCAmelCase       )






      def 	lowerCAmelCase__    (	self:						Any		,  _lowerCAmelCase:						str		,  _lowerCAmelCase:						List[Tuple] = None       )						->    str:
         '''simple docstring'''

         UpperCAmelCase_											=outputs.logits

         # Resize logits and compute semantic segmentation maps
         if target_sizes is not None:
            if len(_lowerCAmelCase       ) != len(_lowerCAmelCase       ):
               raise ValueError(
                   "Make sure that you pass in as many target sizes as the batch dimension of the logits"       )

            if is_torch_tensor(_lowerCAmelCase       ):
               UpperCAmelCase_											=target_sizes.numpy()

            UpperCAmelCase_											=[]

            for idx in range(len(_lowerCAmelCase       )       ):
               UpperCAmelCase_											=torch.nn.functional.interpolate(
                   logits[idx].unsqueeze(dim=0       )		,  size=target_sizes[idx]		,  mode="bilinear"		,  align_corners=_lowerCAmelCase       )
               UpperCAmelCase_											=resized_logits[0].argmax(dim=0       )
               semantic_segmentation.append(_lowerCAmelCase       )
         else:
            UpperCAmelCase_											=logits.argmax(dim=1       )
            UpperCAmelCase_											=[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]       )]

         return semantic_segmentation











from typing import 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 ....file_utils import PaddingStrategy, TensorType
from ....utils import logging


__lowercase  :   Union[str, Any]						      =logging.get_logger(__name__)

class      A       (	__lowercase						):
      _snake_case							     =['''input_features''', '''attention_mask''']



      def __init__(	self:						Dict		,  _lowerCAmelCase:						List[str]=80		,  _lowerCAmelCase:						Optional[Any]=1_6000		,  _lowerCAmelCase:						Any=0.0		,  _lowerCAmelCase:						Optional[Any]=10		,  _lowerCAmelCase:						Optional[Any]=25		,  _lowerCAmelCase:						Union[str, Any]="hamming_window"		,  _lowerCAmelCase:						Optional[int]=3_27_68.0		,  _lowerCAmelCase:						Optional[Any]=0.97		,  _lowerCAmelCase:						Any=1.0		,  _lowerCAmelCase:						List[str]=True		,  _lowerCAmelCase:						Dict=True		,  _lowerCAmelCase:						Any=False		,  **_lowerCAmelCase:						Any		,  )						->    Dict:
         '''simple docstring'''

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

         UpperCAmelCase_											=feature_size
         UpperCAmelCase_											=sampling_rate
         UpperCAmelCase_											=padding_value
         UpperCAmelCase_											=hop_length
         UpperCAmelCase_											=win_length
         UpperCAmelCase_											=frame_signal_scale
         UpperCAmelCase_											=preemphasis_coeff
         UpperCAmelCase_											=mel_floor
         UpperCAmelCase_											=normalize_means
         UpperCAmelCase_											=normalize_vars
         UpperCAmelCase_											=win_function
         UpperCAmelCase_											=return_attention_mask

         UpperCAmelCase_											=win_length * sampling_rate // 1000
         UpperCAmelCase_											=hop_length * sampling_rate // 1000

         UpperCAmelCase_											=optimal_fft_length(self.sample_size       )
         UpperCAmelCase_											=(self.n_fft // 2) + 1



      def 	lowerCAmelCase__    (	self:						Optional[Any]		,  _lowerCAmelCase:						np.array       )						->    np.ndarray:
         '''simple docstring'''

         if self.win_function == "hamming_window":
            UpperCAmelCase_											=window_function(window_length=self.sample_size		,  name=self.win_function		,  periodic=_lowerCAmelCase       )
         else:
            UpperCAmelCase_											=window_function(window_length=self.sample_size		,  name=self.win_function       )

         UpperCAmelCase_											=mel_filter_bank(
             num_frequency_bins=self.n_freqs		,  num_mel_filters=self.feature_size		,  min_frequency=0.0		,  max_frequency=self.sampling_rate / 2.0		,  sampling_rate=self.sampling_rate		,  )

         UpperCAmelCase_											=spectrogram(
             one_waveform * self.frame_signal_scale		,  window=_lowerCAmelCase		,  frame_length=self.sample_size		,  hop_length=self.sample_stride		,  fft_length=self.n_fft		,  center=_lowerCAmelCase		,  preemphasis=self.preemphasis_coeff		,  mel_filters=_lowerCAmelCase		,  mel_floor=self.mel_floor		,  log_mel="log"		,  )
         return msfc_features.T



      def 	lowerCAmelCase__    (	self:						Dict		,  _lowerCAmelCase:						List[Any]		,  _lowerCAmelCase:						Dict		,  _lowerCAmelCase:						Any       )						->    Any:
         '''simple docstring'''

         if self.normalize_means:
            UpperCAmelCase_											=x[:input_length].mean(axis=0       )
            UpperCAmelCase_											=np.subtract(_lowerCAmelCase		,  _lowerCAmelCase       )
         if self.normalize_vars:
            UpperCAmelCase_											=x[:input_length].std(axis=0       )
            UpperCAmelCase_											=np.divide(_lowerCAmelCase		,  _lowerCAmelCase       )

         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:						List[str]		,  _lowerCAmelCase:						List[np.ndarray]		,  _lowerCAmelCase:						Optional[np.ndarray] = None       )						->    List[np.ndarray]:
         '''simple docstring'''

         UpperCAmelCase_											=attention_mask.sum(-1       ) if attention_mask is not None else [x.shape[0] for x in input_features]
         return [self._normalize_one(_lowerCAmelCase		,  _lowerCAmelCase		,  self.padding_value       ) for x, n in zip(_lowerCAmelCase		,  _lowerCAmelCase       )]






      def __call__(	self:						int		,  _lowerCAmelCase:						Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]		,  _lowerCAmelCase:						Union[bool, str, PaddingStrategy] = False		,  _lowerCAmelCase:						Optional[int] = None		,  _lowerCAmelCase:						bool = False		,  _lowerCAmelCase:						Optional[int] = None		,  _lowerCAmelCase:						Optional[bool] = None		,  _lowerCAmelCase:						Optional[Union[str, TensorType]] = None		,  _lowerCAmelCase:						Optional[int] = None		,  **_lowerCAmelCase:						List[Any]		,  )						->    BatchFeature:
         '''simple docstring'''

         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(_lowerCAmelCase		,  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(_lowerCAmelCase		,  (list, tuple)       ) and (isinstance(raw_speech[0]		,  (np.ndarray, tuple, list)       ))
         )

         if is_batched:
            UpperCAmelCase_											=[np.asarray(_lowerCAmelCase		,  dtype=np.floataa       ) for speech in raw_speech]
         elif not is_batched and not isinstance(_lowerCAmelCase		,  np.ndarray       ):
            UpperCAmelCase_											=np.asarray(_lowerCAmelCase		,  dtype=np.floataa       )
         elif isinstance(_lowerCAmelCase		,  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_mfsc_features(_lowerCAmelCase       ) for one_waveform in raw_speech]

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

         UpperCAmelCase_											=self.pad(
             _lowerCAmelCase		,  padding=_lowerCAmelCase		,  max_length=_lowerCAmelCase		,  truncation=_lowerCAmelCase		,  pad_to_multiple_of=_lowerCAmelCase		,  return_attention_mask=_lowerCAmelCase		,  **_lowerCAmelCase		,  )
         # make sure list is in array format
         UpperCAmelCase_											=padded_inputs.get("input_features"       )
         if isinstance(input_features[0]		,  _lowerCAmelCase       ):
            UpperCAmelCase_											=[np.asarray(_lowerCAmelCase		,  dtype=np.floataa       ) for feature in input_features]

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

         if self.normalize_means or self.normalize_vars:
            UpperCAmelCase_											=(
                np.array(_lowerCAmelCase		,  dtype=np.intaa       )
                if self._get_padding_strategies(_lowerCAmelCase		,  max_length=_lowerCAmelCase       ) is not PaddingStrategy.DO_NOT_PAD
                and padding
                else None
            )
            UpperCAmelCase_											=self.normalize(
                padded_inputs["input_features"]		,  attention_mask=_lowerCAmelCase       )

         if return_tensors is not None:
            UpperCAmelCase_											=padded_inputs.convert_to_tensors(_lowerCAmelCase       )

         return padded_inputs




