




import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel

 if is_vision_available():
  from transformers import MaskFormerImageProcessor

if is_vision_available():
 from PIL import Image
class 		_A   :






  def __init__(    self						:      Union[str, Any] ,		_A						:      str ,		_A						:      Optional[Any]=2 ,		_A						:      str=True ,		_A						:      int=False ,		_A						:      Optional[Any]=10 ,		_A						:      Optional[int]=3 ,		_A						:      str=32 * 4 ,		_A						:      Optional[Any]=32 * 6 ,		_A						:      Optional[Any]=4 ,		_A						:      Optional[Any]=32 ,		)						->       List[Any]:






       """simple docstring"""







       lowercase   :  int        =					parent
       lowercase   :  List[str]        =					batch_size
       lowercase   :  Optional[Any]        =					is_training
       lowercase   :  List[Any]        =					use_auxiliary_loss
       lowercase   :  Dict        =					num_queries
       lowercase   :  Union[str, Any]        =					num_channels
       lowercase   :  Optional[int]        =					min_size
       lowercase   :  List[Any]        =					max_size
       lowercase   :  str        =					num_labels
       lowercase   :  Optional[int]        =					mask_feature_size






  def    __a     (    self						:      Dict )						->       Tuple:






       """simple docstring"""







       lowercase   :  Dict        =					floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
           _A )

       lowercase   :  Union[str, Any]        =					torch.ones([self.batch_size, self.min_size, self.max_size] ,		device=_A )

       lowercase   :  Optional[int]        =					(
           torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,		device=_A ) > 0.5
       ).float()
       lowercase   :  Dict        =					(torch.rand((self.batch_size, self.num_labels) ,		device=_A ) > 0.5).long()

       lowercase   :  Optional[int]        =					self.get_config()
       return config, pixel_values, pixel_mask, mask_labels, class_labels






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






       """simple docstring"""







       return MaskFormerConfig.from_backbone_and_decoder_configs(
           backbone_config=SwinConfig(
               depths=[1, 1, 1, 1] ,		) ,		decoder_config=DetrConfig(
               decoder_ffn_dim=128 ,		num_queries=self.num_queries ,		decoder_attention_heads=2 ,		d_model=self.mask_feature_size ,		) ,		mask_feature_size=self.mask_feature_size ,		fpn_feature_size=self.mask_feature_size ,		num_channels=self.num_channels ,		num_labels=self.num_labels ,		)






  def    __a     (    self						:      int )						->       Tuple:






       """simple docstring"""







       lowercase   :  Union[str, Any]        =					self.prepare_config_and_inputs()
       lowercase   :  Dict        =					{"pixel_values": pixel_values, "pixel_mask": pixel_mask}
       return config, inputs_dict






  def    __a     (    self						:      Any ,		_A						:      Optional[int] ,		_A						:      Union[str, Any] )						->       Tuple:






       """simple docstring"""







       lowercase   :  Tuple        =					output.encoder_hidden_states
       lowercase   :  int        =					output.pixel_decoder_hidden_states
       lowercase   :  Optional[Any]        =					output.transformer_decoder_hidden_states

       self.parent.assertTrue(len(_A ) ,		len(config.backbone_config.depths ) )
       self.parent.assertTrue(len(_A ) ,		len(config.backbone_config.depths ) )
       self.parent.assertTrue(len(_A ) ,		config.decoder_config.decoder_layers )






  def    __a     (    self						:      Any ,		_A						:      Any ,		_A						:      Dict ,		_A						:      List[Any] ,		_A						:      List[str]=False )						->       int:






       """simple docstring"""







       with torch.no_grad():
            lowercase   :  Optional[Any]        =					MaskFormerModel(config=_A )
            model.to(_A )
            model.eval()

            lowercase   :  Optional[Any]        =					model(pixel_values=_A ,		pixel_mask=_A )
            lowercase   :  List[Any]        =					model(_A ,		output_hidden_states=_A )
       # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
       # encoder and pixel decoder
       self.parent.assertEqual(
           output.transformer_decoder_last_hidden_state.shape ,		(self.batch_size, self.num_queries, self.mask_feature_size) ,		)
       # let's ensure the other two hidden state exists
       self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
       self.parent.assertTrue(output.encoder_last_hidden_state is not None )

       if output_hidden_states:
            self.check_output_hidden_state(_A ,		_A )






  def    __a     (    self						:      Optional[Any] ,		_A						:      Optional[int] ,		_A						:      Union[str, Any] ,		_A						:      Optional[Any] ,		_A						:      Tuple ,		_A						:      Union[str, Any] )						->       Any:






       """simple docstring"""







       lowercase   :  List[Any]        =					MaskFormerForInstanceSegmentation(config=_A )
       model.to(_A )
       model.eval()

       def comm_check_on_output(_A						:      Dict ):
            # let's still check that all the required stuff is there
            self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
            self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
            self.parent.assertTrue(result.encoder_last_hidden_state is not None )
            # okay, now we need to check the logits shape
            # due to the encoder compression, masks have a //4 spatial size
            self.parent.assertEqual(
                result.masks_queries_logits.shape ,		(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,		)
            # + 1 for null class
            self.parent.assertEqual(
                result.class_queries_logits.shape ,		(self.batch_size, self.num_queries, self.num_labels + 1) )

       with torch.no_grad():
            lowercase   :  Optional[Any]        =					model(pixel_values=_A ,		pixel_mask=_A )
            lowercase   :  Dict        =					model(_A )

            comm_check_on_output(_A )

            lowercase   :  Dict        =					model(
                pixel_values=_A ,		pixel_mask=_A ,		mask_labels=_A ,		class_labels=_A )

       comm_check_on_output(_A )

       self.parent.assertTrue(result.loss is not None )
       self.parent.assertEqual(result.loss.shape ,		torch.Size([1] ) )


@require_torch
class 		_A   (    __snake_case     ,  __snake_case     ,  unittest.TestCase ):
  _UpperCamelCase  :     Tuple					=     (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
  _UpperCamelCase  :     List[str]					=     (
      {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation}
      if is_torch_available()
      else {}
  )

  _UpperCamelCase  :     List[str]					=     False
  _UpperCamelCase  :     Dict					=     False
  _UpperCamelCase  :     Any					=     False
  _UpperCamelCase  :     str					=     False






  def    __a     (    self						:      Dict )						->       List[Any]:






       """simple docstring"""







       lowercase   :  Optional[Any]        =					MaskFormerModelTester(self )
       lowercase   :  Optional[int]        =					ConfigTester(self ,		config_class=_A ,		has_text_modality=_A )






  def    __a     (    self						:      List[str] )						->       Optional[Any]:






       """simple docstring"""







       self.config_tester.run_common_tests()






  def    __a     (    self						:      List[str] )						->       Union[str, Any]:






       """simple docstring"""







       lowercase   :  Union[str, Any]        =					self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.create_and_check_maskformer_model(_A ,		**_A ,		output_hidden_states=_A )






  def    __a     (    self						:      Tuple )						->       List[str]:






       """simple docstring"""







       lowercase   :  List[str]        =					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_A )






  @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' )
  def    __a     (    self						:      Dict )						->       int:






       """simple docstring"""







       pass






  @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' )
  def    __a     (    self						:      Optional[int] )						->       Any:






       """simple docstring"""







       pass






  @unittest.skip(reason='''MaskFormer is not a generative model''' )
  def    __a     (    self						:      Optional[Any] )						->       Any:






       """simple docstring"""







       pass






  @unittest.skip(reason='''MaskFormer does not use token embeddings''' )
  def    __a     (    self						:      Dict )						->       int:






       """simple docstring"""







       pass






  @require_torch_multi_gpu
  @unittest.skip(
      reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' )
  def    __a     (    self						:      Optional[Any] )						->       Optional[int]:






       """simple docstring"""







       pass






  @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
  def    __a     (    self						:      Optional[int] )						->       List[Any]:






       """simple docstring"""







       pass






  def    __a     (    self						:      Any )						->       Any:






       """simple docstring"""







       lowercase   :  Optional[int]        =					self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            lowercase   :  List[str]        =					model_class(_A )
            lowercase   :  Union[str, Any]        =					inspect.signature(model.forward )
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            lowercase   :  Any        =					[*signature.parameters.keys()]

            lowercase   :  List[str]        =					["pixel_values"]
            self.assertListEqual(arg_names[:1] ,		_A )






  @slow
  def    __a     (    self						:      str )						->       List[Any]:






       """simple docstring"""







       for model_name in ["facebook/maskformer-swin-small-coco"]:
            lowercase   :  List[Any]        =					MaskFormerModel.from_pretrained(_A )
            self.assertIsNotNone(_A )






  def    __a     (    self						:      Tuple )						->       Dict:






       """simple docstring"""







       lowercase   :  Optional[int]        =					(self.model_tester.min_size,) * 2
       lowercase   :  List[str]        =					{
           "pixel_values": torch.randn((2, 3, *size) ,		device=_A ),
           "mask_labels": torch.randn((2, 10, *size) ,		device=_A ),
           "class_labels": torch.zeros(2 ,		10 ,		device=_A ).long(),
       }

       lowercase   :  Tuple        =					MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_A )
       lowercase   :  Any        =					model(**_A )
       self.assertTrue(outputs.loss is not None )






  def    __a     (    self						:      Optional[Any] )						->       str:






       """simple docstring"""







       lowercase   :  Optional[Any]        =					self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.create_and_check_maskformer_model(_A ,		**_A ,		output_hidden_states=_A )






  def    __a     (    self						:      Optional[int] )						->       Any:






       """simple docstring"""







       lowercase   :  int        =					self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            lowercase   :  List[Any]        =					model_class(_A ).to(_A )
            lowercase   :  Tuple        =					model(**_A ,		output_attentions=_A )
            self.assertTrue(outputs.attentions is not None )






  def    __a     (    self						:      Union[str, Any] )						->       str:






       """simple docstring"""







       if not self.model_tester.is_training:
            return
       # only MaskFormerForInstanceSegmentation has the loss
       lowercase   :  str        =					self.all_model_classes[1]
       lowercase   :  Any        =					self.model_tester.prepare_config_and_inputs()

       lowercase   :  Dict        =					model_class(_A )
       model.to(_A )
       model.train()

       lowercase   :  List[Any]        =					model(_A ,		mask_labels=_A ,		class_labels=_A ).loss
       loss.backward()






  def    __a     (    self						:      List[str] )						->       int:






       """simple docstring"""







       lowercase   :  List[Any]        =					self.all_model_classes[1]
       lowercase   :  List[Any]        =					self.model_tester.prepare_config_and_inputs()
       lowercase   :  str        =					True
       lowercase   :  int        =					True

       lowercase   :  Optional[int]        =					model_class(_A )
       model.to(_A )
       model.train()

       lowercase   :  List[Any]        =					model(_A ,		mask_labels=_A ,		class_labels=_A )

       lowercase   :  Dict        =					outputs.encoder_hidden_states[0]
       encoder_hidden_states.retain_grad()

       lowercase   :  List[str]        =					outputs.pixel_decoder_hidden_states[0]
       pixel_decoder_hidden_states.retain_grad()
       # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
       lowercase   :  Optional[int]        =					outputs.transformer_decoder_hidden_states[0]
       transformer_decoder_hidden_states.retain_grad()

       lowercase   :  str        =					outputs.attentions[0]
       attentions.retain_grad()

       outputs.loss.backward(retain_graph=_A )

       self.assertIsNotNone(encoder_hidden_states.grad )
       self.assertIsNotNone(pixel_decoder_hidden_states.grad )
       self.assertIsNotNone(transformer_decoder_hidden_states.grad )
       self.assertIsNotNone(attentions.grad )


lowerCAmelCase_						 =					1E-4






def    snake_case(							)					->				Optional[int]:





     '''simple docstring'''


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



@require_vision
@slow
class 		_A   (    unittest.TestCase ):






  @cached_property
  def    __a     (    self						:      Tuple )						->       str:






       """simple docstring"""







       return (
           MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' )
           if is_vision_available()
           else None
       )






  def    __a     (    self						:      Tuple )						->       str:






       """simple docstring"""







       lowercase   :  List[str]        =					MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_A )
       lowercase   :  Optional[Any]        =					self.default_image_processor
       lowercase   :  List[Any]        =					prepare_img()
       lowercase   :  List[Any]        =					image_processor(_A ,		return_tensors='''pt''' ).to(_A )
       lowercase   :  Tuple        =					inputs["pixel_values"].shape
       # check size is divisible by 32
       self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
       # check size
       self.assertEqual(_A ,		(1, 3, 800, 1_088) )

       with torch.no_grad():
            lowercase   :  int        =					model(**_A )

       lowercase   :  Union[str, Any]        =					torch.tensor(
           [[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]] ).to(_A )
       self.assertTrue(
           torch.allclose(
               outputs.encoder_last_hidden_state[0, 0, :3, :3] ,		_A ,		atol=_A ) )

       lowercase   :  List[Any]        =					torch.tensor(
           [[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]] ).to(_A )
       self.assertTrue(
           torch.allclose(
               outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,		_A ,		atol=_A ) )

       lowercase   :  int        =					torch.tensor(
           [[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]] ).to(_A )
       self.assertTrue(
           torch.allclose(
               outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,		_A ,		atol=_A ) )






  def    __a     (    self						:      Optional[int] )						->       Tuple:






       """simple docstring"""







       lowercase   :  int        =					(
           MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
           .to(_A )
           .eval()
       )
       lowercase   :  List[str]        =					self.default_image_processor
       lowercase   :  List[str]        =					prepare_img()
       lowercase   :  List[str]        =					image_processor(_A ,		return_tensors='''pt''' ).to(_A )
       lowercase   :  int        =					inputs["pixel_values"].shape
       # check size is divisible by 32
       self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
       # check size
       self.assertEqual(_A ,		(1, 3, 800, 1_088) )

       with torch.no_grad():
            lowercase   :  Dict        =					model(**_A )
       # masks_queries_logits
       lowercase   :  Tuple        =					outputs.masks_queries_logits
       self.assertEqual(
           masks_queries_logits.shape ,		(1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ,		)
       lowercase   :  List[Any]        =					[
           [-1.3_737_124, -1.7_724_937, -1.9_364_233],
           [-1.5_977_281, -1.9_867_939, -2.1_523_695],
           [-1.5_795_398, -1.9_269_832, -2.093_942],
       ]
       lowercase   :  Any        =					torch.tensor(_A ).to(_A )
       self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,		_A ,		atol=_A ) )
       # class_queries_logits
       lowercase   :  Union[str, Any]        =					outputs.class_queries_logits
       self.assertEqual(
           class_queries_logits.shape ,		(1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
       lowercase   :  Optional[int]        =					torch.tensor(
           [
               [1.6_512E00, -5.2_572E00, -3.3_519E00],
               [3.6_169E-02, -5.9_025E00, -2.9_313E00],
               [1.0_766E-04, -7.7_630E00, -5.1_263E00],
           ] ).to(_A )
       self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,		_A ,		atol=_A ) )






  def    __a     (    self						:      Optional[int] )						->       Optional[Any]:






       """simple docstring"""







       lowercase   :  List[Any]        =					(
           MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' )
           .to(_A )
           .eval()
       )
       lowercase   :  str        =					self.default_image_processor
       lowercase   :  str        =					prepare_img()
       lowercase   :  Any        =					image_processor(_A ,		return_tensors='''pt''' ).to(_A )
       lowercase   :  str        =					inputs["pixel_values"].shape
       # check size is divisible by 32
       self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
       # check size
       self.assertEqual(_A ,		(1, 3, 800, 1_088) )

       with torch.no_grad():
            lowercase   :  str        =					model(**_A )
       # masks_queries_logits
       lowercase   :  Union[str, Any]        =					outputs.masks_queries_logits
       self.assertEqual(
           masks_queries_logits.shape ,		(1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ,		)
       lowercase   :  Optional[Any]        =					[[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
       lowercase   :  int        =					torch.tensor(_A ).to(_A )
       self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,		_A ,		atol=_A ) )
       # class_queries_logits
       lowercase   :  Dict        =					outputs.class_queries_logits
       self.assertEqual(
           class_queries_logits.shape ,		(1, model.config.decoder_config.num_queries, model.config.num_labels + 1) )
       lowercase   :  Optional[Any]        =					torch.tensor(
           [[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]] ).to(_A )
       self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,		_A ,		atol=_A ) )






  def    __a     (    self						:      str )						->       List[Any]:






       """simple docstring"""







       lowercase   :  List[str]        =					(
           MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' )
           .to(_A )
           .eval()
       )
       lowercase   :  Union[str, Any]        =					self.default_image_processor

       lowercase   :  Optional[int]        =					image_processor(
           [np.zeros((3, 800, 1_333) ), np.zeros((3, 800, 1_333) )] ,		segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] ,		return_tensors='''pt''' ,		)

       lowercase   :  Optional[Any]        =					inputs["pixel_values"].to(_A )
       lowercase   :  Optional[Any]        =					[el.to(_A ) for el in inputs["mask_labels"]]
       lowercase   :  Any        =					[el.to(_A ) for el in inputs["class_labels"]]

       with torch.no_grad():
            lowercase   :  str        =					model(**_A )

       self.assertTrue(outputs.loss is not None )

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


UpperCamelCase_						:     Tuple	       =							logging.get_logger(__name__)




class   __lowercase						(						__snake_case       ):
	_A       =   ["pixel_values"]






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






	def       _a(self				: Tuple      ,	snake_case				: np.ndarray      ,	snake_case				: Dict[str, int]      ,	snake_case				: PILImageResampling = PILImageResampling.BICUBIC      ,	snake_case				: Optional[Union[str, ChannelDimension]] = None      ,	**snake_case				: int      ,	) ->			np.ndarray:
							_lowercase       :	Union[str, Any]           =   get_size_dict(snake_case      ,	default_to_square=snake_case    )
							if "shortest_edge" not in size:
													raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"""    )
							_lowercase       :	int           =   get_resize_output_image_size(snake_case      ,	size=size["shortest_edge"]      ,	default_to_square=snake_case    )
							return resize(snake_case      ,	size=snake_case      ,	resample=snake_case      ,	data_format=snake_case      ,	**snake_case    )






	def       _a(self				: str      ,	snake_case				: np.ndarray      ,	snake_case				: Dict[str, int]      ,	snake_case				: Optional[Union[str, ChannelDimension]] = None      ,	**snake_case				: Union[str, Any]      ,	) ->			np.ndarray:
							_lowercase       :	Union[str, Any]           =   get_size_dict(snake_case    )
							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(snake_case      ,	size=(size["height"], size["width"])      ,	data_format=snake_case      ,	**snake_case    )






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






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






	def       _a(self				: Optional[int]      ,	snake_case				: ImageInput      ,	snake_case				: Optional[bool] = None      ,	snake_case				: Dict[str, int] = None      ,	snake_case				: PILImageResampling = None      ,	snake_case				: bool = None      ,	snake_case				: Dict[str, int] = None      ,	snake_case				: Optional[bool] = None      ,	snake_case				: Optional[float] = None      ,	snake_case				: Optional[bool] = None      ,	snake_case				: Optional[Union[float, List[float]]] = None      ,	snake_case				: Optional[Union[float, List[float]]] = None      ,	snake_case				: Optional[Union[str, TensorType]] = None      ,	snake_case				: Union[str, ChannelDimension] = ChannelDimension.FIRST      ,	**snake_case				: Tuple      ,	) ->			Union[str, Any]:
							_lowercase       :	Any           =   do_resize if do_resize is not None else self.do_resize
							_lowercase       :	List[str]           =   size if size is not None else self.size
							_lowercase       :	Optional[int]           =   get_size_dict(snake_case      ,	default_to_square=snake_case    )
							_lowercase       :	Tuple           =   resample if resample is not None else self.resample
							_lowercase       :	List[Any]           =   do_center_crop if do_center_crop is not None else self.do_center_crop
							_lowercase       :	int           =   crop_size if crop_size is not None else self.crop_size
							_lowercase       :	Dict           =   get_size_dict(snake_case      ,	param_name="crop_size"    )
							_lowercase       :	Dict           =   do_rescale if do_rescale is not None else self.do_rescale
							_lowercase       :	List[Any]           =   rescale_factor if rescale_factor is not None else self.rescale_factor
							_lowercase       :	Union[str, Any]           =   do_normalize if do_normalize is not None else self.do_normalize
							_lowercase       :	Dict           =   image_mean if image_mean is not None else self.image_mean
							_lowercase       :	Optional[Any]           =   image_std if image_std is not None else self.image_std

							_lowercase       :	int           =   make_list_of_images(snake_case    )

							if not valid_images(snake_case    ):
													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.
							_lowercase       :	Tuple           =   [to_numpy_array(snake_case    ) for image in images]

							if do_resize:
													_lowercase       :	List[str]           =   [self.resize(image=snake_case      ,	size=snake_case      ,	resample=snake_case    ) for image in images]

							if do_center_crop:
													_lowercase       :	List[str]           =   [self.center_crop(image=snake_case      ,	size=snake_case    ) for image in images]

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

							if do_normalize:
													_lowercase       :	Optional[Any]           =   [self.normalize(image=snake_case      ,	mean=snake_case      ,	std=snake_case    ) for image in images]

							_lowercase       :	Any           =   [to_channel_dimension_format(snake_case      ,	snake_case    ) for image in images]

							_lowercase       :	Optional[Any]           =   {"pixel_values": images}
							return BatchFeature(data=snake_case      ,	tensor_type=snake_case    )






	def       _a(self				: Dict      ,	snake_case				: List[str]      ,	snake_case				: List[Tuple] = None    ) ->			Optional[Any]:
							_lowercase       :	Dict           =   outputs.logits

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

													if is_torch_tensor(snake_case    ):
																			_lowercase       :	Dict           =   target_sizes.numpy()

													_lowercase       :	Tuple           =   []

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

							return semantic_segmentation




