


"""simple docstring"""


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


_snake_case        =				logging.get_logger(__name__)



class 	_a   (   _lowercase			):
    a_     :					List[str]   							=     ['''pixel_values''']
    def __init__(			self				:       Dict				,       SCREAMING_SNAKE_CASE__				:       bool = True				,       SCREAMING_SNAKE_CASE__				:       Optional[Dict[str, int]] = None				,       SCREAMING_SNAKE_CASE__				:       PILImageResampling = PILImageResampling.BILINEAR				,       SCREAMING_SNAKE_CASE__				:       bool = True				,       SCREAMING_SNAKE_CASE__				:       Dict[str, int] = None				,       SCREAMING_SNAKE_CASE__				:       bool = True				,       SCREAMING_SNAKE_CASE__				:       Union[int, float] = 1 / 2_55				,       SCREAMING_SNAKE_CASE__				:       bool = True				,       SCREAMING_SNAKE_CASE__				:       Optional[Union[float, List[float]]] = None				,       SCREAMING_SNAKE_CASE__				:       Optional[Union[float, List[float]]] = None				,       **SCREAMING_SNAKE_CASE__				:       int				,       ):
          super().__init__(**__A					)
          lowerCamelCase__							     =		size if size is not None else {"""shortest_edge""": 2_56}
          lowerCamelCase__							     =		get_size_dict(__A				,       default_to_square=__A					)
          lowerCamelCase__							     =		crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24}
          lowerCamelCase__							     =		get_size_dict(__A				,       param_name='crop_size'					)
          lowerCamelCase__							     =		do_resize
          lowerCamelCase__							     =		size
          lowerCamelCase__							     =		resample
          lowerCamelCase__							     =		do_center_crop
          lowerCamelCase__							     =		crop_size
          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   _UpperCamelCase							(			self				:       Optional[Any]				,       SCREAMING_SNAKE_CASE__				:       np.ndarray				,       SCREAMING_SNAKE_CASE__				:       Dict[str, int]				,       SCREAMING_SNAKE_CASE__				:       PILImageResampling = PILImageResampling.BICUBIC				,       SCREAMING_SNAKE_CASE__				:       Optional[Union[str, ChannelDimension]] = None				,       **SCREAMING_SNAKE_CASE__				:       List[Any]				,       ):
          lowerCamelCase__							     =		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()}'					)
          lowerCamelCase__							     =		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   _UpperCamelCase							(			self				:       Tuple				,       SCREAMING_SNAKE_CASE__				:       np.ndarray				,       SCREAMING_SNAKE_CASE__				:       Dict[str, int]				,       SCREAMING_SNAKE_CASE__				:       Optional[Union[str, ChannelDimension]] = None				,       **SCREAMING_SNAKE_CASE__				:       str				,       ):
          lowerCamelCase__							     =		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   _UpperCamelCase							(			self				:       List[str]				,       SCREAMING_SNAKE_CASE__				:       np.ndarray				,       SCREAMING_SNAKE_CASE__				:       float				,       SCREAMING_SNAKE_CASE__				:       Optional[Union[str, ChannelDimension]] = None				,       **SCREAMING_SNAKE_CASE__				:       Optional[int]					):
          return rescale(__A				,       scale=__A				,       data_format=__A				,       **__A					)
    def   _UpperCamelCase							(			self				:       Any				,       SCREAMING_SNAKE_CASE__				:       np.ndarray				,       SCREAMING_SNAKE_CASE__				:       Union[float, List[float]]				,       SCREAMING_SNAKE_CASE__				:       Union[float, List[float]]				,       SCREAMING_SNAKE_CASE__				:       Optional[Union[str, ChannelDimension]] = None				,       **SCREAMING_SNAKE_CASE__				:       Tuple				,       ):
          return normalize(__A				,       mean=__A				,       std=__A				,       data_format=__A				,       **__A					)
    def   _UpperCamelCase							(			self				:       int				,       SCREAMING_SNAKE_CASE__				:       ImageInput				,       SCREAMING_SNAKE_CASE__				:       Optional[bool] = None				,       SCREAMING_SNAKE_CASE__				:       Dict[str, int] = None				,       SCREAMING_SNAKE_CASE__				:       PILImageResampling = None				,       SCREAMING_SNAKE_CASE__				:       bool = None				,       SCREAMING_SNAKE_CASE__				:       Dict[str, int] = None				,       SCREAMING_SNAKE_CASE__				:       Optional[bool] = None				,       SCREAMING_SNAKE_CASE__				:       Optional[float] = None				,       SCREAMING_SNAKE_CASE__				:       Optional[bool] = None				,       SCREAMING_SNAKE_CASE__				:       Optional[Union[float, List[float]]] = None				,       SCREAMING_SNAKE_CASE__				:       Optional[Union[float, List[float]]] = None				,       SCREAMING_SNAKE_CASE__				:       Optional[Union[str, TensorType]] = None				,       SCREAMING_SNAKE_CASE__				:       Union[str, ChannelDimension] = ChannelDimension.FIRST				,       **SCREAMING_SNAKE_CASE__				:       Optional[int]				,       ):
          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(__A				,       default_to_square=__A					)
          lowerCamelCase__							     =		resample if resample is not None else self.resample
          lowerCamelCase__							     =		do_center_crop if do_center_crop is not None else self.do_center_crop
          lowerCamelCase__							     =		crop_size if crop_size is not None else self.crop_size
          lowerCamelCase__							     =		get_size_dict(__A				,       param_name='crop_size'					)
          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(__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.
          lowerCamelCase__							     =		[to_numpy_array(__A					) for image in images]

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

          if do_center_crop:
                lowerCamelCase__							     =		[self.center_crop(image=__A				,       size=__A					) for image in images]

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

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

          lowerCamelCase__							     =		[to_channel_dimension_format(__A				,       __A					) for image in images]

          lowerCamelCase__							     =		{"""pixel_values""": images}
          return BatchFeature(data=__A				,       tensor_type=__A					)


    def   _UpperCamelCase							(			self				:       int				,       SCREAMING_SNAKE_CASE__				:       List[str]				,       SCREAMING_SNAKE_CASE__				:       List[Tuple] = None					):
          lowerCamelCase__							     =		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					):
                      lowerCamelCase__							     =		target_sizes.numpy()

                lowerCamelCase__							     =		[]

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

          return semantic_segmentation






from typing import List, Optional

import numpy as np

from ...processing_utils import ProcessorMixin
from ...utils import to_numpy






class      lowerCamelCase_      (	_lowercase	):
	_lowercase		:   Union[str, Any]     					=				'''EncodecFeatureExtractor'''
	_lowercase		:   Any     					=				('''T5Tokenizer''', '''T5TokenizerFast''')




	def __init__(     self						:     List[Any]					,      __A						:     Any					,      __A						:     Tuple							):
		super().__init__(__A					,      __A							)
		__A :			Dict		    =			self.feature_extractor
		__A :			List[str]		    =			False




	def        lowerCAmelCase_       (     self						:     Union[str, Any]					,      __A						:     str=None					,      __A						:     Tuple=None					,      __A						:     Dict=True							):
		return self.tokenizer.get_decoder_prompt_ids(task=__A					,      language=__A					,      no_timestamps=__A							)




	def __call__(     self						:     Optional[Any]					,      *__A						:     Tuple					,      **__A						:     Tuple							):
		# For backward compatibility
		if self._in_target_context_manager:
			return self.current_processor(*__A					,      **__A							)

		__A :			str		    =			kwargs.pop("""audio"""					,      __A							)
		__A :			Optional[Any]		    =			kwargs.pop("""sampling_rate"""					,      __A							)
		__A :			int		    =			kwargs.pop("""text"""					,      __A							)
		if len(__A							) > 0:
			__A :			int		    =			args[0]
			__A :			Dict		    =			args[1:]

		if audio is None and text is None:
			raise ValueError("""You need to specify either an `audio` or `text` input to process."""							)

		if text is not None:
			__A :			Dict		    =			self.tokenizer(__A					,      **__A							)

		if audio is not None:
			__A :			Optional[int]		    =			self.feature_extractor(__A					,      *__A					,      sampling_rate=__A					,      **__A							)

		if audio is None:
			return inputs

		elif text is None:
			return audio_inputs

		else:
			__A :			List[Any]		    =			audio_inputs["""input_values"""]
			if "padding_mask" in audio_inputs:
				__A :			int		    =			audio_inputs["""padding_mask"""]
			return inputs




	def        lowerCAmelCase_       (     self						:     List[str]					,      *__A						:     int					,      **__A						:     Tuple							):
		__A :			Optional[int]		    =			kwargs.pop("""audio"""					,      __A							)
		__A :			List[str]		    =			kwargs.pop("""padding_mask"""					,      __A							)

		if len(__A							) > 0:
			__A :			Dict		    =			args[0]
			__A :			Optional[int]		    =			args[1:]

		if audio_values is not None:
			return self._decode_audio(__A					,      padding_mask=__A							)
		else:
			return self.tokenizer.batch_decode(*__A					,      **__A							)




	def        lowerCAmelCase_       (     self						:     Optional[Any]					,      *__A						:     Dict					,      **__A						:     Any							):
		return self.tokenizer.decode(*__A					,      **__A							)




	def        lowerCAmelCase_       (     self						:     Tuple					,      __A						:     Union[str, Any]					,      __A						:     Optional = None							):
		__A :			List[str]		    =			to_numpy(__A							)
		__A    ,				__A    ,				__A :			Tuple		    =			audio_values.shape

		if padding_mask is None:
			return list(__A							)

		__A :			Union[str, Any]		    =			to_numpy(__A							)

		# match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding**
		# token (so that the generated audio values are **not** treated as padded tokens)
		__A :			List[str]		    =			seq_len - padding_mask.shape[-1]
		__A :			Tuple		    =			1 - self.feature_extractor.padding_value
		__A :			Optional[int]		    =			np.pad(__A					,      ((0, 0), (0, difference))					,      """constant"""					,      constant_values=__A							)

		__A :			int		    =			audio_values.tolist()
		for i in range(__A							):
			__A :			str		    =			np.asarray(audio_values[i]							)[
			    padding_mask[i][None, :] != self.feature_extractor.padding_value
			]
			__A :			List[Any]		    =			sliced_audio.reshape(__A					,      -1							)

		return audio_values





