"""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


_a      :		List[str]           =   logging.get_logger(__name__)
class 						__A							( __UpperCAmelCase		):
     _UpperCamelCase							:			Optional[Any]							=		["pixel_values"]






     def __init__(		self				,     a__ = True				,     a__ = None				,     a__ = PILImageResampling.BILINEAR				,     a__ = True				,     a__ = None				,     a__ = True				,     a__ = 1 / 255				,     a__ = True				,     a__ = None				,     a__ = None				,     **a__				,     ):
       super().__init__(**lowerCamelCase__  )
       _lowerCAmelCase						:       List[Any]  			=     size if size is not None else {"""shortest_edge""": 256}
       _lowerCAmelCase						:       int  			=     get_size_dict(lowerCamelCase__				,     default_to_square=lowerCamelCase__  )
       _lowerCAmelCase						:       Union[str, Any]  			=     crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
       _lowerCAmelCase						:       Optional[Any]  			=     get_size_dict(lowerCamelCase__				,     param_name="""crop_size"""  )
       _lowerCAmelCase						:       Dict  			=     do_resize
       _lowerCAmelCase						:       List[str]  			=     size
       _lowerCAmelCase						:       Tuple  			=     resample
       _lowerCAmelCase						:       Optional[Any]  			=     do_center_crop
       _lowerCAmelCase						:       str  			=     crop_size
       _lowerCAmelCase						:       Tuple  			=     do_rescale
       _lowerCAmelCase						:       int  			=     rescale_factor
       _lowerCAmelCase						:       Union[str, Any]  			=     do_normalize
       _lowerCAmelCase						:       Optional[int]  			=     image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       _lowerCAmelCase						:       List[str]  			=     image_std if image_std is not None else IMAGENET_STANDARD_STD






     def     __A  (		self				,     a__				,     a__				,     a__ = PILImageResampling.BICUBIC				,     a__ = None				,     **a__				,     ):
       _lowerCAmelCase						:       Dict  			=     get_size_dict(lowerCamelCase__				,     default_to_square=lowerCamelCase__  )
       if "shortest_edge" not in size:
         raise ValueError(F"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"  )
       _lowerCAmelCase						:       int  			=     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     __A  (		self				,     a__				,     a__				,     a__ = None				,     **a__				,     ):
       _lowerCAmelCase						:       List[Any]  			=     get_size_dict(lowerCamelCase__  )
       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(lowerCamelCase__				,     size=(size["""height"""], size["""width"""])				,     data_format=lowerCamelCase__				,     **lowerCamelCase__  )






     def     __A  (		self				,     a__				,     a__				,     a__ = None				,     **a__  ):
       return rescale(lowerCamelCase__				,     scale=lowerCamelCase__				,     data_format=lowerCamelCase__				,     **lowerCamelCase__  )






     def     __A  (		self				,     a__				,     a__				,     a__				,     a__ = None				,     **a__				,     ):
       return normalize(lowerCamelCase__				,     mean=lowerCamelCase__				,     std=lowerCamelCase__				,     data_format=lowerCamelCase__				,     **lowerCamelCase__  )






     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__				,     ):
       _lowerCAmelCase						:       str  			=     do_resize if do_resize is not None else self.do_resize
       _lowerCAmelCase						:       Any  			=     size if size is not None else self.size
       _lowerCAmelCase						:       Optional[int]  			=     get_size_dict(lowerCamelCase__				,     default_to_square=lowerCamelCase__  )
       _lowerCAmelCase						:       int  			=     resample if resample is not None else self.resample
       _lowerCAmelCase						:       List[Any]  			=     do_center_crop if do_center_crop is not None else self.do_center_crop
       _lowerCAmelCase						:       List[Any]  			=     crop_size if crop_size is not None else self.crop_size
       _lowerCAmelCase						:       Optional[int]  			=     get_size_dict(lowerCamelCase__				,     param_name="""crop_size"""  )
       _lowerCAmelCase						:       Any  			=     do_rescale if do_rescale is not None else self.do_rescale
       _lowerCAmelCase						:       Any  			=     rescale_factor if rescale_factor is not None else self.rescale_factor
       _lowerCAmelCase						:       Union[str, Any]  			=     do_normalize if do_normalize is not None else self.do_normalize
       _lowerCAmelCase						:       List[Any]  			=     image_mean if image_mean is not None else self.image_mean
       _lowerCAmelCase						:       Dict  			=     image_std if image_std is not None else self.image_std

       _lowerCAmelCase						:       Tuple  			=     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_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						:       int  			=     [to_numpy_array(lowerCamelCase__  ) for image in images]

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

       if do_center_crop:
         _lowerCAmelCase						:       Union[str, Any]  			=     [self.center_crop(image=lowerCamelCase__				,     size=lowerCamelCase__  ) for image in images]

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

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

       _lowerCAmelCase						:       Optional[Any]  			=     [to_channel_dimension_format(lowerCamelCase__				,     lowerCamelCase__  ) for image in images]

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






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

         _lowerCAmelCase						:       int  			=     []

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

       return semantic_segmentation





"""simple docstring"""






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

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


lowerCAmelCase__  :  Optional[int]						     =	logging.get_logger(__name__)
class 				snake_case       ( __UpperCAmelCase				):




					"""simple docstring"""

					snake_case__				    = ["input_ids", "attention_mask"]







					def __init__(				self   :	Optional[int]    ,lowerCamelCase__   :	int="</s>"    ,lowerCamelCase__   :	str="<unk>"    ,lowerCamelCase__   :	Union[str, Any]="<pad>"    ,lowerCamelCase__   :	int=125    ,lowerCamelCase__   :	str=None    ,**lowerCamelCase__   :	Union[str, Any]    ,):
									# Add extra_ids to the special token list
									if extra_ids > 0 and additional_special_tokens is None:
													UpperCAmelCase__             =							[f'''<extra_id_{i}>''' for i in range(lowerCamelCase__			)]
									elif extra_ids > 0 and additional_special_tokens is not None:
													# Check that we have the right number of extra_id special tokens
													UpperCAmelCase__             =							len(set(filter(lambda lowerCamelCase__			: bool('extra_id' in str(lowerCamelCase__			)			)    ,lowerCamelCase__			)			)			)
													if extra_tokens != extra_ids:
																	raise ValueError(
																	    f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are'''
																	    ' provided to ByT5Tokenizer. In this case the additional_special_tokens must include the'
																	    ' extra_ids tokens'			)

									UpperCAmelCase__             =							AddedToken(lowerCamelCase__    ,lstrip=lowerCamelCase__    ,rstrip=lowerCamelCase__			) if isinstance(lowerCamelCase__    ,lowerCamelCase__			) else pad_token
									UpperCAmelCase__             =							AddedToken(lowerCamelCase__    ,lstrip=lowerCamelCase__    ,rstrip=lowerCamelCase__			) if isinstance(lowerCamelCase__    ,lowerCamelCase__			) else eos_token
									UpperCAmelCase__             =							AddedToken(lowerCamelCase__    ,lstrip=lowerCamelCase__    ,rstrip=lowerCamelCase__			) if isinstance(lowerCamelCase__    ,lowerCamelCase__			) else unk_token

									super().__init__(
									    eos_token=lowerCamelCase__    ,unk_token=lowerCamelCase__    ,pad_token=lowerCamelCase__    ,extra_ids=lowerCamelCase__    ,additional_special_tokens=lowerCamelCase__    ,**lowerCamelCase__    ,)

									UpperCAmelCase__             =							extra_ids

									UpperCAmelCase__             =							2**8  # utf is 8 bits

									# define special tokens dict
									UpperCAmelCase__             =							{
									    self.pad_token: 0,
									    self.eos_token: 1,
									    self.unk_token: 2,
									}
									UpperCAmelCase__             =							len(self.special_tokens_encoder			)
									UpperCAmelCase__             =							len(lowerCamelCase__			)
									for i, token in enumerate(lowerCamelCase__			):
													UpperCAmelCase__             =							self.vocab_size + i - n
									UpperCAmelCase__             =							{v: k for k, v in self.special_tokens_encoder.items()}







					@property
					def 		__lowerCAmelCase						(				self   :	Union[str, Any]			):
									return self._utf_vocab_size + self._num_special_tokens + self._extra_ids







					def 		__lowerCAmelCase						(				self   :	Optional[Any]    ,lowerCamelCase__   :	List[int]    ,lowerCamelCase__   :	Optional[List[int]] = None    ,lowerCamelCase__   :	bool = False			):
									if already_has_special_tokens:
													return super().get_special_tokens_mask(
													    token_ids_a=lowerCamelCase__    ,token_ids_a=lowerCamelCase__    ,already_has_special_tokens=lowerCamelCase__			)

									# normal case: some special tokens
									if token_ids_a is None:
													return ([0] * len(lowerCamelCase__			)) + [1]
									return ([0] * len(lowerCamelCase__			)) + [1] + ([0] * len(lowerCamelCase__			)) + [1]







					def 		__lowerCAmelCase						(				self   :	str    ,lowerCamelCase__   :	List[int]			):
									if len(lowerCamelCase__			) > 0 and token_ids[-1] == self.eos_token_id:
													warnings.warn(
													    f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated'''
													    ' eos tokens being added.'			)
													return token_ids
									else:
													return token_ids + [self.eos_token_id]







					def 		__lowerCAmelCase						(				self   :	str    ,lowerCamelCase__   :	List[int]    ,lowerCamelCase__   :	Optional[List[int]] = None			):
									UpperCAmelCase__             =							[self.eos_token_id]

									if token_ids_a is None:
													return len(token_ids_a + eos			) * [0]
									return len(token_ids_a + eos + token_ids_a + eos			) * [0]







					def 		__lowerCAmelCase						(				self   :	Dict    ,lowerCamelCase__   :	List[int]    ,lowerCamelCase__   :	Optional[List[int]] = None			):
									UpperCAmelCase__             =							self._add_eos_if_not_present(lowerCamelCase__			)
									if token_ids_a is None:
													return token_ids_a
									else:
													UpperCAmelCase__             =							self._add_eos_if_not_present(lowerCamelCase__			)
													return token_ids_a + token_ids_a







					def 		__lowerCAmelCase						(				self   :	Optional[Any]    ,lowerCamelCase__   :	str			):
									UpperCAmelCase__             =							[chr(lowerCamelCase__			) for i in text.encode('utf-8'			)]
									return tokens







					def 		__lowerCAmelCase						(				self   :	List[Any]    ,lowerCamelCase__   :	str			):
									if token in self.special_tokens_encoder:
													UpperCAmelCase__             =							self.special_tokens_encoder[token]
									elif token in self.added_tokens_encoder:
													UpperCAmelCase__             =							self.added_tokens_encoder[token]
									elif len(lowerCamelCase__			) != 1:
													UpperCAmelCase__             =							self.unk_token_id
									else:
													UpperCAmelCase__             =							ord(lowerCamelCase__			) + self._num_special_tokens
									return token_id







					def 		__lowerCAmelCase						(				self   :	Union[str, Any]    ,lowerCamelCase__   :	Any			):
									if index in self.special_tokens_decoder:
													UpperCAmelCase__             =							self.special_tokens_decoder[index]
									else:
													UpperCAmelCase__             =							chr(index - self._num_special_tokens			)
									return token







					def 		__lowerCAmelCase						(				self   :	Optional[Any]    ,lowerCamelCase__   :	Union[str, Any]			):
									UpperCAmelCase__             =							b''
									for token in tokens:
													if token in self.special_tokens_decoder:
																	UpperCAmelCase__             =							self.special_tokens_decoder[token].encode('utf-8'			)
													elif token in self.added_tokens_decoder:
																	UpperCAmelCase__             =							self.special_tokens_decoder[token].encode('utf-8'			)
													elif token in self.special_tokens_encoder:
																	UpperCAmelCase__             =							token.encode('utf-8'			)
													elif token in self.added_tokens_encoder:
																	UpperCAmelCase__             =							token.encode('utf-8'			)
													else:
																	UpperCAmelCase__             =							bytes([ord(lowerCamelCase__			)]			)
													bstring += tok_string
									UpperCAmelCase__             =							bstring.decode('utf-8'    ,errors='ignore'			)
									return string







					def 		__lowerCAmelCase						(				self   :	str    ,lowerCamelCase__   :	str    ,lowerCamelCase__   :	Optional[str] = None			):
									return ()



