
import unittest

import numpy as np
from datasets import load_dataset

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 BeitImageProcessor







class  UpperCamelCase__		(    unittest.TestCase   ):







	'''simple docstring'''





	def __init__(			self				,       UpperCamelCase__				,       UpperCamelCase__=7				,       UpperCamelCase__=3				,       UpperCamelCase__=18				,       UpperCamelCase__=30				,       UpperCamelCase__=400				,       UpperCamelCase__=True				,       UpperCamelCase__=None				,       UpperCamelCase__=True				,       UpperCamelCase__=None				,       UpperCamelCase__=True				,       UpperCamelCase__=[0.5, 0.5, 0.5]				,       UpperCamelCase__=[0.5, 0.5, 0.5]				,       UpperCamelCase__=False				,       ):
					A__  :	Union[str, Any]         =							size if size is not None else {'''height''': 20, '''width''': 20}
					A__  :	Any         =							crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
					A__  :	Any         =							parent
					A__  :	List[Any]         =							batch_size
					A__  :	Tuple         =							num_channels
					A__  :	int         =							image_size
					A__  :	List[Any]         =							min_resolution
					A__  :	List[Any]         =							max_resolution
					A__  :	List[Any]         =							do_resize
					A__  :	int         =							size
					A__  :	int         =							do_center_crop
					A__  :	int         =							crop_size
					A__  :	Tuple         =							do_normalize
					A__  :	List[str]         =							image_mean
					A__  :	Any         =							image_std
					A__  :	Union[str, Any]         =							do_reduce_labels





	def   __snake_case				(			self		):
					return {
					    "do_resize": self.do_resize,
					    "size": self.size,
					    "do_center_crop": self.do_center_crop,
					    "crop_size": self.crop_size,
					    "do_normalize": self.do_normalize,
					    "image_mean": self.image_mean,
					    "image_std": self.image_std,
					    "do_reduce_labels": self.do_reduce_labels,
					}




def 				SCREAMING_SNAKE_CASE     (      ):

				"""simple docstring"""







				A__  :	int         =							load_dataset('''hf-internal-testing/fixtures_ade20k'''							,						split='''test'''       )

				A__  :	Any         =							Image.open(dataset[0]['''file''']       )
				A__  :	List[Any]         =							Image.open(dataset[1]['''file''']       )

				return image, map

def 				SCREAMING_SNAKE_CASE     (      ):

				"""simple docstring"""







				A__  :	Tuple         =							load_dataset('''hf-internal-testing/fixtures_ade20k'''							,						split='''test'''       )

				A__  :	List[str]         =							Image.open(ds[0]['''file''']       )
				A__  :	int         =							Image.open(ds[1]['''file''']       )
				A__  :	Any         =							Image.open(ds[2]['''file''']       )
				A__  :	Dict         =							Image.open(ds[3]['''file''']       )

				return [imagea, imagea], [mapa, mapa]







@require_torch
@require_vision
class  UpperCamelCase__		(    SCREAMING_SNAKE_CASE_,			unittest.TestCase   ):







	'''simple docstring'''
	_lowerCAmelCase							       =				BeitImageProcessor if is_vision_available() else None





	def   __snake_case				(			self		):
					A__  :	str         =							BeitImageProcessingTester(self		)





	@property
	def   __snake_case				(			self		):
					return self.image_processor_tester.prepare_image_processor_dict()





	def   __snake_case				(			self		):
					A__  :	str         =							self.image_processing_class(**self.image_processor_dict		)
					self.assertTrue(hasattr(UpperCamelCase__				,       '''do_resize'''		)		)
					self.assertTrue(hasattr(UpperCamelCase__				,       '''size'''		)		)
					self.assertTrue(hasattr(UpperCamelCase__				,       '''do_center_crop'''		)		)
					self.assertTrue(hasattr(UpperCamelCase__				,       '''center_crop'''		)		)
					self.assertTrue(hasattr(UpperCamelCase__				,       '''do_normalize'''		)		)
					self.assertTrue(hasattr(UpperCamelCase__				,       '''image_mean'''		)		)
					self.assertTrue(hasattr(UpperCamelCase__				,       '''image_std'''		)		)





	def   __snake_case				(			self		):
					A__  :	Union[str, Any]         =							self.image_processing_class.from_dict(self.image_processor_dict		)
					self.assertEqual(image_processor.size				,       {'''height''': 20, '''width''': 20}		)
					self.assertEqual(image_processor.crop_size				,       {'''height''': 18, '''width''': 18}		)
					self.assertEqual(image_processor.do_reduce_labels				,       UpperCamelCase__		)

					A__  :	Optional[Any]         =							self.image_processing_class.from_dict(
					    self.image_processor_dict				,       size=42				,       crop_size=84				,       reduce_labels=UpperCamelCase__		)
					self.assertEqual(image_processor.size				,       {'''height''': 42, '''width''': 42}		)
					self.assertEqual(image_processor.crop_size				,       {'''height''': 84, '''width''': 84}		)
					self.assertEqual(image_processor.do_reduce_labels				,       UpperCamelCase__		)





	def   __snake_case				(			self		):
					pass





	def   __snake_case				(			self		):
					# Initialize image_processing
					A__  :	Union[str, Any]         =							self.image_processing_class(**self.image_processor_dict		)
					# create random PIL images
					A__  :	Any         =							prepare_image_inputs(self.image_processor_tester				,       equal_resolution=UpperCamelCase__		)
					for image in image_inputs:
									self.assertIsInstance(UpperCamelCase__				,       Image.Image		)

					# Test not batched input
					A__  :	Any         =							image_processing(image_inputs[0]				,       return_tensors='''pt'''		).pixel_values
					self.assertEqual(
					    encoded_images.shape				,       (
					        1,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )

					# Test batched
					A__  :	List[Any]         =							image_processing(UpperCamelCase__				,       return_tensors='''pt'''		).pixel_values
					self.assertEqual(
					    encoded_images.shape				,       (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )





	def   __snake_case				(			self		):
					# Initialize image_processing
					A__  :	str         =							self.image_processing_class(**self.image_processor_dict		)
					# create random numpy tensors
					A__  :	Dict         =							prepare_image_inputs(self.image_processor_tester				,       equal_resolution=UpperCamelCase__				,       numpify=UpperCamelCase__		)
					for image in image_inputs:
									self.assertIsInstance(UpperCamelCase__				,       np.ndarray		)

					# Test not batched input
					A__  :	List[Any]         =							image_processing(image_inputs[0]				,       return_tensors='''pt'''		).pixel_values
					self.assertEqual(
					    encoded_images.shape				,       (
					        1,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )

					# Test batched
					A__  :	Dict         =							image_processing(UpperCamelCase__				,       return_tensors='''pt'''		).pixel_values
					self.assertEqual(
					    encoded_images.shape				,       (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )





	def   __snake_case				(			self		):
					# Initialize image_processing
					A__  :	Optional[int]         =							self.image_processing_class(**self.image_processor_dict		)
					# create random PyTorch tensors
					A__  :	Union[str, Any]         =							prepare_image_inputs(self.image_processor_tester				,       equal_resolution=UpperCamelCase__				,       torchify=UpperCamelCase__		)
					for image in image_inputs:
									self.assertIsInstance(UpperCamelCase__				,       torch.Tensor		)

					# Test not batched input
					A__  :	Tuple         =							image_processing(image_inputs[0]				,       return_tensors='''pt'''		).pixel_values
					self.assertEqual(
					    encoded_images.shape				,       (
					        1,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )

					# Test batched
					A__  :	Tuple         =							image_processing(UpperCamelCase__				,       return_tensors='''pt'''		).pixel_values
					self.assertEqual(
					    encoded_images.shape				,       (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )





	def   __snake_case				(			self		):
					# Initialize image_processing
					A__  :	List[str]         =							self.image_processing_class(**self.image_processor_dict		)
					# create random PyTorch tensors
					A__  :	List[Any]         =							prepare_image_inputs(self.image_processor_tester				,       equal_resolution=UpperCamelCase__				,       torchify=UpperCamelCase__		)
					A__  :	int         =							[]
					for image in image_inputs:
									self.assertIsInstance(UpperCamelCase__				,       torch.Tensor		)
									maps.append(torch.zeros(image.shape[-2:]		).long()		)

					# Test not batched input
					A__  :	Tuple         =							image_processing(image_inputs[0]				,       maps[0]				,       return_tensors='''pt'''		)
					self.assertEqual(
					    encoding['''pixel_values'''].shape				,       (
					        1,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )
					self.assertEqual(
					    encoding['''labels'''].shape				,       (
					        1,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )
					self.assertEqual(encoding['''labels'''].dtype				,       torch.long		)
					self.assertTrue(encoding['''labels'''].min().item() >= 0		)
					self.assertTrue(encoding['''labels'''].max().item() <= 255		)

					# Test batched
					A__  :	Any         =							image_processing(UpperCamelCase__				,       UpperCamelCase__				,       return_tensors='''pt'''		)
					self.assertEqual(
					    encoding['''pixel_values'''].shape				,       (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )
					self.assertEqual(
					    encoding['''labels'''].shape				,       (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )
					self.assertEqual(encoding['''labels'''].dtype				,       torch.long		)
					self.assertTrue(encoding['''labels'''].min().item() >= 0		)
					self.assertTrue(encoding['''labels'''].max().item() <= 255		)

					# Test not batched input (PIL images)
					A__  :	Optional[Any]         =							prepare_semantic_single_inputs()

					A__  :	Dict         =							image_processing(UpperCamelCase__				,       UpperCamelCase__				,       return_tensors='''pt'''		)
					self.assertEqual(
					    encoding['''pixel_values'''].shape				,       (
					        1,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )
					self.assertEqual(
					    encoding['''labels'''].shape				,       (
					        1,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )
					self.assertEqual(encoding['''labels'''].dtype				,       torch.long		)
					self.assertTrue(encoding['''labels'''].min().item() >= 0		)
					self.assertTrue(encoding['''labels'''].max().item() <= 255		)

					# Test batched input (PIL images)
					A__  :	List[str]         =							prepare_semantic_batch_inputs()

					A__  :	List[str]         =							image_processing(UpperCamelCase__				,       UpperCamelCase__				,       return_tensors='''pt'''		)
					self.assertEqual(
					    encoding['''pixel_values'''].shape				,       (
					        2,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )
					self.assertEqual(
					    encoding['''labels'''].shape				,       (
					        2,
					        self.image_processor_tester.crop_size['''height'''],
					        self.image_processor_tester.crop_size['''width'''],
					    )				,       )
					self.assertEqual(encoding['''labels'''].dtype				,       torch.long		)
					self.assertTrue(encoding['''labels'''].min().item() >= 0		)
					self.assertTrue(encoding['''labels'''].max().item() <= 255		)





	def   __snake_case				(			self		):
					# Initialize image_processing
					A__  :	Optional[Any]         =							self.image_processing_class(**self.image_processor_dict		)

					# ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
					A__  :	List[Any]         =							prepare_semantic_single_inputs()
					A__  :	int         =							image_processing(UpperCamelCase__				,       UpperCamelCase__				,       return_tensors='''pt'''		)
					self.assertTrue(encoding['''labels'''].min().item() >= 0		)
					self.assertTrue(encoding['''labels'''].max().item() <= 150		)

					A__  :	Optional[int]         =							True
					A__  :	str         =							image_processing(UpperCamelCase__				,       UpperCamelCase__				,       return_tensors='''pt'''		)
					self.assertTrue(encoding['''labels'''].min().item() >= 0		)
					self.assertTrue(encoding['''labels'''].max().item() <= 255		)

import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


_SCREAMING_SNAKE_CASE    :      Union[str, Any]          =			logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE    :      int          =			{
    'SenseTime/deformable-detr': 'https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json',
    # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr
}







class  UpperCamelCase__		(    SCREAMING_SNAKE_CASE_   ):







	'''simple docstring'''
	_lowerCAmelCase							       =				"deformable_detr"
	_lowerCAmelCase							       =				{
	    "hidden_size": "d_model",
	    "num_attention_heads": "encoder_attention_heads",
	}





	def __init__(			self				,       UpperCamelCase__=True				,       UpperCamelCase__=None				,       UpperCamelCase__=3				,       UpperCamelCase__=300				,       UpperCamelCase__=1024				,       UpperCamelCase__=6				,       UpperCamelCase__=1024				,       UpperCamelCase__=8				,       UpperCamelCase__=6				,       UpperCamelCase__=1024				,       UpperCamelCase__=8				,       UpperCamelCase__=0.0				,       UpperCamelCase__=True				,       UpperCamelCase__="relu"				,       UpperCamelCase__=256				,       UpperCamelCase__=0.1				,       UpperCamelCase__=0.0				,       UpperCamelCase__=0.0				,       UpperCamelCase__=0.0_2				,       UpperCamelCase__=1.0				,       UpperCamelCase__=True				,       UpperCamelCase__=False				,       UpperCamelCase__="sine"				,       UpperCamelCase__="resnet50"				,       UpperCamelCase__=True				,       UpperCamelCase__=False				,       UpperCamelCase__=4				,       UpperCamelCase__=4				,       UpperCamelCase__=4				,       UpperCamelCase__=False				,       UpperCamelCase__=300				,       UpperCamelCase__=False				,       UpperCamelCase__=1				,       UpperCamelCase__=5				,       UpperCamelCase__=2				,       UpperCamelCase__=1				,       UpperCamelCase__=1				,       UpperCamelCase__=5				,       UpperCamelCase__=2				,       UpperCamelCase__=0.1				,       UpperCamelCase__=0.2_5				,       UpperCamelCase__=False				,       **UpperCamelCase__				,       ):
					if backbone_config is not None and use_timm_backbone:
									raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.'''		)

					if not use_timm_backbone:
									if backbone_config is None:
													logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.'''		)
													A__  :	int         =							CONFIG_MAPPING['''resnet'''](out_features=['''stage4''']		)
									elif isinstance(UpperCamelCase__				,       UpperCamelCase__		):
													A__  :	Union[str, Any]         =							backbone_config.get('''model_type'''		)
													A__  :	Union[str, Any]         =							CONFIG_MAPPING[backbone_model_type]
													A__  :	Optional[int]         =							config_class.from_dict(UpperCamelCase__		)
					A__  :	Tuple         =							use_timm_backbone
					A__  :	int         =							backbone_config
					A__  :	List[Any]         =							num_channels
					A__  :	List[Any]         =							num_queries
					A__  :	str         =							max_position_embeddings
					A__  :	Tuple         =							d_model
					A__  :	int         =							encoder_ffn_dim
					A__  :	Union[str, Any]         =							encoder_layers
					A__  :	Optional[Any]         =							encoder_attention_heads
					A__  :	List[Any]         =							decoder_ffn_dim
					A__  :	Tuple         =							decoder_layers
					A__  :	Optional[Any]         =							decoder_attention_heads
					A__  :	List[str]         =							dropout
					A__  :	str         =							attention_dropout
					A__  :	List[Any]         =							activation_dropout
					A__  :	Any         =							activation_function
					A__  :	Optional[Any]         =							init_std
					A__  :	Union[str, Any]         =							init_xavier_std
					A__  :	Union[str, Any]         =							encoder_layerdrop
					A__  :	Optional[int]         =							auxiliary_loss
					A__  :	str         =							position_embedding_type
					A__  :	List[Any]         =							backbone
					A__  :	Optional[Any]         =							use_pretrained_backbone
					A__  :	Any         =							dilation
					# deformable attributes
					A__  :	List[Any]         =							num_feature_levels
					A__  :	List[str]         =							encoder_n_points
					A__  :	int         =							decoder_n_points
					A__  :	List[Any]         =							two_stage
					A__  :	Dict         =							two_stage_num_proposals
					A__  :	Optional[int]         =							with_box_refine
					if two_stage is True and with_box_refine is False:
									raise ValueError('''If two_stage is True, with_box_refine must be True.'''		)
					# Hungarian matcher
					A__  :	List[str]         =							class_cost
					A__  :	List[Any]         =							bbox_cost
					A__  :	Any         =							giou_cost
					# Loss coefficients
					A__  :	List[str]         =							mask_loss_coefficient
					A__  :	Union[str, Any]         =							dice_loss_coefficient
					A__  :	List[Any]         =							bbox_loss_coefficient
					A__  :	Tuple         =							giou_loss_coefficient
					A__  :	Optional[Any]         =							eos_coefficient
					A__  :	List[Any]         =							focal_alpha
					A__  :	List[str]         =							disable_custom_kernels
					super().__init__(is_encoder_decoder=UpperCamelCase__				,       **UpperCamelCase__		)





	@property
	def   __snake_case				(			self		):
					return self.encoder_attention_heads





	@property
	def   __snake_case				(			self		):
					return self.d_model





	def   __snake_case				(			self		):
					A__  :	List[str]         =							copy.deepcopy(self.__dict__		)
					if self.backbone_config is not None:
									A__  :	Tuple         =							self.backbone_config.to_dict()
					A__  :	Optional[int]         =							self.__class__.model_type
					return output