


import copy
from collections import OrderedDict
from typing import Dict, Mapping

from packaging import version

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


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

lowerCAmelCase__			:      List[str]								={
    'facebook/detr-resnet-50': 'https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json',
    # See all DETR models at https://huggingface.co/models?filter=detr
}







class 	__lowercase    (__SCREAMING_SNAKE_CASE  ):





							"""simple docstring"""







							_UpperCAmelCase      =						"""detr"""
							_UpperCAmelCase      =						["""past_key_values"""]
							_UpperCAmelCase      =						{
							    """hidden_size""": """d_model""",
							    """num_attention_heads""": """encoder_attention_heads""",
							}






							def __init__(      self			,						lowerCAmelCase__=True			,						lowerCAmelCase__=None			,						lowerCAmelCase__=3			,						lowerCAmelCase__=1_0_0			,						lowerCAmelCase__=6			,						lowerCAmelCase__=2_0_4_8			,						lowerCAmelCase__=8			,						lowerCAmelCase__=6			,						lowerCAmelCase__=2_0_4_8			,						lowerCAmelCase__=8			,						lowerCAmelCase__=0.0			,						lowerCAmelCase__=0.0			,						lowerCAmelCase__=True			,						lowerCAmelCase__="relu"			,						lowerCAmelCase__=2_5_6			,						lowerCAmelCase__=0.1			,						lowerCAmelCase__=0.0			,						lowerCAmelCase__=0.0			,						lowerCAmelCase__=0.02			,						lowerCAmelCase__=1.0			,						lowerCAmelCase__=False			,						lowerCAmelCase__="sine"			,						lowerCAmelCase__="resnet50"			,						lowerCAmelCase__=True			,						lowerCAmelCase__=False			,						lowerCAmelCase__=1			,						lowerCAmelCase__=5			,						lowerCAmelCase__=2			,						lowerCAmelCase__=1			,						lowerCAmelCase__=1			,						lowerCAmelCase__=5			,						lowerCAmelCase__=2			,						lowerCAmelCase__=0.1			,						**lowerCAmelCase__			,						):





										"""simple docstring"""




										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.'       )
																SCREAMING_SNAKE_CASE_		:     Dict					=					CONFIG_MAPPING['resnet'](out_features=['stage4']       )
													elif isinstance(lowerCAmelCase__			,						lowerCAmelCase__       ):
																SCREAMING_SNAKE_CASE_		:     Tuple					=					backbone_config.get('model_type'       )
																SCREAMING_SNAKE_CASE_		:     Optional[int]					=					CONFIG_MAPPING[backbone_model_type]
																SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					config_class.from_dict(lowerCAmelCase__       )
													# set timm attributes to None
													SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					None, None, None

										SCREAMING_SNAKE_CASE_		:     List[Any]					=					use_timm_backbone
										SCREAMING_SNAKE_CASE_		:     List[str]					=					backbone_config
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					num_channels
										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					num_queries
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					d_model
										SCREAMING_SNAKE_CASE_		:     Dict					=					encoder_ffn_dim
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					encoder_layers
										SCREAMING_SNAKE_CASE_		:     Tuple					=					encoder_attention_heads
										SCREAMING_SNAKE_CASE_		:     Tuple					=					decoder_ffn_dim
										SCREAMING_SNAKE_CASE_		:     int					=					decoder_layers
										SCREAMING_SNAKE_CASE_		:     Any					=					decoder_attention_heads
										SCREAMING_SNAKE_CASE_		:     int					=					dropout
										SCREAMING_SNAKE_CASE_		:     List[str]					=					attention_dropout
										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					activation_dropout
										SCREAMING_SNAKE_CASE_		:     int					=					activation_function
										SCREAMING_SNAKE_CASE_		:     int					=					init_std
										SCREAMING_SNAKE_CASE_		:     Dict					=					init_xavier_std
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					encoder_layerdrop
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					decoder_layerdrop
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					encoder_layers
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					auxiliary_loss
										SCREAMING_SNAKE_CASE_		:     Dict					=					position_embedding_type
										SCREAMING_SNAKE_CASE_		:     str					=					backbone
										SCREAMING_SNAKE_CASE_		:     Any					=					use_pretrained_backbone
										SCREAMING_SNAKE_CASE_		:     Dict					=					dilation
										# Hungarian matcher
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					class_cost
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					bbox_cost
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					giou_cost
										# Loss coefficients
										SCREAMING_SNAKE_CASE_		:     Any					=					mask_loss_coefficient
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					dice_loss_coefficient
										SCREAMING_SNAKE_CASE_		:     Dict					=					bbox_loss_coefficient
										SCREAMING_SNAKE_CASE_		:     int					=					giou_loss_coefficient
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					eos_coefficient
										super().__init__(is_encoder_decoder=lowerCAmelCase__			,						**lowerCAmelCase__       )






							@property
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										return self.encoder_attention_heads






							@property
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										return self.d_model






							@classmethod
							def 					UpperCamelCase__     (      cls			,						lowerCAmelCase__			,						**lowerCAmelCase__       ):





										"""simple docstring"""




										return cls(backbone_config=lowerCAmelCase__			,						**lowerCAmelCase__       )






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					copy.deepcopy(self.__dict__       )
										if output["backbone_config"] is not None:
													SCREAMING_SNAKE_CASE_		:     str					=					self.backbone_config.to_dict()
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					self.__class__.model_type
										return output







class 	__lowercase    (__SCREAMING_SNAKE_CASE  ):





							"""simple docstring"""







							_UpperCAmelCase      =						version.parse("""1.11"""  )






							@property
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										return OrderedDict(
										    [
										        ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
										        ('pixel_mask', {0: 'batch'}),
										    ]       )






							@property
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										return 1E-5






							@property
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										return 1_2









import unittest

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 PoolFormerImageProcessor






class      UpperCamelCase(	unittest.TestCase ):


					def __init__(    self						:		Tuple  ,     SCREAMING_SNAKE_CASE						:		List[Any]  ,     SCREAMING_SNAKE_CASE						:		Optional[Any]=7  ,     SCREAMING_SNAKE_CASE						:		Dict=3  ,     SCREAMING_SNAKE_CASE						:		Any=3_0  ,     SCREAMING_SNAKE_CASE						:		List[str]=4_0_0  ,     SCREAMING_SNAKE_CASE						:		Any=True  ,     SCREAMING_SNAKE_CASE						:		List[Any]=None  ,     SCREAMING_SNAKE_CASE						:		int=0.9  ,     SCREAMING_SNAKE_CASE						:		Tuple=None  ,     SCREAMING_SNAKE_CASE						:		int=True  ,     SCREAMING_SNAKE_CASE						:		Union[str, Any]=[0.5, 0.5, 0.5]  ,     SCREAMING_SNAKE_CASE						:		Optional[Any]=[0.5, 0.5, 0.5]  ,     )      ->						Union[str, Any]:




											'''simple docstring'''

											__snake_case				=		size if size is not None else {"shortest_edge": 3_0}
											__snake_case				=		crop_size if crop_size is not None else {"height": 3_0, "width": 3_0}
											__snake_case				=		parent
											__snake_case				=		batch_size
											__snake_case				=		num_channels
											__snake_case				=		min_resolution
											__snake_case				=		max_resolution
											__snake_case				=		do_resize_and_center_crop
											__snake_case				=		size
											__snake_case				=		crop_pct
											__snake_case				=		crop_size
											__snake_case				=		do_normalize
											__snake_case				=		image_mean
											__snake_case				=		image_std






					def 				SCREAMING_SNAKE_CASE_	(    self						:		str    )      ->						Any:




											'''simple docstring'''

											return {
											    "size": self.size,
											    "do_resize_and_center_crop": self.do_resize_and_center_crop,
											    "crop_pct": self.crop_pct,
											    "crop_size": self.crop_size,
											    "do_normalize": self.do_normalize,
											    "image_mean": self.image_mean,
											    "image_std": self.image_std,
											}






@require_torch
@require_vision
class      UpperCamelCase(	_a  ,				unittest.TestCase ):
					snake_case_		:					List[str]    					=						PoolFormerImageProcessor if is_vision_available() else None


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




											'''simple docstring'''

											__snake_case				=		PoolFormerImageProcessingTester(self    )


					@property
					def 				SCREAMING_SNAKE_CASE_	(    self						:		int    )      ->						Dict:




											'''simple docstring'''

											return self.image_processor_tester.prepare_image_processor_dict()


					def 				SCREAMING_SNAKE_CASE_	(    self						:		Dict    )      ->						List[str]:




											'''simple docstring'''

											__snake_case				=		self.image_processing_class(**self.image_processor_dict    )
											self.assertTrue(hasattr(SCREAMING_SNAKE_CASE  ,     "do_resize_and_center_crop"    )    )
											self.assertTrue(hasattr(SCREAMING_SNAKE_CASE  ,     "size"    )    )
											self.assertTrue(hasattr(SCREAMING_SNAKE_CASE  ,     "crop_pct"    )    )
											self.assertTrue(hasattr(SCREAMING_SNAKE_CASE  ,     "do_normalize"    )    )
											self.assertTrue(hasattr(SCREAMING_SNAKE_CASE  ,     "image_mean"    )    )
											self.assertTrue(hasattr(SCREAMING_SNAKE_CASE  ,     "image_std"    )    )


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




											'''simple docstring'''

											__snake_case				=		self.image_processing_class.from_dict(self.image_processor_dict    )
											self.assertEqual(image_processor.size  ,     {"shortest_edge": 3_0}    )
											self.assertEqual(image_processor.crop_size  ,     {"height": 3_0, "width": 3_0}    )

											__snake_case				=		self.image_processing_class.from_dict(self.image_processor_dict  ,     size=4_2  ,     crop_size=8_4    )
											self.assertEqual(image_processor.size  ,     {"shortest_edge": 4_2}    )
											self.assertEqual(image_processor.crop_size  ,     {"height": 8_4, "width": 8_4}    )


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




											'''simple docstring'''

											pass


					def 				SCREAMING_SNAKE_CASE_	(    self						:		Optional[Any]    )      ->						Dict:




											'''simple docstring'''

											__snake_case				=		self.image_processing_class(**self.image_processor_dict    )
											# create random PIL images
											__snake_case				=		prepare_image_inputs(self.image_processor_tester  ,     equal_resolution=SCREAMING_SNAKE_CASE    )
											for image in image_inputs:
																	self.assertIsInstance(SCREAMING_SNAKE_CASE  ,     Image.Image    )

											# Test not batched input
											__snake_case				=		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
											__snake_case				=		image_processing(SCREAMING_SNAKE_CASE  ,     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 				SCREAMING_SNAKE_CASE_	(    self						:		Optional[Any]    )      ->						Optional[int]:




											'''simple docstring'''

											__snake_case				=		self.image_processing_class(**self.image_processor_dict    )
											# create random numpy tensors
											__snake_case				=		prepare_image_inputs(self.image_processor_tester  ,     equal_resolution=SCREAMING_SNAKE_CASE  ,     numpify=SCREAMING_SNAKE_CASE    )
											for image in image_inputs:
																	self.assertIsInstance(SCREAMING_SNAKE_CASE  ,     np.ndarray    )

											# Test not batched input
											__snake_case				=		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
											__snake_case				=		image_processing(SCREAMING_SNAKE_CASE  ,     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 				SCREAMING_SNAKE_CASE_	(    self						:		Optional[int]    )      ->						Union[str, Any]:




											'''simple docstring'''

											__snake_case				=		self.image_processing_class(**self.image_processor_dict    )
											# create random PyTorch tensors
											__snake_case				=		prepare_image_inputs(self.image_processor_tester  ,     equal_resolution=SCREAMING_SNAKE_CASE  ,     torchify=SCREAMING_SNAKE_CASE    )
											for image in image_inputs:
																	self.assertIsInstance(SCREAMING_SNAKE_CASE  ,     torch.Tensor    )

											# Test not batched input
											__snake_case				=		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
											__snake_case				=		image_processing(SCREAMING_SNAKE_CASE  ,     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"],
											    )  ,     )





