'''simple docstring'''
import inspect
import unittest
import warnings

from transformers import DeiTConfig
from transformers.models.auto import get_values
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch
      from torch import nn

      from transformers import (
          MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
          MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
          MODEL_MAPPING,
          DeiTForImageClassification,
          DeiTForImageClassificationWithTeacher,
          DeiTForMaskedImageModeling,
          DeiTModel,
      )
      from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import DeiTImageProcessor







class lowerCamelCase							:




  '''simple docstring'''



  def __init__(      self			:       Optional[Any]  ,							UpperCAmelCase__			:       Optional[int]  ,							UpperCAmelCase__			:       Optional[int]=13  ,							UpperCAmelCase__			:       List[str]=30  ,							UpperCAmelCase__			:       Any=2  ,							UpperCAmelCase__			:       Dict=3  ,							UpperCAmelCase__			:       Optional[int]=True  ,							UpperCAmelCase__			:       int=True  ,							UpperCAmelCase__			:       Optional[Any]=32  ,							UpperCAmelCase__			:       str=5  ,							UpperCAmelCase__			:       List[Any]=4  ,							UpperCAmelCase__			:       str=37  ,							UpperCAmelCase__			:       Any="gelu"  ,							UpperCAmelCase__			:       Dict=0.1  ,							UpperCAmelCase__			:       Dict=0.1  ,							UpperCAmelCase__			:       Tuple=10  ,							UpperCAmelCase__			:       str=0.02  ,							UpperCAmelCase__			:       List[str]=3  ,							UpperCAmelCase__			:       Dict=None  ,							UpperCAmelCase__			:       Union[str, Any]=2  ,							)				->Union[str, Any]:
        UpperCAmelCase_            =  parent
        UpperCAmelCase_            =  batch_size
        UpperCAmelCase_            =  image_size
        UpperCAmelCase_            =  patch_size
        UpperCAmelCase_            =  num_channels
        UpperCAmelCase_            =  is_training
        UpperCAmelCase_            =  use_labels
        UpperCAmelCase_            =  hidden_size
        UpperCAmelCase_            =  num_hidden_layers
        UpperCAmelCase_            =  num_attention_heads
        UpperCAmelCase_            =  intermediate_size
        UpperCAmelCase_            =  hidden_act
        UpperCAmelCase_            =  hidden_dropout_prob
        UpperCAmelCase_            =  attention_probs_dropout_prob
        UpperCAmelCase_            =  type_sequence_label_size
        UpperCAmelCase_            =  initializer_range
        UpperCAmelCase_            =  scope
        UpperCAmelCase_            =  encoder_stride

        # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
        UpperCAmelCase_            =  (image_size // patch_size) ** 2
        UpperCAmelCase_            =  num_patches + 2






  def  lowerCAmelCase__ (      self			:       List[str]  )				->Dict:
        UpperCAmelCase_            =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

        UpperCAmelCase_            =  None
        if self.use_labels:
              UpperCAmelCase_            =  ids_tensor([self.batch_size]  ,							self.type_sequence_label_size  )

        UpperCAmelCase_            =  self.get_config()

        return config, pixel_values, labels






  def  lowerCAmelCase__ (      self			:       Dict  )				->List[Any]:
        return DeiTConfig(
            image_size=self.image_size  ,							patch_size=self.patch_size  ,							num_channels=self.num_channels  ,							hidden_size=self.hidden_size  ,							num_hidden_layers=self.num_hidden_layers  ,							num_attention_heads=self.num_attention_heads  ,							intermediate_size=self.intermediate_size  ,							hidden_act=self.hidden_act  ,							hidden_dropout_prob=self.hidden_dropout_prob  ,							attention_probs_dropout_prob=self.attention_probs_dropout_prob  ,							is_decoder=lowercase__  ,							initializer_range=self.initializer_range  ,							encoder_stride=self.encoder_stride  ,							)






  def  lowerCAmelCase__ (      self			:       Any  ,							UpperCAmelCase__			:       Dict  ,							UpperCAmelCase__			:       Optional[int]  ,							UpperCAmelCase__			:       Any  )				->List[str]:
        UpperCAmelCase_            =  DeiTModel(config=lowercase__  )
        model.to(lowercase__  )
        model.eval()
        UpperCAmelCase_            =  model(lowercase__  )
        self.parent.assertEqual(result.last_hidden_state.shape  ,							(self.batch_size, self.seq_length, self.hidden_size)  )






  def  lowerCAmelCase__ (      self			:       List[str]  ,							UpperCAmelCase__			:       str  ,							UpperCAmelCase__			:       str  ,							UpperCAmelCase__			:       int  )				->str:
        UpperCAmelCase_            =  DeiTForMaskedImageModeling(config=lowercase__  )
        model.to(lowercase__  )
        model.eval()
        UpperCAmelCase_            =  model(lowercase__  )
        self.parent.assertEqual(
            result.reconstruction.shape  ,							(self.batch_size, self.num_channels, self.image_size, self.image_size)  )

        # test greyscale images
        UpperCAmelCase_            =  1
        UpperCAmelCase_            =  DeiTForMaskedImageModeling(lowercase__  )
        model.to(lowercase__  )
        model.eval()

        UpperCAmelCase_            =  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
        UpperCAmelCase_            =  model(lowercase__  )
        self.parent.assertEqual(result.reconstruction.shape  ,							(self.batch_size, 1, self.image_size, self.image_size)  )






  def  lowerCAmelCase__ (      self			:       str  ,							UpperCAmelCase__			:       int  ,							UpperCAmelCase__			:       Optional[Any]  ,							UpperCAmelCase__			:       Any  )				->int:
        UpperCAmelCase_            =  self.type_sequence_label_size
        UpperCAmelCase_            =  DeiTForImageClassification(lowercase__  )
        model.to(lowercase__  )
        model.eval()
        UpperCAmelCase_            =  model(lowercase__  ,							labels=lowercase__  )
        self.parent.assertEqual(result.logits.shape  ,							(self.batch_size, self.type_sequence_label_size)  )

        # test greyscale images
        UpperCAmelCase_            =  1
        UpperCAmelCase_            =  DeiTForImageClassification(lowercase__  )
        model.to(lowercase__  )
        model.eval()

        UpperCAmelCase_            =  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
        UpperCAmelCase_            =  model(lowercase__  ,							labels=lowercase__  )
        self.parent.assertEqual(result.logits.shape  ,							(self.batch_size, self.type_sequence_label_size)  )






  def  lowerCAmelCase__ (      self			:       List[str]  )				->Optional[Any]:
        UpperCAmelCase_            =  self.prepare_config_and_inputs()
        (
            UpperCAmelCase_		
        )            =  config_and_inputs
        UpperCAmelCase_            =  {"pixel_values": pixel_values}
        return config, inputs_dict







@require_torch
class lowerCamelCase							(	_UpperCAmelCase     ,		_UpperCAmelCase     ,		unittest.TestCase					):




  '''simple docstring'''



  lowerCAmelCase__										=	(
      (
          DeiTModel,
          DeiTForImageClassification,
          DeiTForImageClassificationWithTeacher,
          DeiTForMaskedImageModeling,
      )
      if is_torch_available()
      else ()
  )
  lowerCAmelCase__										=	(
      {
          '''feature-extraction''': DeiTModel,
          '''image-classification''': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher),
      }
      if is_torch_available()
      else {}
  )

  lowerCAmelCase__										=	False
  lowerCAmelCase__										=	False
  lowerCAmelCase__										=	False






  def  lowerCAmelCase__ (      self			:       Optional[int]  )				->List[str]:
        UpperCAmelCase_            =  DeiTModelTester(self  )
        UpperCAmelCase_            =  ConfigTester(self  ,							config_class=lowercase__  ,							has_text_modality=lowercase__  ,							hidden_size=37  )






  def  lowerCAmelCase__ (      self			:       int  )				->int:
        self.config_tester.run_common_tests()






  @unittest.skip(reason='''DeiT does not use inputs_embeds'''  )
  def  lowerCAmelCase__ (      self			:       int  )				->str:
        pass






  def  lowerCAmelCase__ (      self			:       List[Any]  )				->Any:
        UpperCAmelCase_            =  self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              UpperCAmelCase_            =  model_class(lowercase__  )
              self.assertIsInstance(model.get_input_embeddings()  ,							(nn.Module)  )
              UpperCAmelCase_            =  model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(lowercase__  ,							nn.Linear  )  )






  def  lowerCAmelCase__ (      self			:       Optional[int]  )				->List[str]:
        UpperCAmelCase_            =  self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              UpperCAmelCase_            =  model_class(lowercase__  )
              UpperCAmelCase_            =  inspect.signature(model.forward  )
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              UpperCAmelCase_            =  [*signature.parameters.keys()]

              UpperCAmelCase_            =  ["pixel_values"]
              self.assertListEqual(arg_names[:1]  ,							lowercase__  )






  def  lowerCAmelCase__ (      self			:       Dict  )				->int:
        UpperCAmelCase_            =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase__  )






  def  lowerCAmelCase__ (      self			:       Optional[int]  )				->Union[str, Any]:
        UpperCAmelCase_            =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_image_modeling(*lowercase__  )






  def  lowerCAmelCase__ (      self			:       int  )				->int:
        UpperCAmelCase_            =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowercase__  )






  def  lowerCAmelCase__ (      self			:       Tuple  ,							UpperCAmelCase__			:       Optional[Any]  ,							UpperCAmelCase__			:       List[str]  ,							UpperCAmelCase__			:       Optional[Any]=False  )				->str:
        UpperCAmelCase_            =  super()._prepare_for_class(lowercase__  ,							lowercase__  ,							return_labels=lowercase__  )

        if return_labels:
              if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
                    del inputs_dict["labels"]

        return inputs_dict






  def  lowerCAmelCase__ (      self			:       str  )				->Optional[int]:






        if not self.model_tester.is_training:
              return

        UpperCAmelCase_            =  self.model_tester.prepare_config_and_inputs_for_common()
        UpperCAmelCase_            =  True

        for model_class in self.all_model_classes:
              # DeiTForImageClassificationWithTeacher supports inference-only
              if (
                  model_class in get_values(lowercase__  )
                  or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
              ):
                    continue
              UpperCAmelCase_            =  model_class(lowercase__  )
              model.to(lowercase__  )
              model.train()
              UpperCAmelCase_            =  self._prepare_for_class(lowercase__  ,							lowercase__  ,							return_labels=lowercase__  )
              UpperCAmelCase_            =  model(**lowercase__  ).loss
              loss.backward()






  def  lowerCAmelCase__ (      self			:       Tuple  )				->Tuple:
        UpperCAmelCase_            =  self.model_tester.prepare_config_and_inputs_for_common()
        if not self.model_tester.is_training:
              return

        UpperCAmelCase_            =  False
        UpperCAmelCase_            =  True

        for model_class in self.all_model_classes:
              if model_class in get_values(lowercase__  ) or not model_class.supports_gradient_checkpointing:
                    continue
              # DeiTForImageClassificationWithTeacher supports inference-only
              if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
                    continue
              UpperCAmelCase_            =  model_class(lowercase__  )
              model.gradient_checkpointing_enable()
              model.to(lowercase__  )
              model.train()
              UpperCAmelCase_            =  self._prepare_for_class(lowercase__  ,							lowercase__  ,							return_labels=lowercase__  )
              UpperCAmelCase_            =  model(**lowercase__  ).loss
              loss.backward()






  def  lowerCAmelCase__ (      self			:       Any  )				->List[Any]:
        UpperCAmelCase_            =  self.model_tester.prepare_config_and_inputs_for_common()

        UpperCAmelCase_            =  [
            {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float},
            {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long},
            {"title": "regression", "num_labels": 1, "dtype": torch.float},
        ]

        for model_class in self.all_model_classes:
              if (
                  model_class
                  not in [
                      *get_values(lowercase__  ),
                      *get_values(lowercase__  ),
                  ]
                  or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
              ):
                    continue

              for problem_type in problem_types:
                    with self.subTest(msg=f"""Testing {model_class} with {problem_type["title"]}"""  ):
                          UpperCAmelCase_            =  problem_type["title"]
                          UpperCAmelCase_            =  problem_type["num_labels"]

                          UpperCAmelCase_            =  model_class(lowercase__  )
                          model.to(lowercase__  )
                          model.train()

                          UpperCAmelCase_            =  self._prepare_for_class(lowercase__  ,							lowercase__  ,							return_labels=lowercase__  )

                          if problem_type["num_labels"] > 1:
                                UpperCAmelCase_            =  inputs["labels"].unsqueeze(1  ).repeat(1  ,							problem_type['''num_labels''']  )

                          UpperCAmelCase_            =  inputs["labels"].to(problem_type['''dtype''']  )

                          # This tests that we do not trigger the warning form PyTorch "Using a target size that is different
                          # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
                          # they have the same size." which is a symptom something in wrong for the regression problem.
                          # See https://github.com/huggingface/transformers/issues/11780
                          with warnings.catch_warnings(record=lowercase__  ) as warning_list:
                                UpperCAmelCase_            =  model(**lowercase__  ).loss
                          for w in warning_list:
                                if "Using a target size that is different to the input size" in str(w.message  ):
                                      raise ValueError(
                                          f"""Something is going wrong in the regression problem: intercepted {w.message}"""  )

                          loss.backward()






  @slow
  def  lowerCAmelCase__ (      self			:       Union[str, Any]  )				->Optional[int]:






        for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase_            =  DeiTModel.from_pretrained(lowercase__  )
              self.assertIsNotNone(lowercase__  )






def  __lowerCamelCase       (      ):


      '''simple docstring'''


      UpperCAmelCase_            =  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
      return image







@require_torch
@require_vision
class lowerCamelCase							(	unittest.TestCase					):




  '''simple docstring'''



  @cached_property
  def  lowerCAmelCase__ (      self			:       List[Any]  )				->Dict:
        return (
            DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224'''  )
            if is_vision_available()
            else None
        )






  @slow
  def  lowerCAmelCase__ (      self			:       List[Any]  )				->Optional[Any]:
        UpperCAmelCase_            =  DeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224'''  ).to(
            lowercase__  )

        UpperCAmelCase_            =  self.default_image_processor
        UpperCAmelCase_            =  prepare_img()
        UpperCAmelCase_            =  image_processor(images=lowercase__  ,							return_tensors='''pt'''  ).to(lowercase__  )

        # forward pass
        with torch.no_grad():
              UpperCAmelCase_            =  model(**lowercase__  )

        # verify the logits
        UpperCAmelCase_            =  torch.Size((1, 1000)  )
        self.assertEqual(outputs.logits.shape  ,							lowercase__  )

        UpperCAmelCase_            =  torch.tensor([-1.0266, 0.1912, -1.2861]  ).to(lowercase__  )

        self.assertTrue(torch.allclose(outputs.logits[0, :3]  ,							lowercase__  ,							atol=1e-4  )  )






  @slow
  @require_accelerate
  @require_torch_gpu
  def  lowerCAmelCase__ (      self			:       List[str]  )				->Dict:
        UpperCAmelCase_            =  DeiTModel.from_pretrained(
            '''facebook/deit-base-distilled-patch16-224'''  ,							torch_dtype=torch.floataa  ,							device_map='''auto'''  )
        UpperCAmelCase_            =  self.default_image_processor

        UpperCAmelCase_            =  prepare_img()
        UpperCAmelCase_            =  image_processor(images=lowercase__  ,							return_tensors='''pt'''  )
        UpperCAmelCase_            =  inputs.pixel_values.to(lowercase__  )

        # forward pass to make sure inference works in fp16
        with torch.no_grad():
              UpperCAmelCase_            =  model(lowercase__  )






'''simple docstring'''
import math
from typing import Dict, Iterable, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    is_torch_available,
    is_torch_tensor,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_torch_available():
      import torch

if is_vision_available():
      import PIL


lowercase__  :      Optional[int]        =					logging.get_logger(__name__)



def  __lowerCamelCase       (      _UpperCamelCase  :  np.ndarray							,    _UpperCamelCase  :  Union[int, Iterable[int]]							,    _UpperCamelCase  :  bool							,    _UpperCamelCase  :  int					):


      '''simple docstring'''


      def constraint_to_multiple_of(_UpperCamelCase  :  int							,    _UpperCamelCase  :  Tuple							,    _UpperCamelCase  :  Optional[int]=0							,    _UpperCamelCase  :  str=None					):
            UpperCAmelCase_            =  round(val / multiple					) * multiple

            if max_val is not None and x > max_val:
                  UpperCAmelCase_            =  math.floor(val / multiple					) * multiple

            if x < min_val:
                  UpperCAmelCase_            =  math.ceil(val / multiple					) * multiple

            return x

      UpperCAmelCase_            =  (output_size, output_size) if isinstance(_UpperCamelCase							,    _UpperCamelCase					) else output_size

      UpperCAmelCase_      ,		UpperCAmelCase_            =  get_image_size(_UpperCamelCase					)
      UpperCAmelCase_      ,		UpperCAmelCase_            =  output_size

      # determine new height and width
      UpperCAmelCase_            =  output_height / input_height
      UpperCAmelCase_            =  output_width / input_width

      if keep_aspect_ratio:
            # scale as little as possible
            if abs(1 - scale_width					) < abs(1 - scale_height					):
                  # fit width
                  UpperCAmelCase_            =  scale_width
            else:
                  # fit height
                  UpperCAmelCase_            =  scale_height

      UpperCAmelCase_            =  constraint_to_multiple_of(scale_height * input_height							,    multiple=_UpperCamelCase					)
      UpperCAmelCase_            =  constraint_to_multiple_of(scale_width * input_width							,    multiple=_UpperCamelCase					)

      return (new_height, new_width)







class lowerCamelCase							(	lowerCamelCase					):




  '''simple docstring'''



  lowerCAmelCase__										=	['''pixel_values''']






  def __init__(      self			:       Any  ,							UpperCAmelCase__			:       bool = True  ,							UpperCAmelCase__			:       Dict[str, int] = None  ,							UpperCAmelCase__			:       PILImageResampling = PILImageResampling.BILINEAR  ,							UpperCAmelCase__			:       bool = False  ,							UpperCAmelCase__			:       int = 1  ,							UpperCAmelCase__			:       bool = True  ,							UpperCAmelCase__			:       Union[int, float] = 1 / 255  ,							UpperCAmelCase__			:       bool = True  ,							UpperCAmelCase__			:       Optional[Union[float, List[float]]] = None  ,							UpperCAmelCase__			:       Optional[Union[float, List[float]]] = None  ,							**UpperCAmelCase__			:       str  ,							)				->None:
        super().__init__(**UpperCAmelCase__  )
        UpperCAmelCase_            =  size if size is not None else {'''height''': 384, '''width''': 384}
        UpperCAmelCase_            =  get_size_dict(UpperCAmelCase__  )
        UpperCAmelCase_            =  do_resize
        UpperCAmelCase_            =  size
        UpperCAmelCase_            =  keep_aspect_ratio
        UpperCAmelCase_            =  ensure_multiple_of
        UpperCAmelCase_            =  resample
        UpperCAmelCase_            =  do_rescale
        UpperCAmelCase_            =  rescale_factor
        UpperCAmelCase_            =  do_normalize
        UpperCAmelCase_            =  image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
        UpperCAmelCase_            =  image_std if image_std is not None else IMAGENET_STANDARD_STD






  def  lowerCAmelCase__ (      self			:       Union[str, Any]  ,							UpperCAmelCase__			:       np.ndarray  ,							UpperCAmelCase__			:       Dict[str, int]  ,							UpperCAmelCase__			:       bool = False  ,							UpperCAmelCase__			:       int = 1  ,							UpperCAmelCase__			:       PILImageResampling = PILImageResampling.BICUBIC  ,							UpperCAmelCase__			:       Optional[Union[str, ChannelDimension]] = None  ,							**UpperCAmelCase__			:       List[str]  ,							)				->np.ndarray:
        UpperCAmelCase_            =  get_size_dict(UpperCAmelCase__  )
        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()}"""  )
        UpperCAmelCase_            =  get_resize_output_image_size(
            UpperCAmelCase__  ,							output_size=(size['''height'''], size['''width'''])  ,							keep_aspect_ratio=UpperCAmelCase__  ,							multiple=UpperCAmelCase__  ,							)
        return resize(UpperCAmelCase__  ,							size=UpperCAmelCase__  ,							resample=UpperCAmelCase__  ,							data_format=UpperCAmelCase__  ,							**UpperCAmelCase__  )






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






  def  lowerCAmelCase__ (      self			:       List[Any]  ,							UpperCAmelCase__			:       np.ndarray  ,							UpperCAmelCase__			:       Union[float, List[float]]  ,							UpperCAmelCase__			:       Union[float, List[float]]  ,							UpperCAmelCase__			:       Optional[Union[str, ChannelDimension]] = None  ,							**UpperCAmelCase__			:       Optional[int]  ,							)				->np.ndarray:
        return normalize(UpperCAmelCase__  ,							mean=UpperCAmelCase__  ,							std=UpperCAmelCase__  ,							data_format=UpperCAmelCase__  ,							**UpperCAmelCase__  )






  def  lowerCAmelCase__ (      self			:       str  ,							UpperCAmelCase__			:       ImageInput  ,							UpperCAmelCase__			:       bool = None  ,							UpperCAmelCase__			:       int = None  ,							UpperCAmelCase__			:       bool = None  ,							UpperCAmelCase__			:       int = None  ,							UpperCAmelCase__			:       PILImageResampling = None  ,							UpperCAmelCase__			:       bool = None  ,							UpperCAmelCase__			:       float = None  ,							UpperCAmelCase__			:       bool = None  ,							UpperCAmelCase__			:       Optional[Union[float, List[float]]] = None  ,							UpperCAmelCase__			:       Optional[Union[float, List[float]]] = None  ,							UpperCAmelCase__			:       Optional[Union[str, TensorType]] = None  ,							UpperCAmelCase__			:       ChannelDimension = ChannelDimension.FIRST  ,							**UpperCAmelCase__			:       Any  ,							)				->PIL.Image.Image:
        UpperCAmelCase_            =  do_resize if do_resize is not None else self.do_resize
        UpperCAmelCase_            =  size if size is not None else self.size
        UpperCAmelCase_            =  get_size_dict(UpperCAmelCase__  )
        UpperCAmelCase_            =  keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
        UpperCAmelCase_            =  ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
        UpperCAmelCase_            =  resample if resample is not None else self.resample
        UpperCAmelCase_            =  do_rescale if do_rescale is not None else self.do_rescale
        UpperCAmelCase_            =  rescale_factor if rescale_factor is not None else self.rescale_factor
        UpperCAmelCase_            =  do_normalize if do_normalize is not None else self.do_normalize
        UpperCAmelCase_            =  image_mean if image_mean is not None else self.image_mean
        UpperCAmelCase_            =  image_std if image_std is not None else self.image_std

        UpperCAmelCase_            =  make_list_of_images(UpperCAmelCase__  )

        if not valid_images(UpperCAmelCase__  ):
              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 or resample is None:
              raise ValueError('''Size and resample 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_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.
        UpperCAmelCase_            =  [to_numpy_array(UpperCAmelCase__  ) for image in images]

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

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

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

        UpperCAmelCase_            =  [to_channel_dimension_format(UpperCAmelCase__  ,							UpperCAmelCase__  ) for image in images]

        UpperCAmelCase_            =  {'''pixel_values''': images}
        return BatchFeature(data=UpperCAmelCase__  ,							tensor_type=UpperCAmelCase__  )






  def  lowerCAmelCase__ (      self			:       List[str]  ,							UpperCAmelCase__			:       List[Any]  ,							UpperCAmelCase__			:       List[Tuple] = None  )				->Optional[Any]:
        UpperCAmelCase_            =  outputs.logits

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

              if is_torch_tensor(UpperCAmelCase__  ):
                    UpperCAmelCase_            =  target_sizes.numpy()

              UpperCAmelCase_            =  []

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

        return semantic_segmentation





