



import unittest
from typing import Dict, List, Optional, Union

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
						import torch

if is_vision_available():
						from PIL import Image

						from transformers import BridgeTowerImageProcessor



class 				__snake_case						(     unittest.TestCase						):




							def __init__(       self     :       List[str]				,				A_     :       Dict				,				A_     :       bool = True				,				A_     :       Dict[str, int] = None				,				A_     :       int = 3_2				,				A_     :       bool = True				,				A_     :       Union[int, float] = 1 / 2_5_5				,				A_     :       bool = True				,				A_     :       bool = True				,				A_     :       Optional[Union[float, List[float]]] = [0.4814_5466, 0.457_8275, 0.4082_1073]				,				A_     :       Optional[Union[float, List[float]]] = [0.2686_2954, 0.2613_0258, 0.2757_7711]				,				A_     :       bool = True				,				A_     :       List[str]=7				,				A_     :       Any=3_0				,				A_     :       Dict=4_0_0				,				A_     :       str=3				,				):
									lowerCAmelCase_			:     Optional[int]									= parent
									lowerCAmelCase_			:     List[Any]									= do_resize
									lowerCAmelCase_			:     Dict									= size if size is not None else {'''shortest_edge''': 2_8_8}
									lowerCAmelCase_			:     int									= size_divisor
									lowerCAmelCase_			:     List[str]									= do_rescale
									lowerCAmelCase_			:     List[Any]									= rescale_factor
									lowerCAmelCase_			:     List[Any]									= do_normalize
									lowerCAmelCase_			:     Optional[Any]									= do_center_crop
									lowerCAmelCase_			:     Optional[Any]									= image_mean
									lowerCAmelCase_			:     Dict									= image_std
									lowerCAmelCase_			:     List[Any]									= do_pad
									lowerCAmelCase_			:     List[Any]									= batch_size
									lowerCAmelCase_			:     Optional[int]									= num_channels
									lowerCAmelCase_			:     Any									= min_resolution
									lowerCAmelCase_			:     Optional[int]									= max_resolution




							def    UpperCAmelCase__			(       self     :       int):
									return {
									    "image_mean": self.image_mean,
									    "image_std": self.image_std,
									    "do_normalize": self.do_normalize,
									    "do_resize": self.do_resize,
									    "size": self.size,
									    "size_divisor": self.size_divisor,
									}







							def    UpperCAmelCase__			(       self     :       Dict				,				A_     :       Tuple				,				A_     :       str=False):
									if not batched:
											lowerCAmelCase_			:     Optional[int]									= self.size['''shortest_edge''']
											lowerCAmelCase_			:     List[str]									= image_inputs[0]
											if isinstance(A_				,				Image.Image):
													lowerCAmelCase_					,  lowerCAmelCase_			:     str									= image.size
											else:
													lowerCAmelCase_					,  lowerCAmelCase_			:     Tuple									= image.shape[1], image.shape[2]
											lowerCAmelCase_			:     str									= size / min(A_				,				A_)
											if h < w:
													lowerCAmelCase_					,  lowerCAmelCase_			:     Union[str, Any]									= size, scale * w
											else:
													lowerCAmelCase_					,  lowerCAmelCase_			:     Dict									= scale * h, size

											lowerCAmelCase_			:     Union[str, Any]									= int((1_3_3_3 / 8_0_0) * size)
											if max(A_				,				A_) > max_size:
													lowerCAmelCase_			:     Tuple									= max_size / max(A_				,				A_)
													lowerCAmelCase_			:     int									= newh * scale
													lowerCAmelCase_			:     int									= neww * scale

											lowerCAmelCase_					,  lowerCAmelCase_			:     List[Any]									= int(newh + 0.5), int(neww + 0.5)
											lowerCAmelCase_					,  lowerCAmelCase_			:     Optional[int]									= (
											    newh // self.size_divisor * self.size_divisor,
											    neww // self.size_divisor * self.size_divisor,
											)

									else:
											lowerCAmelCase_			:     Any									= []
											for image in image_inputs:
													lowerCAmelCase_					,  lowerCAmelCase_			:     int									= self.get_expected_values([image])
													expected_values.append((expected_height, expected_width))
											lowerCAmelCase_			:     List[str]									= max(A_				,				key=lambda A_: item[0])[0]
											lowerCAmelCase_			:     List[str]									= max(A_				,				key=lambda A_: item[1])[1]

									return expected_height, expected_width





@require_torch
@require_vision
class 				__snake_case						(     UpperCamelCase_						,unittest.TestCase						):
							_a			      = BridgeTowerImageProcessor if is_vision_available() else None




							def    UpperCAmelCase__			(       self     :       List[str]):
									lowerCAmelCase_			:     Tuple									= BridgeTowerImageProcessingTester(self)




							@property
							def    UpperCAmelCase__			(       self     :       str):
									return self.image_processor_tester.prepare_image_processor_dict()




							def    UpperCAmelCase__			(       self     :       Union[str, Any]):
									lowerCAmelCase_			:     Dict									= self.image_processing_class(**self.image_processor_dict)
									self.assertTrue(hasattr(A_				,				'''image_mean'''))
									self.assertTrue(hasattr(A_				,				'''image_std'''))
									self.assertTrue(hasattr(A_				,				'''do_normalize'''))
									self.assertTrue(hasattr(A_				,				'''do_resize'''))
									self.assertTrue(hasattr(A_				,				'''size'''))
									self.assertTrue(hasattr(A_				,				'''size_divisor'''))




							def    UpperCAmelCase__			(       self     :       List[Any]):
									pass




							def    UpperCAmelCase__			(       self     :       Union[str, Any]):
									# Initialize image processor
									lowerCAmelCase_			:     List[Any]									= self.image_processing_class(**self.image_processor_dict)
									# create random PIL images
									lowerCAmelCase_			:     Union[str, Any]									= prepare_image_inputs(self.image_processor_tester				,				equal_resolution=A_)
									for image in image_inputs:
											self.assertIsInstance(A_				,				Image.Image)

									# Test not batched input
									lowerCAmelCase_			:     int									= image_processing(image_inputs[0]				,				return_tensors='''pt''').pixel_values

									lowerCAmelCase_					,  lowerCAmelCase_			:     Optional[int]									= self.image_processor_tester.get_expected_values(A_)
									self.assertEqual(
									    encoded_images.shape				,				(1, self.image_processor_tester.num_channels, expected_height, expected_width)				,				)

									# Test batched
									lowerCAmelCase_			:     Optional[int]									= image_processing(A_				,				return_tensors='''pt''').pixel_values

									lowerCAmelCase_					,  lowerCAmelCase_			:     str									= self.image_processor_tester.get_expected_values(A_				,				batched=A_)
									self.assertEqual(
									    encoded_images.shape				,				(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        expected_height,
									        expected_width,
									    )				,				)




							def    UpperCAmelCase__			(       self     :       Optional[int]):
									# Initialize image processor
									lowerCAmelCase_			:     Any									= self.image_processing_class(**self.image_processor_dict)
									# create random numpy tensors
									lowerCAmelCase_			:     Dict									= prepare_image_inputs(self.image_processor_tester				,				equal_resolution=A_				,				numpify=A_)
									for image in image_inputs:
											self.assertIsInstance(A_				,				np.ndarray)

									# Test not batched input
									lowerCAmelCase_			:     Optional[Any]									= image_processing(image_inputs[0]				,				return_tensors='''pt''').pixel_values

									lowerCAmelCase_					,  lowerCAmelCase_			:     List[Any]									= self.image_processor_tester.get_expected_values(A_)
									self.assertEqual(
									    encoded_images.shape				,				(1, self.image_processor_tester.num_channels, expected_height, expected_width)				,				)

									# Test batched
									lowerCAmelCase_			:     List[str]									= image_processing(A_				,				return_tensors='''pt''').pixel_values

									lowerCAmelCase_					,  lowerCAmelCase_			:     List[Any]									= self.image_processor_tester.get_expected_values(A_				,				batched=A_)
									self.assertEqual(
									    encoded_images.shape				,				(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        expected_height,
									        expected_width,
									    )				,				)







							def    UpperCAmelCase__			(       self     :       Dict):
									# Initialize image processor
									lowerCAmelCase_			:     Optional[Any]									= self.image_processing_class(**self.image_processor_dict)
									# create random PyTorch tensors
									lowerCAmelCase_			:     List[str]									= prepare_image_inputs(self.image_processor_tester				,				equal_resolution=A_				,				torchify=A_)
									for image in image_inputs:
											self.assertIsInstance(A_				,				torch.Tensor)

									# Test not batched input
									lowerCAmelCase_			:     List[str]									= image_processing(image_inputs[0]				,				return_tensors='''pt''').pixel_values

									lowerCAmelCase_					,  lowerCAmelCase_			:     int									= self.image_processor_tester.get_expected_values(A_)
									self.assertEqual(
									    encoded_images.shape				,				(1, self.image_processor_tester.num_channels, expected_height, expected_width)				,				)

									# Test batched
									lowerCAmelCase_			:     str									= image_processing(A_				,				return_tensors='''pt''').pixel_values

									lowerCAmelCase_					,  lowerCAmelCase_			:     int									= self.image_processor_tester.get_expected_values(A_				,				batched=A_)
									self.assertEqual(
									    encoded_images.shape				,				(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        expected_height,
									        expected_width,
									    )				,				)










from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


A__  :  List[str]								=					logging.get_logger(__name__)



class 				__snake_case						(     UpperCamelCase_						,UpperCamelCase_						):
							_a			      = '''maskformer-swin'''

							_a			      = {
							    '''num_attention_heads''': '''num_heads''',
							    '''num_hidden_layers''': '''num_layers''',
							}




							def __init__(       self     :       Union[str, Any]				,				A_     :       Dict=2_2_4				,				A_     :       Optional[Any]=4				,				A_     :       List[str]=3				,				A_     :       str=9_6				,				A_     :       Optional[Any]=[2, 2, 6, 2]				,				A_     :       Tuple=[3, 6, 1_2, 2_4]				,				A_     :       List[Any]=7				,				A_     :       List[Any]=4.0				,				A_     :       List[str]=True				,				A_     :       Dict=0.0				,				A_     :       int=0.0				,				A_     :       str=0.1				,				A_     :       Optional[int]="gelu"				,				A_     :       List[Any]=False				,				A_     :       int=0.02				,				A_     :       int=1e-5				,				A_     :       Optional[int]=None				,				A_     :       List[str]=None				,				**A_     :       List[Any]				,				):
									super().__init__(**A_)

									lowerCAmelCase_			:     Dict									= image_size
									lowerCAmelCase_			:     Optional[Any]									= patch_size
									lowerCAmelCase_			:     Tuple									= num_channels
									lowerCAmelCase_			:     Any									= embed_dim
									lowerCAmelCase_			:     List[str]									= depths
									lowerCAmelCase_			:     Union[str, Any]									= len(A_)
									lowerCAmelCase_			:     List[str]									= num_heads
									lowerCAmelCase_			:     Dict									= window_size
									lowerCAmelCase_			:     Optional[int]									= mlp_ratio
									lowerCAmelCase_			:     Dict									= qkv_bias
									lowerCAmelCase_			:     str									= hidden_dropout_prob
									lowerCAmelCase_			:     List[str]									= attention_probs_dropout_prob
									lowerCAmelCase_			:     Optional[int]									= drop_path_rate
									lowerCAmelCase_			:     Any									= hidden_act
									lowerCAmelCase_			:     str									= use_absolute_embeddings
									lowerCAmelCase_			:     List[str]									= layer_norm_eps
									lowerCAmelCase_			:     int									= initializer_range
									# we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
									# this indicates the channel dimension after the last stage of the model
									lowerCAmelCase_			:     str									= int(embed_dim * 2 ** (len(A_) - 1))
									lowerCAmelCase_			:     Optional[Any]									= ['''stem'''] + [F"""stage{idx}""" for idx in range(1				,				len(A_) + 1)]
									lowerCAmelCase_					,  lowerCAmelCase_			:     int									= get_aligned_output_features_output_indices(
									    out_features=A_				,				out_indices=A_				,				stage_names=self.stage_names)





