





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,
    flip_channel_order,
    get_resize_output_image_size,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging


if is_vision_available():
     import PIL

if is_torch_available():
     import torch


_snake_case  :    Optional[Any]						    =  logging.get_logger(__name__)



class 				_UpperCAmelCase    (    _UpperCamelCase    ):

  """simple docstring"""


  a_        = ["""pixel_values"""]






  def __init__(				self :		int					,  lowerCAmelCase_ :		bool = True					,  lowerCAmelCase_ :		Dict[str, int] = None					,  lowerCAmelCase_ :		PILImageResampling = PILImageResampling.BILINEAR					,  lowerCAmelCase_ :		bool = True					,  lowerCAmelCase_ :		Union[int, float] = 1 / 2_5_5					,  lowerCAmelCase_ :		bool = True					,  lowerCAmelCase_ :		Dict[str, int] = None					,  lowerCAmelCase_ :		bool = True					,  **lowerCAmelCase_ :		Optional[Any]					,  )							->						None:
     super().__init__(**lowerCAmelCase_     )
     __lowerCAmelCase								=	size if size is not None else {'shortest_edge': 2_2_4}
     __lowerCAmelCase								=	get_size_dict(lowerCAmelCase_					,  default_to_square=lowerCAmelCase_     )
     __lowerCAmelCase								=	crop_size if crop_size is not None else {'height': 2_5_6, 'width': 2_5_6}
     __lowerCAmelCase								=	get_size_dict(lowerCAmelCase_					,  param_name='crop_size'     )

     __lowerCAmelCase								=	do_resize
     __lowerCAmelCase								=	size
     __lowerCAmelCase								=	resample
     __lowerCAmelCase								=	do_rescale
     __lowerCAmelCase								=	rescale_factor
     __lowerCAmelCase								=	do_center_crop
     __lowerCAmelCase								=	crop_size
     __lowerCAmelCase								=	do_flip_channel_order






  def 				lowercase		(				self :		List[Any]					,  lowerCAmelCase_ :		np.ndarray					,  lowerCAmelCase_ :		Dict[str, int]					,  lowerCAmelCase_ :		PILImageResampling = PIL.Image.BILINEAR					,  lowerCAmelCase_ :		Optional[Union[str, ChannelDimension]] = None					,  **lowerCAmelCase_ :		Any					,  )							->						np.ndarray:
     __lowerCAmelCase								=	get_size_dict(lowerCAmelCase_					,  default_to_square=lowerCAmelCase_     )
     if "shortest_edge" not in size:
        raise ValueError(f"""The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}"""     )
     __lowerCAmelCase								=	get_resize_output_image_size(lowerCAmelCase_					,  size=size['shortest_edge']					,  default_to_square=lowerCAmelCase_     )
     return resize(lowerCAmelCase_					,  size=lowerCAmelCase_					,  resample=lowerCAmelCase_					,  data_format=lowerCAmelCase_					,  **lowerCAmelCase_     )






  def 				lowercase		(				self :		str					,  lowerCAmelCase_ :		np.ndarray					,  lowerCAmelCase_ :		Dict[str, int]					,  lowerCAmelCase_ :		Optional[Union[str, ChannelDimension]] = None					,  **lowerCAmelCase_ :		Optional[Any]					,  )							->						np.ndarray:
     __lowerCAmelCase								=	get_size_dict(lowerCAmelCase_     )
     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()}"""     )
     return center_crop(lowerCAmelCase_					,  size=(size['height'], size['width'])					,  data_format=lowerCAmelCase_					,  **lowerCAmelCase_     )






  def 				lowercase		(				self :		Optional[Any]					,  lowerCAmelCase_ :		np.ndarray					,  lowerCAmelCase_ :		Union[int, float]					,  lowerCAmelCase_ :		Optional[Union[str, ChannelDimension]] = None					,  **lowerCAmelCase_ :		Tuple					,  )							->						List[str]:
     return rescale(lowerCAmelCase_					,  scale=lowerCAmelCase_					,  data_format=lowerCAmelCase_					,  **lowerCAmelCase_     )






  def 				lowercase		(				self :		Union[str, Any]					,  lowerCAmelCase_ :		np.ndarray					,  lowerCAmelCase_ :		Optional[Union[str, ChannelDimension]] = None     )							->						np.ndarray:
     return flip_channel_order(lowerCAmelCase_					,  data_format=lowerCAmelCase_     )






  def 				lowercase		(				self :		Any					,  lowerCAmelCase_ :		ImageInput					,  lowerCAmelCase_ :		bool = None					,  lowerCAmelCase_ :		Dict[str, int] = None					,  lowerCAmelCase_ :		PILImageResampling = None					,  lowerCAmelCase_ :		bool = None					,  lowerCAmelCase_ :		float = None					,  lowerCAmelCase_ :		bool = None					,  lowerCAmelCase_ :		Dict[str, int] = None					,  lowerCAmelCase_ :		bool = None					,  lowerCAmelCase_ :		Optional[Union[str, TensorType]] = None					,  lowerCAmelCase_ :		ChannelDimension = ChannelDimension.FIRST					,  **lowerCAmelCase_ :		int					,  )							->						PIL.Image.Image:
     __lowerCAmelCase								=	do_resize if do_resize is not None else self.do_resize
     __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_center_crop if do_center_crop is not None else self.do_center_crop
     __lowerCAmelCase								=	(
         do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
     )

     __lowerCAmelCase								=	size if size is not None else self.size
     __lowerCAmelCase								=	get_size_dict(lowerCAmelCase_					,  default_to_square=lowerCAmelCase_     )
     __lowerCAmelCase								=	crop_size if crop_size is not None else self.crop_size
     __lowerCAmelCase								=	get_size_dict(lowerCAmelCase_					,  param_name='crop_size'     )

     __lowerCAmelCase								=	make_list_of_images(lowerCAmelCase_     )

     if not valid_images(lowerCAmelCase_     ):
        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_rescale and rescale_factor is None:
        raise ValueError('Rescale factor must be specified if do_rescale is True.'     )

     if do_center_crop and crop_size is None:
        raise ValueError('Crop size must be specified if do_center_crop is True.'     )

     # All transformations expect numpy arrays.
     __lowerCAmelCase								=	[to_numpy_array(lowerCAmelCase_     ) for image in images]

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

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

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

     # the pretrained checkpoints assume images are BGR, not RGB
     if do_flip_channel_order:
        __lowerCAmelCase								=	[self.flip_channel_order(image=lowerCAmelCase_     ) for image in images]

     __lowerCAmelCase								=	[to_channel_dimension_format(lowerCAmelCase_					,  lowerCAmelCase_     ) for image in images]

     __lowerCAmelCase								=	{'pixel_values': images}
     return BatchFeature(data=lowerCAmelCase_					,  tensor_type=lowerCAmelCase_     )






  def 				lowercase		(				self :		Any					,  lowerCAmelCase_ :		Any					,  lowerCAmelCase_ :		List[Tuple] = None     )							->						int:
     __lowerCAmelCase								=	outputs.logits

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

        if is_torch_tensor(lowerCAmelCase_     ):
           __lowerCAmelCase								=	target_sizes.numpy()

        __lowerCAmelCase								=	[]

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

     return semantic_segmentation








from ...configuration_utils import PretrainedConfig
from ...utils import logging


_snake_case  :    List[Any]						    =  logging.get_logger(__name__)

_snake_case  :    Any						    =  {
    'google/pegasus-large': 'https://huggingface.co/google/pegasus-large/resolve/main/config.json',
    # See all PEGASUS models at https://huggingface.co/models?filter=pegasus
}



class 				_UpperCAmelCase    (    _UpperCamelCase    ):

  """simple docstring"""


  a_        = """pegasus"""
  a_        = ["""past_key_values"""]
  a_        = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}






  def __init__(				self :		List[str]					,  lowerCAmelCase_ :		Union[str, Any]=5_0_2_6_5					,  lowerCAmelCase_ :		Union[str, Any]=1_0_2_4					,  lowerCAmelCase_ :		Union[str, Any]=1_2					,  lowerCAmelCase_ :		Dict=4_0_9_6					,  lowerCAmelCase_ :		str=1_6					,  lowerCAmelCase_ :		List[Any]=1_2					,  lowerCAmelCase_ :		Union[str, Any]=4_0_9_6					,  lowerCAmelCase_ :		Union[str, Any]=1_6					,  lowerCAmelCase_ :		Any=0.0					,  lowerCAmelCase_ :		Optional[int]=0.0					,  lowerCAmelCase_ :		List[Any]=True					,  lowerCAmelCase_ :		Any=True					,  lowerCAmelCase_ :		Dict="gelu"					,  lowerCAmelCase_ :		Optional[int]=1_0_2_4					,  lowerCAmelCase_ :		List[str]=0.1					,  lowerCAmelCase_ :		str=0.0					,  lowerCAmelCase_ :		Union[str, Any]=0.0					,  lowerCAmelCase_ :		Optional[int]=0.02					,  lowerCAmelCase_ :		Tuple=0					,  lowerCAmelCase_ :		Tuple=False					,  lowerCAmelCase_ :		Union[str, Any]=0					,  lowerCAmelCase_ :		int=1					,  lowerCAmelCase_ :		Tuple=1					,  **lowerCAmelCase_ :		Tuple					,  )							->						List[str]:
     __lowerCAmelCase								=	vocab_size
     __lowerCAmelCase								=	max_position_embeddings
     __lowerCAmelCase								=	d_model
     __lowerCAmelCase								=	encoder_ffn_dim
     __lowerCAmelCase								=	encoder_layers
     __lowerCAmelCase								=	encoder_attention_heads
     __lowerCAmelCase								=	decoder_ffn_dim
     __lowerCAmelCase								=	decoder_layers
     __lowerCAmelCase								=	decoder_attention_heads
     __lowerCAmelCase								=	dropout
     __lowerCAmelCase								=	attention_dropout
     __lowerCAmelCase								=	activation_dropout
     __lowerCAmelCase								=	activation_function
     __lowerCAmelCase								=	init_std
     __lowerCAmelCase								=	encoder_layerdrop
     __lowerCAmelCase								=	decoder_layerdrop
     __lowerCAmelCase								=	use_cache
     __lowerCAmelCase								=	encoder_layers
     __lowerCAmelCase								=	scale_embedding  # scale factor will be sqrt(d_model) if True
     super().__init__(
         pad_token_id=lowerCAmelCase_					,  eos_token_id=lowerCAmelCase_					,  is_encoder_decoder=lowerCAmelCase_					,  decoder_start_token_id=lowerCAmelCase_					,  forced_eos_token_id=lowerCAmelCase_					,  **lowerCAmelCase_					,  )






  @property
  def 				lowercase		(				self :		List[Any]     )							->						int:
     return self.encoder_attention_heads






  @property
  def 				lowercase		(				self :		Optional[Any]     )							->						int:
     return self.d_model

