
'''simple docstring'''



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          =						logging.get_logger(__name__)


def A (__lowerCamelCase :np.ndarray					,      __lowerCamelCase :Union[int, Iterable[int]]					,      __lowerCamelCase :bool					,      __lowerCamelCase :int						):
						def constraint_to_multiple_of(__lowerCamelCase :List[str]					,      __lowerCamelCase :str					,      __lowerCamelCase :Optional[int]=0					,      __lowerCamelCase :Any=None						):
												_lowerCAmelCase    		=					round(val / multiple						) * multiple

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

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

												return x

						_lowerCAmelCase    		=					(output_size, output_size) if isinstance(__lowerCamelCase					,      __lowerCamelCase						) else output_size

						_lowerCAmelCase		,       _lowerCAmelCase    		=					get_image_size(__lowerCamelCase						)
						_lowerCAmelCase		,       _lowerCAmelCase    		=					output_size

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

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

						_lowerCAmelCase    		=					constraint_to_multiple_of(scale_height * input_height					,      multiple=__lowerCamelCase						)
						_lowerCAmelCase    		=					constraint_to_multiple_of(scale_width * input_width					,      multiple=__lowerCamelCase						)

						return (new_height, new_width)





class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						_lowercase						: List[str]										=  ['''pixel_values''']




						def __init__(   self       ,  _lowercase = True       ,  _lowercase = None       ,  _lowercase = PILImageResampling.BILINEAR       ,  _lowercase = False       ,  _lowercase = 1       ,  _lowercase = True       ,  _lowercase = 1 / 255       ,  _lowercase = True       ,  _lowercase = None       ,  _lowercase = None       ,  **_lowercase       ,  ):

												"""simple docstring"""



												super().__init__(**_lowercase )
												_lowerCAmelCase    		=					size if size is not None else {"""height""": 384, """width""": 384}
												_lowerCAmelCase    		=					get_size_dict(_lowercase )
												_lowerCAmelCase    		=					do_resize
												_lowerCAmelCase    		=					size
												_lowerCAmelCase    		=					keep_aspect_ratio
												_lowerCAmelCase    		=					ensure_multiple_of
												_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       ,  _lowercase       ,  _lowercase       ,  _lowercase = False       ,  _lowercase = 1       ,  _lowercase = PILImageResampling.BICUBIC       ,  _lowercase = None       ,  **_lowercase       ,  ):

												"""simple docstring"""



												_lowerCAmelCase    		=					get_size_dict(_lowercase )
												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()}' )
												_lowerCAmelCase    		=					get_resize_output_image_size(
												    _lowercase       ,  output_size=(size["""height"""], size["""width"""])       ,  keep_aspect_ratio=_lowercase       ,  multiple=_lowercase       ,  )
												return resize(_lowercase       ,  size=_lowercase       ,  resample=_lowercase       ,  data_format=_lowercase       ,  **_lowercase )




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase       ,  _lowercase = None       ,  **_lowercase       ,  ):

												"""simple docstring"""



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




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase       ,  _lowercase       ,  _lowercase = None       ,  **_lowercase       ,  ):

												"""simple docstring"""



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




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase = None       ,  _lowercase = None       ,  _lowercase = None       ,  _lowercase = None       ,  _lowercase = None       ,  _lowercase = None       ,  _lowercase = None       ,  _lowercase = None       ,  _lowercase = None       ,  _lowercase = None       ,  _lowercase = None       ,  _lowercase = ChannelDimension.FIRST       ,  **_lowercase       ,  ):

												"""simple docstring"""



												_lowerCAmelCase    		=					do_resize if do_resize is not None else self.do_resize
												_lowerCAmelCase    		=					size if size is not None else self.size
												_lowerCAmelCase    		=					get_size_dict(_lowercase )
												_lowerCAmelCase    		=					keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
												_lowerCAmelCase    		=					ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
												_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    		=					make_list_of_images(_lowercase )

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

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

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

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

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

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




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase = None ):

												"""simple docstring"""



												_lowerCAmelCase    		=					outputs.logits

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

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

																		_lowerCAmelCase    		=					[]

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

												return semantic_segmentation


'''simple docstring'''



from typing import List, Optional, Union

import numpy as np

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     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						_lowercase						: List[str]										=  ['''input_values''', '''padding_mask''']




						def __init__(   self       ,  _lowercase = 1       ,  _lowercase = 24_000       ,  _lowercase = 0.0       ,  _lowercase = None       ,  _lowercase = None       ,  **_lowercase       ,  ):

												"""simple docstring"""



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




						@property
						def    _lowercase      (   self ):

												"""simple docstring"""



												if self.chunk_length_s is None:
																		return None
												else:
																		return int(self.chunk_length_s * self.sampling_rate )




						@property
						def    _lowercase      (   self ):

												"""simple docstring"""



												if self.chunk_length_s is None or self.overlap is None:
																		return None
												else:
																		return max(1       ,  int((1.0 - self.overlap) * self.chunk_length ) )




						def __call__(   self       ,  _lowercase       ,  _lowercase = None       ,  _lowercase = False       ,  _lowercase = None       ,  _lowercase = None       ,  _lowercase = None       ,  ):

												"""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 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 padding and truncation:
																		raise ValueError("""Both padding and truncation were set. Make sure you only set one.""" )
												elif padding is None:
																		# by default let's pad the inputs
																		_lowerCAmelCase    		=					True

												_lowerCAmelCase    		=					bool(
												    isinstance(_lowercase       ,  (list, tuple) ) and (isinstance(raw_audio[0]       ,  (np.ndarray, tuple, list) )) )

												if is_batched:
																		_lowerCAmelCase    		=					[np.asarray(_lowercase       ,  dtype=np.floataa ).T for audio in raw_audio]
												elif not is_batched and not isinstance(_lowercase       ,  np.ndarray ):
																		_lowerCAmelCase    		=					np.asarray(_lowercase       ,  dtype=np.floataa )
												elif isinstance(_lowercase       ,  np.ndarray ) and raw_audio.dtype is np.dtype(np.floataa ):
																		_lowerCAmelCase    		=					raw_audio.astype(np.floataa )

												# always return batch
												if not is_batched:
																		_lowerCAmelCase    		=					[np.asarray(_lowercase ).T]

												# verify inputs are valid
												for idx, example in enumerate(_lowercase ):
																		if example.ndim > 2:
																								raise ValueError(F'Expected input shape (channels, length) but got shape {example.shape}' )
																		if self.feature_size == 1 and example.ndim != 1:
																								raise ValueError(F'Expected mono audio but example has {example.shape[-1]} channels' )
																		if self.feature_size == 2 and example.shape[-1] != 2:
																								raise ValueError(F'Expected stereo audio but example has {example.shape[-1]} channels' )

												_lowerCAmelCase    		=					None
												_lowerCAmelCase    		=					BatchFeature({"""input_values""": raw_audio} )
												if self.chunk_stride is not None and self.chunk_length is not None and max_length is None:
																		if truncation:
																								_lowerCAmelCase    		=					min(array.shape[0] for array in raw_audio )
																								_lowerCAmelCase    		=					int(np.floor(max_length / self.chunk_stride ) )
																								_lowerCAmelCase    		=					(nb_step - 1) * self.chunk_stride + self.chunk_length
																		elif padding:
																								_lowerCAmelCase    		=					max(array.shape[0] for array in raw_audio )
																								_lowerCAmelCase    		=					int(np.ceil(max_length / self.chunk_stride ) )
																								_lowerCAmelCase    		=					(nb_step - 1) * self.chunk_stride + self.chunk_length
																								_lowerCAmelCase    		=					"""max_length"""
																		else:
																								_lowerCAmelCase    		=					input_values

        # normal padding on batch
												if padded_inputs is None:
																		_lowerCAmelCase    		=					self.pad(
																		    _lowercase       ,  max_length=_lowercase       ,  truncation=_lowercase       ,  padding=_lowercase       ,  return_attention_mask=_lowercase       ,  )
																		if padding:
																								_lowerCAmelCase    		=					padded_inputs.pop("""attention_mask""" )

												_lowerCAmelCase    		=					[]
												for example in padded_inputs.pop("""input_values""" ):
																		if self.feature_size == 1:
																								_lowerCAmelCase    		=					example[..., None]
																		input_values.append(example.T )

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

												return padded_inputs
