






'''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,
    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


__A							:							Optional[int]  							=		logging.get_logger(__name__)
class 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							["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 / 255				,     __lowerCamelCase     :     bool = True				,     __lowerCamelCase     :     Dict[str, int] = None				,     __lowerCamelCase     :     bool = True				,     **__lowerCamelCase     :     str				,     )							->							None:

     '''simple docstring'''




     super().__init__(**__lowerCamelCase     )
     lowerCamelCase__  =     size if size is not None else {"shortest_edge": 224}
     lowerCamelCase__  =     get_size_dict(__lowerCamelCase				,     default_to_square=__lowerCamelCase     )
     lowerCamelCase__  =     crop_size if crop_size is not None else {"height": 256, "width": 256}
     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    a__				(					self     :     List[str]				,     __lowerCamelCase     :     np.ndarray				,     __lowerCamelCase     :     Dict[str, int]				,     __lowerCamelCase     :     PILImageResampling = PIL.Image.BILINEAR				,     __lowerCamelCase     :     Optional[Union[str, ChannelDimension]] = None				,     **__lowerCamelCase     :     str				,     )							->							np.ndarray:

     '''simple docstring'''




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

     '''simple docstring'''




     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    a__				(					self     :     int				,     __lowerCamelCase     :     np.ndarray				,     __lowerCamelCase     :     Union[int, float]				,     __lowerCamelCase     :     Optional[Union[str, ChannelDimension]] = None				,     **__lowerCamelCase     :     Optional[Any]				,     )							->							int:

     '''simple docstring'''




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

    def    a__				(					self     :     Tuple				,     __lowerCamelCase     :     np.ndarray				,     __lowerCamelCase     :     Optional[Union[str, ChannelDimension]] = None     )							->							np.ndarray:

     '''simple docstring'''




     return flip_channel_order(__lowerCamelCase				,     data_format=__lowerCamelCase     )

    def    a__				(					self     :     Optional[int]				,     __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     :     Optional[Any]				,     )							->							PIL.Image.Image:

     '''simple docstring'''




     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    a__				(					self     :     Tuple				,     __lowerCamelCase     :     Optional[int]				,     __lowerCamelCase     :     List[Tuple] = None     )							->							Optional[int]:

     '''simple docstring'''




     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









'''simple docstring'''





import warnings

from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum

from ...processing_utils import ProcessorMixin


if is_torch_available():
 import torch
class 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							"char"
    lowerCAmelCase__      				=							"bpe"
    lowerCAmelCase__      				=							"wp"
__A							:							Any  							=		(DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)
class 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							["image_processor", "char_tokenizer"]
    lowerCAmelCase__      				=							"ViTImageProcessor"
    lowerCAmelCase__      				=							"MgpstrTokenizer"

    def __init__(					self     :     Any				,     __lowerCamelCase     :     Optional[Any]=None				,     __lowerCamelCase     :     List[str]=None				,     **__lowerCamelCase     :     Any     )							->							Optional[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     None
     if "feature_extractor" in kwargs:
      warnings.warn(
          "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
          " instead."				,     __lowerCamelCase				,     )
      lowerCamelCase__  =     kwargs.pop("feature_extractor"     )

     lowerCamelCase__  =     image_processor if image_processor is not None else feature_extractor
     if image_processor is None:
      raise ValueError("You need to specify an `image_processor`."     )
     if tokenizer is None:
      raise ValueError("You need to specify a `tokenizer`."     )

     lowerCamelCase__  =     tokenizer
     lowerCamelCase__  =     AutoTokenizer.from_pretrained("gpt2"     )
     lowerCamelCase__  =     AutoTokenizer.from_pretrained("bert-base-uncased"     )

     super().__init__(__lowerCamelCase				,     __lowerCamelCase     )

    def __call__(					self     :     List[str]				,     __lowerCamelCase     :     Union[str, Any]=None				,     __lowerCamelCase     :     List[Any]=None				,     __lowerCamelCase     :     str=None				,     **__lowerCamelCase     :     Optional[Any]     )							->							str:

     '''simple docstring'''




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

     if images is not None:
      lowerCamelCase__  =     self.image_processor(__lowerCamelCase				,     return_tensors=__lowerCamelCase				,     **__lowerCamelCase     )
     if text is not None:
      lowerCamelCase__  =     self.char_tokenizer(__lowerCamelCase				,     return_tensors=__lowerCamelCase				,     **__lowerCamelCase     )

     if text is None:
      return inputs
     elif images is None:
      return encodings
     else:
      lowerCamelCase__  =     encodings["input_ids"]
      return inputs

    def    a__				(					self     :     Any				,     __lowerCamelCase     :     Tuple     )							->							Tuple:

     '''simple docstring'''




     lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  =     sequences
     lowerCamelCase__  =     char_preds.size(0     )

     lowerCamelCase__  ,	lowerCamelCase__  =     self._decode_helper(__lowerCamelCase				,     "char"     )
     lowerCamelCase__  ,	lowerCamelCase__  =     self._decode_helper(__lowerCamelCase				,     "bpe"     )
     lowerCamelCase__  ,	lowerCamelCase__  =     self._decode_helper(__lowerCamelCase				,     "wp"     )

     lowerCamelCase__  =     []
     lowerCamelCase__  =     []
     for i in range(__lowerCamelCase     ):
      lowerCamelCase__  =     [char_scores[i], bpe_scores[i], wp_scores[i]]
      lowerCamelCase__  =     [char_strs[i], bpe_strs[i], wp_strs[i]]
      lowerCamelCase__  =     scores.index(max(__lowerCamelCase     )     )
      final_strs.append(strs[max_score_index]     )
      final_scores.append(scores[max_score_index]     )

     lowerCamelCase__  =     {}
     lowerCamelCase__  =     final_strs
     lowerCamelCase__  =     final_scores
     lowerCamelCase__  =     char_strs
     lowerCamelCase__  =     bpe_strs
     lowerCamelCase__  =     wp_strs
     return out

    def    a__				(					self     :     Optional[Any]				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     Any     )							->							Optional[int]:

     '''simple docstring'''




     if format == DecodeType.CHARACTER:
      lowerCamelCase__  =     self.char_decode
      lowerCamelCase__  =     1
      lowerCamelCase__  =     "[s]"
     elif format == DecodeType.BPE:
      lowerCamelCase__  =     self.bpe_decode
      lowerCamelCase__  =     2
      lowerCamelCase__  =     "#"
     elif format == DecodeType.WORDPIECE:
      lowerCamelCase__  =     self.wp_decode
      lowerCamelCase__  =     102
      lowerCamelCase__  =     "[SEP]"
     else:
      raise ValueError(f'''Format {format} is not supported.'''     )

     lowerCamelCase__  ,	lowerCamelCase__  =     [], []
     lowerCamelCase__  =     pred_logits.size(0     )
     lowerCamelCase__  =     pred_logits.size(1     )
     lowerCamelCase__  ,	lowerCamelCase__  =     pred_logits.topk(1				,     dim=-1				,     largest=__lowerCamelCase				,     sorted=__lowerCamelCase     )
     lowerCamelCase__  =     preds_index.view(-1				,     __lowerCamelCase     )[:, 1:]
     lowerCamelCase__  =     decoder(__lowerCamelCase     )
     lowerCamelCase__  ,	lowerCamelCase__  =     torch.nn.functional.softmax(__lowerCamelCase				,     dim=2     ).max(dim=2     )
     lowerCamelCase__  =     preds_max_prob[:, 1:]

     for index in range(__lowerCamelCase     ):
      lowerCamelCase__  =     preds_str[index].find(__lowerCamelCase     )
      lowerCamelCase__  =     preds_str[index][:pred_eos]
      lowerCamelCase__  =     preds_index[index].cpu().tolist()
      lowerCamelCase__  =     pred_index.index(__lowerCamelCase     ) if eos_token in pred_index else -1
      lowerCamelCase__  =     preds_max_prob[index][: pred_eos_index + 1]
      lowerCamelCase__  =     pred_max_prob.cumprod(dim=0     )[-1] if pred_max_prob.nelement() != 0 else 0.0
      dec_strs.append(__lowerCamelCase     )
      conf_scores.append(__lowerCamelCase     )

     return dec_strs, conf_scores

    def    a__				(					self     :     Any				,     __lowerCamelCase     :     Tuple     )							->							List[str]:

     '''simple docstring'''




     lowerCamelCase__  =     [seq.replace(" "				,     ""     ) for seq in self.char_tokenizer.batch_decode(__lowerCamelCase     )]
     return decode_strs

    def    a__				(					self     :     Optional[Any]				,     __lowerCamelCase     :     Tuple     )							->							Union[str, Any]:

     '''simple docstring'''




     return self.bpe_tokenizer.batch_decode(__lowerCamelCase     )




    def    a__				(					self     :     Union[str, Any]				,     __lowerCamelCase     :     int     )							->							Optional[int]:

     '''simple docstring'''




     lowerCamelCase__  =     [seq.replace(" "				,     ""     ) for seq in self.wp_tokenizer.batch_decode(__lowerCamelCase     )]
     return decode_strs

