



'''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   (							_SCREAMING_SNAKE_CASE     :  np.ndarray					,   _SCREAMING_SNAKE_CASE     :  Union[int, Iterable[int]]					,   _SCREAMING_SNAKE_CASE     :  bool					,   _SCREAMING_SNAKE_CASE     :  int	):







					"""simple docstring"""






					def constraint_to_multiple_of(_SCREAMING_SNAKE_CASE     :  List[str]					,   _SCREAMING_SNAKE_CASE     :  str					,   _SCREAMING_SNAKE_CASE     :  Optional[int]=0					,   _SCREAMING_SNAKE_CASE     :  Any=None	):
										__SCREAMING_SNAKE_CASE				:    Dict						    =							round(val / multiple	) * multiple

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

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

										return x

					__SCREAMING_SNAKE_CASE				:    Tuple						    =							(output_size, output_size) if isinstance(__lowerCamelCase					,   __lowerCamelCase	) else output_size

					__SCREAMING_SNAKE_CASE    ,       __SCREAMING_SNAKE_CASE				:    Tuple						    =							get_image_size(__lowerCamelCase	)
					__SCREAMING_SNAKE_CASE    ,       __SCREAMING_SNAKE_CASE				:    str						    =							output_size

					# determine new height and width
					__SCREAMING_SNAKE_CASE				:    Union[str, Any]						    =							output_height / input_height
					__SCREAMING_SNAKE_CASE				:    List[str]						    =							output_width / input_width

					if keep_aspect_ratio:
										# scale as little as possible
										if abs(1 - scale_width	) < abs(1 - scale_height	):
															# fit width
															__SCREAMING_SNAKE_CASE				:    Union[str, Any]						    =							scale_width
										else:
															# fit height
															__SCREAMING_SNAKE_CASE				:    Tuple						    =							scale_height

					__SCREAMING_SNAKE_CASE				:    Dict						    =							constraint_to_multiple_of(scale_height * input_height					,   multiple=__lowerCamelCase	)
					__SCREAMING_SNAKE_CASE				:    Any						    =							constraint_to_multiple_of(scale_width * input_width					,   multiple=__lowerCamelCase	)

					return (new_height, new_width)






class    __lowerCamelCase							( _SCREAMING_SNAKE_CASE   ):







	'''simple docstring'''
	snake_case__		:   List[str]       =				['''pixel_values''']






	def __init__(      self      ,     a__ = True      ,     a__ = None      ,     a__ = PILImageResampling.BILINEAR      ,     a__ = False      ,     a__ = 1      ,     a__ = True      ,     a__ = 1 / 255      ,     a__ = True      ,     a__ = None      ,     a__ = None      ,     **a__      ,     ):
						super().__init__(**_lowercase					)
						__SCREAMING_SNAKE_CASE				:    Tuple						    =							size if size is not None else {"height": 384, "width": 384}
						__SCREAMING_SNAKE_CASE				:    Optional[int]						    =							get_size_dict(_lowercase					)
						__SCREAMING_SNAKE_CASE				:    Any						    =							do_resize
						__SCREAMING_SNAKE_CASE				:    Any						    =							size
						__SCREAMING_SNAKE_CASE				:    List[str]						    =							keep_aspect_ratio
						__SCREAMING_SNAKE_CASE				:    int						    =							ensure_multiple_of
						__SCREAMING_SNAKE_CASE				:    List[str]						    =							resample
						__SCREAMING_SNAKE_CASE				:    Tuple						    =							do_rescale
						__SCREAMING_SNAKE_CASE				:    List[Any]						    =							rescale_factor
						__SCREAMING_SNAKE_CASE				:    Optional[int]						    =							do_normalize
						__SCREAMING_SNAKE_CASE				:    Any						    =							image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
						__SCREAMING_SNAKE_CASE				:    int						    =							image_std if image_std is not None else IMAGENET_STANDARD_STD






	def  a_					(      self      ,     a__      ,     a__      ,     a__ = False      ,     a__ = 1      ,     a__ = PILImageResampling.BICUBIC      ,     a__ = None      ,     **a__      ,     ):
						__SCREAMING_SNAKE_CASE				:    List[Any]						    =							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()}'					)
						__SCREAMING_SNAKE_CASE				:    Any						    =							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  a_					(      self      ,     a__      ,     a__      ,     a__ = None      ,     **a__      ,     ):
						return rescale(_lowercase      ,     scale=_lowercase      ,     data_format=_lowercase      ,     **_lowercase					)






	def  a_					(      self      ,     a__      ,     a__      ,     a__      ,     a__ = None      ,     **a__      ,     ):
						return normalize(_lowercase      ,     mean=_lowercase      ,     std=_lowercase      ,     data_format=_lowercase      ,     **_lowercase					)






	def  a_					(      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__      ,     ):
						__SCREAMING_SNAKE_CASE				:    Any						    =							do_resize if do_resize is not None else self.do_resize
						__SCREAMING_SNAKE_CASE				:    Tuple						    =							size if size is not None else self.size
						__SCREAMING_SNAKE_CASE				:    Union[str, Any]						    =							get_size_dict(_lowercase					)
						__SCREAMING_SNAKE_CASE				:    int						    =							keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
						__SCREAMING_SNAKE_CASE				:    Union[str, Any]						    =							ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
						__SCREAMING_SNAKE_CASE				:    Optional[Any]						    =							resample if resample is not None else self.resample
						__SCREAMING_SNAKE_CASE				:    List[str]						    =							do_rescale if do_rescale is not None else self.do_rescale
						__SCREAMING_SNAKE_CASE				:    int						    =							rescale_factor if rescale_factor is not None else self.rescale_factor
						__SCREAMING_SNAKE_CASE				:    Union[str, Any]						    =							do_normalize if do_normalize is not None else self.do_normalize
						__SCREAMING_SNAKE_CASE				:    List[Any]						    =							image_mean if image_mean is not None else self.image_mean
						__SCREAMING_SNAKE_CASE				:    List[str]						    =							image_std if image_std is not None else self.image_std

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

						if do_resize:
											__SCREAMING_SNAKE_CASE				:    Union[str, Any]						    =							[self.resize(image=_lowercase      ,     size=_lowercase      ,     resample=_lowercase					) for image in images]

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

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

						__SCREAMING_SNAKE_CASE				:    str						    =							[to_channel_dimension_format(_lowercase      ,     _lowercase					) for image in images]

						__SCREAMING_SNAKE_CASE				:    List[Any]						    =							{"pixel_values": images}
						return BatchFeature(data=_lowercase      ,     tensor_type=_lowercase					)






	def  a_					(      self      ,     a__      ,     a__ = None					):
						__SCREAMING_SNAKE_CASE				:    Union[str, Any]						    =							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					):
																__SCREAMING_SNAKE_CASE				:    Tuple						    =							target_sizes.numpy()

											__SCREAMING_SNAKE_CASE				:    Optional[Any]						    =							[]

											for idx in range(len(_lowercase					)					):
																__SCREAMING_SNAKE_CASE				:    Optional[int]						    =							torch.nn.functional.interpolate(
																    logits[idx].unsqueeze(dim=0					)      ,     size=target_sizes[idx]      ,     mode="bilinear"      ,     align_corners=_lowercase					)
																__SCREAMING_SNAKE_CASE				:    List[Any]						    =							resized_logits[0].argmax(dim=0					)
																semantic_segmentation.append(_lowercase					)
						else:
											__SCREAMING_SNAKE_CASE				:    List[Any]						    =							logits.argmax(dim=1					)
											__SCREAMING_SNAKE_CASE				:    Tuple						    =							[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
