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


lowercase_       :						List[Any]     					=	logging.get_logger(__name__)
class 			UpperCamelCase      (							lowerCamelCase__  ):
     A__      =			["""pixel_values"""]
     def __init__(     self  ,     snake_case__ = True  ,     snake_case__ = None  ,     snake_case__ = PILImageResampling.BILINEAR  ,     snake_case__ = True  ,     snake_case__ = None  ,     snake_case__ = True  ,     snake_case__ = 1 / 255  ,     snake_case__ = True  ,     snake_case__ = None  ,     snake_case__ = None  ,     **snake_case__  ,     ):




       """simple docstring"""


       super().__init__(**__lowerCamelCase				)
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = size if size is not None else {'''shortest_edge''': 256}
       _SCREAMING_SNAKE_CASE   :				Any							    = get_size_dict(__lowerCamelCase  ,     default_to_square=__lowerCamelCase				)
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
       _SCREAMING_SNAKE_CASE   :				Any							    = get_size_dict(__lowerCamelCase  ,     param_name="crop_size"				)
       _SCREAMING_SNAKE_CASE   :				Dict							    = do_resize
       _SCREAMING_SNAKE_CASE   :				str							    = size
       _SCREAMING_SNAKE_CASE   :				Tuple							    = resample
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = do_center_crop
       _SCREAMING_SNAKE_CASE   :				Dict							    = crop_size
       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = do_rescale
       _SCREAMING_SNAKE_CASE   :				List[str]							    = rescale_factor
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = do_normalize
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       _SCREAMING_SNAKE_CASE   :				str							    = image_std if image_std is not None else IMAGENET_STANDARD_STD
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__ = PILImageResampling.BICUBIC  ,     snake_case__ = None  ,     **snake_case__  ,     ):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				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()}'''				)
       _SCREAMING_SNAKE_CASE   :				str							    = 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 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__ = None  ,     **snake_case__  ,     ):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Union[str, 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 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__ = None  ,     **snake_case__				):




       """simple docstring"""


       return rescale(__lowerCamelCase  ,     scale=__lowerCamelCase  ,     data_format=__lowerCamelCase  ,     **__lowerCamelCase				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__ = None  ,     **snake_case__  ,     ):




       """simple docstring"""


       return normalize(__lowerCamelCase  ,     mean=__lowerCamelCase  ,     std=__lowerCamelCase  ,     data_format=__lowerCamelCase  ,     **__lowerCamelCase				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__ = None  ,     snake_case__ = None  ,     snake_case__ = None  ,     snake_case__ = None  ,     snake_case__ = None  ,     snake_case__ = None  ,     snake_case__ = None  ,     snake_case__ = None  ,     snake_case__ = None  ,     snake_case__ = None  ,     snake_case__ = None  ,     snake_case__ = ChannelDimension.FIRST  ,     **snake_case__  ,     ):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = do_resize if do_resize is not None else self.do_resize
       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = size if size is not None else self.size
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = get_size_dict(__lowerCamelCase  ,     default_to_square=__lowerCamelCase				)
       _SCREAMING_SNAKE_CASE   :				Dict							    = resample if resample is not None else self.resample
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = do_center_crop if do_center_crop is not None else self.do_center_crop
       _SCREAMING_SNAKE_CASE   :				Any							    = crop_size if crop_size is not None else self.crop_size
       _SCREAMING_SNAKE_CASE   :				List[str]							    = get_size_dict(__lowerCamelCase  ,     param_name="crop_size"				)
       _SCREAMING_SNAKE_CASE   :				List[str]							    = do_rescale if do_rescale is not None else self.do_rescale
       _SCREAMING_SNAKE_CASE   :				str							    = rescale_factor if rescale_factor is not None else self.rescale_factor
       _SCREAMING_SNAKE_CASE   :				int							    = do_normalize if do_normalize is not None else self.do_normalize
       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = image_mean if image_mean is not None else self.image_mean
       _SCREAMING_SNAKE_CASE   :				List[Any]							    = image_std if image_std is not None else self.image_std

       _SCREAMING_SNAKE_CASE   :				Any							    = 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.
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = [to_numpy_array(__lowerCamelCase				) for image in images]

       if do_resize:
         _SCREAMING_SNAKE_CASE   :				str							    = [self.resize(image=__lowerCamelCase  ,     size=__lowerCamelCase  ,     resample=__lowerCamelCase				) for image in images]

       if do_center_crop:
         _SCREAMING_SNAKE_CASE   :				List[Any]							    = [self.center_crop(image=__lowerCamelCase  ,     size=__lowerCamelCase				) for image in images]

       if do_rescale:
         _SCREAMING_SNAKE_CASE   :				Any							    = [self.rescale(image=__lowerCamelCase  ,     scale=__lowerCamelCase				) for image in images]

       if do_normalize:
         _SCREAMING_SNAKE_CASE   :				Tuple							    = [self.normalize(image=__lowerCamelCase  ,     mean=__lowerCamelCase  ,     std=__lowerCamelCase				) for image in images]

       _SCREAMING_SNAKE_CASE   :				int							    = [to_channel_dimension_format(__lowerCamelCase  ,     __lowerCamelCase				) for image in images]

       _SCREAMING_SNAKE_CASE   :				int							    = {'''pixel_values''': images}
       return BatchFeature(data=__lowerCamelCase  ,     tensor_type=__lowerCamelCase				)




     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__ = None				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = 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				):
           _SCREAMING_SNAKE_CASE   :				str							    = target_sizes.numpy()

         _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = []

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

       return semantic_segmentation





"""simple docstring"""
import re
import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin
class 			UpperCamelCase      (							__SCREAMING_SNAKE_CASE  ):
     A__      =			["""image_processor""", """tokenizer"""]
     A__      =			"""AutoImageProcessor"""
     A__      =			"""AutoTokenizer"""
     def __init__(     self  ,     snake_case__=None  ,     snake_case__=None  ,     **snake_case__				):




       """simple docstring"""


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

       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = 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`."				)

       super().__init__(snake_case__  ,     snake_case__				)
       _SCREAMING_SNAKE_CASE   :				Any							    = self.image_processor
       _SCREAMING_SNAKE_CASE   :				Any							    = False
     def __call__(     self  ,     *snake_case__  ,     **snake_case__				):




       """simple docstring"""


       if self._in_target_context_manager:
         return self.current_processor(*snake_case__  ,     **snake_case__				)

       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = kwargs.pop("images"  ,     snake_case__				)
       _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = kwargs.pop("text"  ,     snake_case__				)
       if len(snake_case__				) > 0:
         _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = args[0]
         _SCREAMING_SNAKE_CASE   :				List[str]							    = args[1:]

       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:
         _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = self.image_processor(snake_case__  ,     *snake_case__  ,     **snake_case__				)
       if text is not None:
         _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = self.tokenizer(snake_case__  ,     **snake_case__				)

       if text is None:
         return inputs
       elif images is None:
         return encodings
       else:
         _SCREAMING_SNAKE_CASE   :				List[Any]							    = encodings["input_ids"]
         return inputs
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     *snake_case__  ,     **snake_case__				):




       """simple docstring"""


       return self.tokenizer.batch_decode(*snake_case__  ,     **snake_case__				)
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     *snake_case__  ,     **snake_case__				):




       """simple docstring"""


       return self.tokenizer.decode(*snake_case__  ,     **snake_case__				)
     @contextmanager
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       warnings.warn(
           "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
           "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
           "your images inputs, or in a separate call."				)
       _SCREAMING_SNAKE_CASE   :				Dict							    = True
       _SCREAMING_SNAKE_CASE   :				str							    = self.tokenizer
       yield
       _SCREAMING_SNAKE_CASE   :				str							    = self.image_processor
       _SCREAMING_SNAKE_CASE   :				int							    = False
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__=False  ,     snake_case__=None				):




       """simple docstring"""


       if added_vocab is None:
         _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = self.tokenizer.get_added_vocab()

       _SCREAMING_SNAKE_CASE   :				int							    = {}

       while tokens:
         _SCREAMING_SNAKE_CASE   :				List[Any]							    = re.search(r"<s_(.*?)>"  ,     snake_case__  ,     re.IGNORECASE				)
         if start_token is None:
           break
         _SCREAMING_SNAKE_CASE   :				List[Any]							    = start_token.group(1				)
         _SCREAMING_SNAKE_CASE   :				Any							    = re.search(rF'''</s_{key}>'''  ,     snake_case__  ,     re.IGNORECASE				)
         _SCREAMING_SNAKE_CASE   :				Tuple							    = start_token.group()
         if end_token is None:
           _SCREAMING_SNAKE_CASE   :				Optional[int]							    = tokens.replace(snake_case__  ,     ""				)
         else:
           _SCREAMING_SNAKE_CASE   :				Any							    = end_token.group()
           _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = re.escape(snake_case__				)
           _SCREAMING_SNAKE_CASE   :				Union[str, Any]							    = re.escape(snake_case__				)
           _SCREAMING_SNAKE_CASE   :				str							    = re.search(F'''{start_token_escaped}(.*?){end_token_escaped}'''  ,     snake_case__  ,     re.IGNORECASE				)
           if content is not None:
             _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = content.group(1				).strip()
             if r"<s_" in content and r"</s_" in content:  # non-leaf node
               _SCREAMING_SNAKE_CASE   :				Dict							    = self.tokenajson(snake_case__  ,     is_inner_value=snake_case__  ,     added_vocab=snake_case__				)
               if value:
                 if len(snake_case__				) == 1:
                   _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = value[0]
                 _SCREAMING_SNAKE_CASE   :				Dict							    = value
             else:  # leaf nodes
               _SCREAMING_SNAKE_CASE   :				Dict							    = []
               for leaf in content.split(r"<sep/>"				):
                 _SCREAMING_SNAKE_CASE   :				int							    = leaf.strip()
                 if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
                   _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = leaf[1:-2]  # for categorical special tokens
                 output[key].append(snake_case__				)
               if len(output[key]				) == 1:
                 _SCREAMING_SNAKE_CASE   :				Dict							    = output[key][0]

           _SCREAMING_SNAKE_CASE   :				List[Any]							    = tokens[tokens.find(snake_case__				) + len(snake_case__				) :].strip()
           if tokens[:6] == r"<sep/>":  # non-leaf nodes
             return [output] + self.tokenajson(tokens[6:]  ,     is_inner_value=snake_case__  ,     added_vocab=snake_case__				)

       if len(snake_case__				):
         return [output] if is_inner_value else output
       else:
         return [] if is_inner_value else {"text_sequence": tokens}
     @property
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       warnings.warn(
           "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."  ,     snake_case__  ,     )
       return self.image_processor_class




     @property
     def 				__SCREAMING_SNAKE_CASE							(     self				):




       """simple docstring"""


       warnings.warn(
           "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."  ,     snake_case__  ,     )
       return self.image_processor



