



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


UpperCAmelCase__     = logging.get_logger(__name__)







class     __lowerCAmelCase					(    A		):
			UpperCamelCase           =  ['''input_values''', '''padding_mask''']



			def __init__(		self     :						Any				,	A     :						int = 1				,	A     :						int = 2_40_00				,	A     :						float = 0.0				,	A     :						float = None				,	A     :						float = None				,	**A     :						Dict				,	)     ->					Dict:



						"""simple docstring"""






						super().__init__(feature_size=A				,	sampling_rate=A				,	padding_value=A				,	**A)
						_UpperCAmelCase	 =     chunk_length_s
						_UpperCAmelCase	 =     overlap



			@property
			def 					_lowerCamelCase (		self     :						int)     ->					Optional[int]:



						"""simple docstring"""






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



			@property
			def 					_lowerCamelCase (		self     :						Optional[int])     ->					Optional[int]:



						"""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     :						Tuple				,	A     :						Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]				,	A     :						Optional[Union[bool, str, PaddingStrategy]] = None				,	A     :						Optional[bool] = False				,	A     :						Optional[int] = None				,	A     :						Optional[Union[str, TensorType]] = None				,	A     :						Optional[int] = None				,	)     ->					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 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
									_UpperCAmelCase	 =     True

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

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

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

						# verify inputs are valid
						for idx, example in enumerate(A):
									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")

						_UpperCAmelCase	 =     None
						_UpperCAmelCase	 =     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:
												_UpperCAmelCase	 =     min(array.shape[0] for array in raw_audio)
												_UpperCAmelCase	 =     int(np.floor(max_length / self.chunk_stride))
												_UpperCAmelCase	 =     (nb_step - 1) * self.chunk_stride + self.chunk_length
									elif padding:
												_UpperCAmelCase	 =     max(array.shape[0] for array in raw_audio)
												_UpperCAmelCase	 =     int(np.ceil(max_length / self.chunk_stride))
												_UpperCAmelCase	 =     (nb_step - 1) * self.chunk_stride + self.chunk_length
												_UpperCAmelCase	 =     'max_length'
									else:
												_UpperCAmelCase	 =     input_values

        # normal padding on batch
						if padded_inputs is None:
									_UpperCAmelCase	 =     self.pad(
									    A				,	max_length=A				,	truncation=A				,	padding=A				,	return_attention_mask=A				,	)
									if padding:
												_UpperCAmelCase	 =     padded_inputs.pop('attention_mask')

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

						_UpperCAmelCase	 =     input_values
						if return_tensors is not None:
									_UpperCAmelCase	 =     padded_inputs.convert_to_tensors(A)

						return padded_inputs





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

import numpy as np

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


if is_torch_available():
							import torch


UpperCAmelCase__     = logging.get_logger(__name__)







class     __lowerCAmelCase					(    A		):
			UpperCamelCase           =  ['''pixel_values''']



			def __init__(		self     :						Any				,	A     :						bool = True				,	A     :						Optional[Dict[str, int]] = None				,	A     :						PILImageResampling = PILImageResampling.BILINEAR				,	A     :						bool = True				,	A     :						Dict[str, int] = None				,	A     :						bool = True				,	A     :						Union[int, float] = 1 / 2_55				,	A     :						bool = True				,	A     :						Optional[Union[float, List[float]]] = None				,	A     :						Optional[Union[float, List[float]]] = None				,	**A     :						Union[str, Any]				,	)     ->					None:



						"""simple docstring"""






						super().__init__(**A)
						_UpperCAmelCase	 =     size if size is not None else {'shortest_edge': 2_56}
						_UpperCAmelCase	 =     get_size_dict(A				,	default_to_square=A)
						_UpperCAmelCase	 =     crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24}
						_UpperCAmelCase	 =     get_size_dict(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 IMAGENET_STANDARD_MEAN
						_UpperCAmelCase	 =     image_std if image_std is not None else IMAGENET_STANDARD_STD



			def 					_lowerCamelCase (		self     :						List[str]				,	A     :						np.ndarray				,	A     :						Dict[str, int]				,	A     :						PILImageResampling = PILImageResampling.BICUBIC				,	A     :						Optional[Union[str, ChannelDimension]] = None				,	**A     :						List[str]				,	)     ->					np.ndarray:



						"""simple docstring"""






						_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     :						Any				,	A     :						np.ndarray				,	A     :						Dict[str, int]				,	A     :						Optional[Union[str, ChannelDimension]] = None				,	**A     :						Union[str, Any]				,	)     ->					np.ndarray:



						"""simple docstring"""






						_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` and `width`. Got {size.keys()}")
						return center_crop(A				,	size=(size['height'], size['width'])				,	data_format=A				,	**A)



			def 					_lowerCamelCase (		self     :						Any				,	A     :						np.ndarray				,	A     :						float				,	A     :						Optional[Union[str, ChannelDimension]] = None				,	**A     :						Dict)     ->					np.ndarray:



						"""simple docstring"""






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



			def 					_lowerCamelCase (		self     :						int				,	A     :						np.ndarray				,	A     :						Union[float, List[float]]				,	A     :						Union[float, List[float]]				,	A     :						Optional[Union[str, ChannelDimension]] = None				,	**A     :						Dict				,	)     ->					np.ndarray:



						"""simple docstring"""






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



			def 					_lowerCamelCase (		self     :						Union[str, Any]				,	A     :						ImageInput				,	A     :						Optional[bool] = None				,	A     :						Dict[str, int] = None				,	A     :						PILImageResampling = None				,	A     :						bool = None				,	A     :						Dict[str, int] = None				,	A     :						Optional[bool] = None				,	A     :						Optional[float] = None				,	A     :						Optional[bool] = None				,	A     :						Optional[Union[float, List[float]]] = None				,	A     :						Optional[Union[float, List[float]]] = None				,	A     :						Optional[Union[str, TensorType]] = None				,	A     :						Union[str, ChannelDimension] = ChannelDimension.FIRST				,	**A     :						int				,	)     ->					Dict:



						"""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(A				,	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')
						_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(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.')

						# 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)



			def 					_lowerCamelCase (		self     :						str				,	A     :						Any				,	A     :						List[Tuple] = None)     ->					Tuple:



						"""simple docstring"""






						_UpperCAmelCase	 =     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):
												_UpperCAmelCase	 =     target_sizes.numpy()

									_UpperCAmelCase	 =     []

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

						return semantic_segmentation
