






import copy
from typing import Any, Dict, List, Optional, Union

import numpy as np
import torch

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


__lowerCamelCase	:		Dict										=   logging.get_logger(__name__)







class  _lowercase   (   _A						):
      _a							:						List[str]										=							['input_features', 'is_longer']
      def __init__(     self				,			a=6_4				,			a=4_8_0_0_0				,			a=4_8_0				,			a=1_0				,			a=1_0_2_4				,			a=0.0				,			a=False				,			a = 0				,			a = 1_4_0_0_0				,			a = None				,			a = "fusion"				,			a = "repeatpad"				,			**a				,			):
       super().__init__(
           feature_size=a				,			sampling_rate=a				,			padding_value=a				,			return_attention_mask=a				,			**a				,			)
       snake_case__  :    List[Any]							       =top_db
       snake_case__  :    List[str]							       =truncation
       snake_case__  :    Union[str, Any]							       =padding
       snake_case__  :    List[str]							       =fft_window_size
       snake_case__  :    Dict							       =(fft_window_size >> 1) + 1
       snake_case__  :    Tuple							       =hop_length
       snake_case__  :    List[Any]							       =max_length_s
       snake_case__  :    Tuple							       =max_length_s * sampling_rate
       snake_case__  :    Optional[Any]							       =sampling_rate
       snake_case__  :    Union[str, Any]							       =frequency_min
       snake_case__  :    List[str]							       =frequency_max
       snake_case__  :    List[Any]							       =mel_filter_bank(
           num_frequency_bins=self.nb_frequency_bins				,			num_mel_filters=a				,			min_frequency=a				,			max_frequency=a				,			sampling_rate=a				,			norm=a				,			mel_scale="""htk"""				,			)
       snake_case__  :    List[str]							       =mel_filter_bank(
           num_frequency_bins=self.nb_frequency_bins				,			num_mel_filters=a				,			min_frequency=a				,			max_frequency=a				,			sampling_rate=a				,			norm="""slaney"""				,			mel_scale="""slaney"""				,			)
      def 						lowercase__					(     self   ):
       snake_case__  :    List[str]							       =copy.deepcopy(self.__dict__   )
       snake_case__  :    Dict							       =self.__class__.__name__
       if "mel_filters" in output:
        del output["mel_filters"]
       if "mel_filters_slaney" in output:
        del output["mel_filters_slaney"]
       return output
      def 						lowercase__					(     self				,			a				,			a = None   ):
       snake_case__  :    Dict							       =spectrogram(
           a				,			window_function(self.fft_window_size				,			"""hann"""   )				,			frame_length=self.fft_window_size				,			hop_length=self.hop_length				,			power=2.0				,			mel_filters=a				,			log_mel="""dB"""				,			)
       return log_mel_spectrogram.T
      def 						lowercase__					(     self				,			a				,			a				,			a   ):
       snake_case__  :    Any							       =np.array_split(list(range(0				,			total_frames - chunk_frames + 1   )   )				,			3   )
       if len(ranges[1]   ) == 0:
        # if the audio is too short, we just use the first chunk
        snake_case__  :    Optional[int]							       =[0]
       if len(ranges[2]   ) == 0:
        # if the audio is too short, we just use the first chunk
        snake_case__  :    Union[str, Any]							       =[0]
       # randomly choose index for each part
       snake_case__  :    str							       =np.random.choice(ranges[0]   )
       snake_case__  :    str							       =np.random.choice(ranges[1]   )
       snake_case__  :    List[str]							       =np.random.choice(ranges[2]   )

       snake_case__  :    List[Any]							       =mel[idx_front : idx_front + chunk_frames, :]
       snake_case__  :    List[Any]							       =mel[idx_middle : idx_middle + chunk_frames, :]
       snake_case__  :    List[Any]							       =mel[idx_back : idx_back + chunk_frames, :]

       snake_case__  :    Any							       =torch.tensor(mel[None, None, :]   )
       snake_case__  :    Any							       =torch.nn.functional.interpolate(
           a				,			size=[chunk_frames, 6_4]				,			mode="""bilinear"""				,			align_corners=a   )
       snake_case__  :    Any							       =mel_shrink[0][0].numpy()
       snake_case__  :    int							       =np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back]				,			axis=0   )
       return mel_fusion
      def 						lowercase__					(     self				,			a				,			a				,			a				,			a   ):
       if waveform.shape[0] > max_length:
        if truncation == "rand_trunc":
         snake_case__  :    Optional[int]							       =True
         # random crop to max_length (for compatibility) -> this should be handled by self.pad
         snake_case__  :    Optional[int]							       =len(a   ) - max_length
         snake_case__  :    int							       =np.random.randint(0				,			overflow + 1   )
         snake_case__  :    Tuple							       =waveform[idx : idx + max_length]
         snake_case__  :    Optional[Any]							       =self._np_extract_fbank_features(a				,			self.mel_filters_slaney   )[None, :]
        elif truncation == "fusion":
         snake_case__  :    Optional[Any]							       =self._np_extract_fbank_features(a				,			self.mel_filters   )
         snake_case__  :    Optional[Any]							       =max_length // self.hop_length + 1  # the +1 related to how the spectrogram is computed
         snake_case__  :    List[str]							       =mel.shape[0]
         if chunk_frames == total_frames:
          # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
          # In this case, we just use the whole audio.
          snake_case__  :    List[str]							       =np.stack([mel, mel, mel, mel]				,			axis=0   )
          snake_case__  :    Dict							       =False
         else:
          snake_case__  :    Tuple							       =self._random_mel_fusion(a				,			a				,			a   )
          snake_case__  :    Any							       =True
        else:
         raise NotImplementedError(F"data_truncating {truncation} not implemented"   )

       else:
        snake_case__  :    Tuple							       =False
        # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
        if waveform.shape[0] < max_length:
         if padding == "repeat":
          snake_case__  :    Tuple							       =int(max_length / len(a   )   )
          snake_case__  :    Union[str, Any]							       =np.stack(np.tile(a				,			n_repeat + 1   )   )[:max_length]
         if padding == "repeatpad":
          snake_case__  :    List[Any]							       =int(max_length / len(a   )   )
          snake_case__  :    List[Any]							       =np.stack(np.tile(a				,			a   )   )
         snake_case__  :    Union[str, Any]							       =np.pad(a				,			(0, max_length - waveform.shape[0])				,			mode="""constant"""				,			constant_values=0   )

        if truncation == "fusion":
         snake_case__  :    Tuple							       =self._np_extract_fbank_features(a				,			self.mel_filters   )
         snake_case__  :    Optional[Any]							       =np.stack([input_mel, input_mel, input_mel, input_mel]				,			axis=0   )
        else:
         snake_case__  :    str							       =self._np_extract_fbank_features(a				,			self.mel_filters_slaney   )[None, :]

       return input_mel, longer



      def __call__(     self				,			a				,			a = None				,			a = None				,			a = None				,			a = None				,			a = None				,			**a				,			):
       snake_case__  :    Optional[int]							       =truncation if truncation is not None else self.truncation
       snake_case__  :    Union[str, Any]							       =padding if padding else self.padding

       if sampling_rate is not None:
        if sampling_rate != self.sampling_rate:
         raise ValueError(
             F"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"
             F" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"
             F" was sampled with {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."""   )

       snake_case__  :    Dict							       =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}"   )
       snake_case__  :    Union[str, Any]							       =is_batched_numpy or (
           isinstance(a				,			(list, tuple)   ) and (isinstance(raw_speech[0]				,			(np.ndarray, tuple, list)   ))
       )

       if is_batched:
        snake_case__  :    str							       =[np.asarray(a				,			dtype=np.floataa   ) for speech in raw_speech]
       elif not is_batched and not isinstance(a				,			np.ndarray   ):
        snake_case__  :    Optional[Any]							       =np.asarray(a				,			dtype=np.floataa   )
       elif isinstance(a				,			np.ndarray   ) and raw_speech.dtype is np.dtype(np.floataa   ):
        snake_case__  :    str							       =raw_speech.astype(np.floataa   )

       # always return batch
       if not is_batched:
        snake_case__  :    Any							       =[np.asarray(a   )]

       # convert to mel spectrogram, truncate and pad if needed.
       snake_case__  :    Tuple							       =[
           self._get_input_mel(a				,			max_length if max_length else self.nb_max_samples				,			a				,			a   )
           for waveform in raw_speech
       ]

       snake_case__  :    Tuple							       =[]
       snake_case__  :    Dict							       =[]
       for mel, longer in padded_inputs:
        input_mel.append(a   )
        is_longer.append(a   )

       if truncation == "fusion" and sum(a   ) == 0:
        # if no audio is longer than 10s, then randomly select one audio to be longer
        snake_case__  :    Optional[int]							       =np.random.randint(0				,			len(a   )   )
        snake_case__  :    Dict							       =True

       if isinstance(input_mel[0]				,			a   ):
        snake_case__  :    int							       =[np.asarray(a				,			dtype=np.floataa   ) for feature in input_mel]

       # is_longer is a list of bool
       snake_case__  :    Any							       =[[longer] for longer in is_longer]

       snake_case__  :    Union[str, Any]							       ={"""input_features""": input_mel, """is_longer""": is_longer}
       snake_case__  :    Any							       =BatchFeature(a   )

       if return_tensors is not None:
        snake_case__  :    Union[str, Any]							       =input_features.convert_to_tensors(a   )

       return input_features













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


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







def 			A__							(      _a  :					np.ndarray		,  _a  :					Union[int, Iterable[int]]		,  _a  :					bool		,  _a  :					int	):





 '''simple docstring'''







 def constraint_to_multiple_of(_a  :					Union[str, Any]		,  _a  :					List[str]		,  _a  :					str=0		,  _a  :					Any=None	):
  snake_case__  :    Any							       =round(val / multiple	) * multiple

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

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

  return x

 snake_case__  :    str							       =(output_size, output_size) if isinstance(_a		,  _a	) else output_size

 snake_case__       ,   snake_case__  :    Dict							       =get_image_size(_a	)
 snake_case__       ,   snake_case__  :    int							       =output_size

 # determine new height and width
 snake_case__  :    Tuple							       =output_height / input_height
 snake_case__  :    Optional[Any]							       =output_width / input_width

 if keep_aspect_ratio:
  # scale as little as possible
  if abs(1 - scale_width	) < abs(1 - scale_height	):
   # fit width
   snake_case__  :    Optional[int]							       =scale_width
  else:
   # fit height
   snake_case__  :    Any							       =scale_height

 snake_case__  :    Optional[int]							       =constraint_to_multiple_of(scale_height * input_height		,  multiple=_a	)
 snake_case__  :    str							       =constraint_to_multiple_of(scale_width * input_width		,  multiple=_a	)

 return (new_height, new_width)







class  _lowercase   (   _A						):
      _a							:						List[Any]										=							['pixel_values']
      def __init__(     self				,			a = True				,			a = None				,			a = PILImageResampling.BILINEAR				,			a = False				,			a = 1				,			a = True				,			a = 1 / 2_5_5				,			a = True				,			a = None				,			a = None				,			**a				,			):
       super().__init__(**a   )
       snake_case__  :    Any							       =size if size is not None else {"""height""": 3_8_4, """width""": 3_8_4}
       snake_case__  :    List[Any]							       =get_size_dict(a   )
       snake_case__  :    Tuple							       =do_resize
       snake_case__  :    Tuple							       =size
       snake_case__  :    Any							       =keep_aspect_ratio
       snake_case__  :    List[Any]							       =ensure_multiple_of
       snake_case__  :    Tuple							       =resample
       snake_case__  :    str							       =do_rescale
       snake_case__  :    int							       =rescale_factor
       snake_case__  :    Tuple							       =do_normalize
       snake_case__  :    int							       =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       snake_case__  :    Any							       =image_std if image_std is not None else IMAGENET_STANDARD_STD
      def 						lowercase__					(     self				,			a				,			a				,			a = False				,			a = 1				,			a = PILImageResampling.BICUBIC				,			a = None				,			**a				,			):
       snake_case__  :    Tuple							       =get_size_dict(a   )
       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()}"   )
       snake_case__  :    Optional[int]							       =get_resize_output_image_size(
           a				,			output_size=(size["""height"""], size["""width"""])				,			keep_aspect_ratio=a				,			multiple=a				,			)
       return resize(a				,			size=a				,			resample=a				,			data_format=a				,			**a   )
      def 						lowercase__					(     self				,			a				,			a				,			a = None				,			**a				,			):
       return rescale(a				,			scale=a				,			data_format=a				,			**a   )
      def 						lowercase__					(     self				,			a				,			a				,			a				,			a = None				,			**a				,			):
       return normalize(a				,			mean=a				,			std=a				,			data_format=a				,			**a   )
      def 						lowercase__					(     self				,			a				,			a = None				,			a = None				,			a = None				,			a = None				,			a = None				,			a = None				,			a = None				,			a = None				,			a = None				,			a = None				,			a = None				,			a = ChannelDimension.FIRST				,			**a				,			):
       snake_case__  :    Optional[int]							       =do_resize if do_resize is not None else self.do_resize
       snake_case__  :    List[Any]							       =size if size is not None else self.size
       snake_case__  :    int							       =get_size_dict(a   )
       snake_case__  :    Optional[int]							       =keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
       snake_case__  :    int							       =ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
       snake_case__  :    Optional[Any]							       =resample if resample is not None else self.resample
       snake_case__  :    Optional[int]							       =do_rescale if do_rescale is not None else self.do_rescale
       snake_case__  :    str							       =rescale_factor if rescale_factor is not None else self.rescale_factor
       snake_case__  :    Optional[Any]							       =do_normalize if do_normalize is not None else self.do_normalize
       snake_case__  :    Tuple							       =image_mean if image_mean is not None else self.image_mean
       snake_case__  :    int							       =image_std if image_std is not None else self.image_std

       snake_case__  :    int							       =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 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.
       snake_case__  :    int							       =[to_numpy_array(a   ) for image in images]

       if do_resize:
        snake_case__  :    List[str]							       =[self.resize(image=a				,			size=a				,			resample=a   ) for image in images]

       if do_rescale:
        snake_case__  :    List[Any]							       =[self.rescale(image=a				,			scale=a   ) for image in images]

       if do_normalize:
        snake_case__  :    str							       =[self.normalize(image=a				,			mean=a				,			std=a   ) for image in images]

       snake_case__  :    List[Any]							       =[to_channel_dimension_format(a				,			a   ) for image in images]

       snake_case__  :    Union[str, Any]							       ={"""pixel_values""": images}
       return BatchFeature(data=a				,			tensor_type=a   )



      def 						lowercase__					(     self				,			a				,			a = None   ):
       snake_case__  :    Optional[Any]							       =outputs.logits

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

        if is_torch_tensor(a   ):
         snake_case__  :    Optional[Any]							       =target_sizes.numpy()

        snake_case__  :    Optional[Any]							       =[]

        for idx in range(len(a   )   ):
         snake_case__  :    List[str]							       =torch.nn.functional.interpolate(
             logits[idx].unsqueeze(dim=0   )				,			size=target_sizes[idx]				,			mode="""bilinear"""				,			align_corners=a   )
         snake_case__  :    List[Any]							       =resized_logits[0].argmax(dim=0   )
         semantic_segmentation.append(a   )
       else:
        snake_case__  :    List[str]							       =logits.argmax(dim=1   )
        snake_case__  :    Optional[int]							       =[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]   )]

       return semantic_segmentation





