



"""simple docstring"""






import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, 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 MaskaFormerForUniversalSegmentation, MaskaFormerModel

				if is_vision_available():
								from transformers import MaskaFormerImageProcessor

if is_vision_available():
				from PIL import Image

class 						__lowerCAmelCase				:


					'''simple docstring'''


					def __init__(   self     ,							a     ,							a=2     ,							a=True     ,							a=False     ,							a=10     ,							a=3     ,							a=32 * 8     ,							a=32 * 8     ,							a=4     ,							a=64     ,							):




										"""simple docstring"""





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







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :Optional[Any]										=    floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
										    __lowercase )

										snake_case_    :Optional[int]										=    torch.ones([self.batch_size, self.min_size, self.max_size]     ,							device=__lowercase )

										snake_case_    :str										=    (
										    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]     ,							device=__lowercase ) > 0.5
										).float()
										snake_case_    :Optional[Any]										=    (torch.rand((self.batch_size, self.num_labels)     ,							device=__lowercase ) > 0.5).long()

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







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :Any										=    MaskaFormerConfig(
										    hidden_size=self.hidden_dim     ,							)
										snake_case_    :Dict										=    self.num_queries
										snake_case_    :str										=    self.num_labels

										snake_case_    :Optional[int]										=    [1, 1, 1, 1]
										snake_case_    :int										=    self.num_channels

										snake_case_    :str										=    64
										snake_case_    :Union[str, Any]										=    1_28
										snake_case_    :Dict										=    self.hidden_dim
										snake_case_    :Tuple										=    self.hidden_dim
										snake_case_    :Optional[int]										=    self.hidden_dim
										return config







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :List[Any]										=    self.prepare_config_and_inputs()
										snake_case_    :Union[str, Any]										=    {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
										return config, inputs_dict







					def 		_a			(   self     ,							a     ,							a ):




										"""simple docstring"""





										snake_case_    :List[Any]										=    output.encoder_hidden_states
										snake_case_    :int										=    output.pixel_decoder_hidden_states
										snake_case_    :List[Any]										=    output.transformer_decoder_hidden_states

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







					def 		_a			(   self     ,							a     ,							a     ,							a     ,							a=False ):




										"""simple docstring"""





										with torch.no_grad():
															snake_case_    :Union[str, Any]										=    MaskaFormerModel(config=__lowercase )
															model.to(__lowercase )
															model.eval()

															snake_case_    :Union[str, Any]										=    model(pixel_values=__lowercase     ,							pixel_mask=__lowercase )
															snake_case_    :Optional[int]										=    model(__lowercase     ,							output_hidden_states=__lowercase )

										self.parent.assertEqual(
										    output.transformer_decoder_last_hidden_state.shape     ,							(self.batch_size, self.num_queries, self.hidden_dim)     ,							)
										# 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(__lowercase     ,							__lowercase )







					def 		_a			(   self     ,							a     ,							a     ,							a     ,							a     ,							a ):




										"""simple docstring"""





										snake_case_    :Dict										=    MaskaFormerForUniversalSegmentation(config=__lowercase )
										model.to(__lowercase )
										model.eval()

										def comm_check_on_output(a ):
															# 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():
															snake_case_    :Optional[int]										=    model(pixel_values=__lowercase     ,							pixel_mask=__lowercase )
															snake_case_    :str										=    model(__lowercase )

															comm_check_on_output(__lowercase )

															snake_case_    :List[str]										=    model(
															    pixel_values=__lowercase     ,							pixel_mask=__lowercase     ,							mask_labels=__lowercase     ,							class_labels=__lowercase )

										comm_check_on_output(__lowercase )

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



@require_torch
class 						__lowerCAmelCase				(snake_case__       ,snake_case__       ,unittest.TestCase	):


					'''simple docstring'''


					a__          =  (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
					a__          =  {"""feature-extraction""": MaskaFormerModel} if is_torch_available() else {}

					a__          =  False
					a__          =  False
					a__          =  False
					a__          =  False







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :Dict										=    MaskaFormerModelTester(self )
										snake_case_    :List[Any]										=    ConfigTester(self     ,							config_class=__lowercase     ,							has_text_modality=__lowercase )







					def 		_a			(   self ):




										"""simple docstring"""





										self.config_tester.run_common_tests()







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :List[str]										=    self.model_tester.prepare_config_and_inputs_for_common()
										self.model_tester.create_and_check_maskaformer_model(__lowercase     ,							**__lowercase     ,							output_hidden_states=__lowercase )







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :Dict										=    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*__lowercase )







					@unittest.skip(reason="Mask2Former does not use inputs_embeds" )
					def 		_a			(   self ):




										"""simple docstring"""





										pass







					@unittest.skip(reason="Mask2Former does not have a get_input_embeddings method" )
					def 		_a			(   self ):




										"""simple docstring"""





										pass







					@unittest.skip(reason="Mask2Former is not a generative model" )
					def 		_a			(   self ):




										"""simple docstring"""





										pass







					@unittest.skip(reason="Mask2Former does not use token embeddings" )
					def 		_a			(   self ):




										"""simple docstring"""





										pass







					@require_torch_multi_gpu
					@unittest.skip(
					    reason="Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`" )
					def 		_a			(   self ):




										"""simple docstring"""





										pass







					@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
					def 		_a			(   self ):




										"""simple docstring"""





										pass







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :int										=    self.model_tester.prepare_config_and_inputs_for_common()

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

															snake_case_    :Any										=    ['''pixel_values''']
															self.assertListEqual(arg_names[:1]     ,							__lowercase )







					@slow
					def 		_a			(   self ):




										"""simple docstring"""





										for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
															snake_case_    :List[Any]										=    MaskaFormerModel.from_pretrained(__lowercase )
															self.assertIsNotNone(__lowercase )







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :str										=    (self.model_tester.min_size,) * 2
										snake_case_    :str										=    {
										    '''pixel_values''': torch.randn((2, 3, *size)     ,							device=__lowercase ),
										    '''mask_labels''': torch.randn((2, 10, *size)     ,							device=__lowercase ),
										    '''class_labels''': torch.zeros(2     ,							10     ,							device=__lowercase ).long(),
										}
										snake_case_    :Any										=    self.model_tester.get_config()

										snake_case_    :Optional[Any]										=    MaskaFormerForUniversalSegmentation(__lowercase ).to(__lowercase )
										snake_case_    :Any										=    model(**__lowercase )
										self.assertTrue(outputs.loss is not None )







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :List[str]										=    self.model_tester.prepare_config_and_inputs_for_common()
										self.model_tester.create_and_check_maskaformer_model(__lowercase     ,							**__lowercase     ,							output_hidden_states=__lowercase )







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :Dict										=    self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
															snake_case_    :Optional[int]										=    model_class(__lowercase ).to(__lowercase )
															snake_case_    :Tuple										=    model(**__lowercase     ,							output_attentions=__lowercase )
															self.assertTrue(outputs.attentions is not None )







					def 		_a			(   self ):




										"""simple docstring"""





										if not self.model_tester.is_training:
															return

										snake_case_    :str										=    self.all_model_classes[1]
										snake_case_    :str										=    self.model_tester.prepare_config_and_inputs()

										snake_case_    :int										=    model_class(__lowercase )
										model.to(__lowercase )
										model.train()

										snake_case_    :Union[str, Any]										=    model(__lowercase     ,							mask_labels=__lowercase     ,							class_labels=__lowercase ).loss
										loss.backward()







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :List[Any]										=    self.all_model_classes[1]
										snake_case_    :Dict										=    self.model_tester.prepare_config_and_inputs()
										snake_case_    :List[Any]										=    True
										snake_case_    :Union[str, Any]										=    True

										snake_case_    :List[Any]										=    model_class(__lowercase ).to(__lowercase )
										model.train()

										snake_case_    :Dict										=    model(__lowercase     ,							mask_labels=__lowercase     ,							class_labels=__lowercase )

										snake_case_    :str										=    outputs.encoder_hidden_states[0]
										encoder_hidden_states.retain_grad()

										snake_case_    :Optional[int]										=    outputs.pixel_decoder_hidden_states[0]
										pixel_decoder_hidden_states.retain_grad()

										snake_case_    :List[str]										=    outputs.transformer_decoder_hidden_states[0]
										transformer_decoder_hidden_states.retain_grad()

										snake_case_    :Tuple										=    outputs.attentions[0]
										attentions.retain_grad()

										outputs.loss.backward(retain_graph=__lowercase )

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



__UpperCAmelCase   :   List[Any]        =       1E-4
def   A   (      ):




					"""simple docstring"""
					snake_case_    :Any										=    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
					return image

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


					'''simple docstring'''


					@cached_property
					def 		_a			(   self ):




										"""simple docstring"""





										return "facebook/mask2former-swin-small-coco-instance"







					@cached_property
					def 		_a			(   self ):




										"""simple docstring"""





										return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :Dict										=    MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(__lowercase )
										snake_case_    :int										=    self.default_image_processor
										snake_case_    :List[Any]										=    prepare_img()
										snake_case_    :List[str]										=    image_processor(__lowercase     ,							return_tensors="pt" ).to(__lowercase )
										snake_case_    :List[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(__lowercase     ,							(1, 3, 3_84, 3_84) )

										with torch.no_grad():
															snake_case_    :Optional[Any]										=    model(**__lowercase )

										snake_case_    :Union[str, Any]										=    torch.tensor(
										    [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(__lowercase )
										self.assertTrue(
										    torch.allclose(
										        outputs.encoder_last_hidden_state[0, 0, :3, :3]     ,							__lowercase     ,							atol=__lowercase ) )

										snake_case_    :List[Any]										=    torch.tensor(
										    [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(__lowercase )
										self.assertTrue(
										    torch.allclose(
										        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]     ,							__lowercase     ,							atol=__lowercase ) )

										snake_case_    :int										=    torch.tensor(
										    [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(__lowercase )
										self.assertTrue(
										    torch.allclose(
										        outputs.transformer_decoder_last_hidden_state[0, :3, :3]     ,							__lowercase     ,							atol=__lowercase ) )







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :Tuple										=    MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__lowercase ).eval()
										snake_case_    :Union[str, Any]										=    self.default_image_processor
										snake_case_    :Union[str, Any]										=    prepare_img()
										snake_case_    :Any										=    image_processor(__lowercase     ,							return_tensors="pt" ).to(__lowercase )
										snake_case_    :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(__lowercase     ,							(1, 3, 3_84, 3_84) )

										with torch.no_grad():
															snake_case_    :str										=    model(**__lowercase )
										# masks_queries_logits
										snake_case_    :Union[str, Any]										=    outputs.masks_queries_logits
										self.assertEqual(
										    masks_queries_logits.shape     ,							(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) )
										snake_case_    :List[Any]										=    [
										    [-8.7839, -9.0056, -8.8121],
										    [-7.4104, -7.0313, -6.5401],
										    [-6.6105, -6.3427, -6.4675],
										]
										snake_case_    :Optional[int]										=    torch.tensor(__lowercase ).to(__lowercase )
										self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]     ,							__lowercase     ,							atol=__lowercase ) )
										# class_queries_logits
										snake_case_    :List[str]										=    outputs.class_queries_logits
										self.assertEqual(class_queries_logits.shape     ,							(1, model.config.num_queries, model.config.num_labels + 1) )
										snake_case_    :Tuple										=    torch.tensor(
										    [
										        [1.8324, -8.0835, -4.1922],
										        [0.8450, -9.0050, -3.6053],
										        [0.3045, -7.7293, -3.0275],
										    ] ).to(__lowercase )
										self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]     ,							__lowercase     ,							atol=__lowercase ) )







					def 		_a			(   self ):




										"""simple docstring"""





										snake_case_    :Optional[Any]										=    MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__lowercase ).eval()
										snake_case_    :List[str]										=    self.default_image_processor

										snake_case_    :str										=    image_processor(
										    [np.zeros((3, 8_00, 13_33) ), np.zeros((3, 8_00, 13_33) )]     ,							segmentation_maps=[np.zeros((3_84, 3_84) ).astype(np.floataa ), np.zeros((3_84, 3_84) ).astype(np.floataa )]     ,							return_tensors="pt"     ,							)

										snake_case_    :Optional[int]										=    inputs['''pixel_values'''].to(__lowercase )
										snake_case_    :Tuple										=    [el.to(__lowercase ) for el in inputs['''mask_labels''']]
										snake_case_    :Tuple										=    [el.to(__lowercase ) for el in inputs['''class_labels''']]

										with torch.no_grad():
															snake_case_    :str										=    model(**__lowercase )

										self.assertTrue(outputs.loss is not None )








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


_UpperCamelCase					      =   logging.get_logger(__name__)
class 		SCREAMING_SNAKE_CASE_				(     snake_case__ ):
				"""simple docstring"""
				__snake_case :							Optional[int]									=		["""pixel_values"""]




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




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




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




				def        __lowercase	(  self	:str    ,     __lowercase	:np.ndarray    ,     __lowercase	:float    ,     __lowercase	:Optional[Union[str, ChannelDimension]] = None    ,     **__lowercase	:str      ):
											return rescale(__lowercase    ,     scale=__lowercase    ,     data_format=__lowercase    ,     **__lowercase      )




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




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

											__lowerCamelCase   :   int       =make_list_of_images(__lowercase      )

											if not valid_images(__lowercase      ):
																		raise ValueError(
																		    '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
																		    '''torch.Tensor, tf.Tensor or jax.ndarray.'''      )

											if do_resize and size is None:
																		raise ValueError('''Size must be specified if do_resize is True.'''      )

											if do_center_crop and crop_size is None:
																		raise ValueError('''Crop size must be specified if do_center_crop is True.'''      )

											if do_rescale and rescale_factor is None:
																		raise ValueError('''Rescale factor must be specified if do_rescale is True.'''      )

											if do_normalize and (image_mean is None or image_std is None):
																		raise ValueError('''Image mean and std must be specified if do_normalize is True.'''      )

											# All transformations expect numpy arrays.
											__lowerCamelCase   :   int       =[to_numpy_array(__lowercase      ) for image in images]

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

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

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

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

											__lowerCamelCase   :   List[str]       =[to_channel_dimension_format(__lowercase    ,     __lowercase      ) for image in images]

											__lowerCamelCase   :   Union[str, Any]       ={'''pixel_values''': images}
											return BatchFeature(data=__lowercase    ,     tensor_type=__lowercase      )




				def        __lowercase	(  self	:Dict    ,     __lowercase	:Dict    ,     __lowercase	:List[Tuple] = None      ):
											__lowerCamelCase   :   Dict       =outputs.logits

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

																		if is_torch_tensor(__lowercase      ):
																									__lowerCamelCase   :   Optional[int]       =target_sizes.numpy()

																		__lowerCamelCase   :   List[Any]       =[]

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

											return semantic_segmentation




