





"""simple docstring"""







import json
import pathlib
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision, slow
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 ConditionalDetrImageProcessor




class __magic_name__   (       unittest.TestCase		):
       def __init__(     self   ,  __magic_name__   ,  __magic_name__=7   ,  __magic_name__=3   ,  __magic_name__=3_0   ,  __magic_name__=4_0_0   ,  __magic_name__=True   ,  __magic_name__=None   ,  __magic_name__=True   ,  __magic_name__=[0.5, 0.5, 0.5]   ,  __magic_name__=[0.5, 0.5, 0.5]   ,  __magic_name__=True   ,  __magic_name__=1 / 2_5_5   ,  __magic_name__=True   ,  ):





         """simple docstring"""


         _lowerCAmelCase	      =					size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}
         _lowerCAmelCase	      =					parent
         _lowerCAmelCase	      =					batch_size
         _lowerCAmelCase	      =					num_channels
         _lowerCAmelCase	      =					min_resolution
         _lowerCAmelCase	      =					max_resolution
         _lowerCAmelCase	      =					do_resize
         _lowerCAmelCase	      =					size
         _lowerCAmelCase	      =					do_normalize
         _lowerCAmelCase	      =					image_mean
         _lowerCAmelCase	      =					image_std
         _lowerCAmelCase	      =					do_rescale
         _lowerCAmelCase	      =					rescale_factor
         _lowerCAmelCase	      =					do_pad
       def 		_lowerCamelCase   (     self	):





         """simple docstring"""


         return {
             "do_resize": self.do_resize,
             "size": self.size,
             "do_normalize": self.do_normalize,
             "image_mean": self.image_mean,
             "image_std": self.image_std,
             "do_rescale": self.do_rescale,
             "rescale_factor": self.rescale_factor,
             "do_pad": self.do_pad,
         }
       def 		_lowerCamelCase   (     self   ,  __magic_name__   ,  __magic_name__=False	):





         """simple docstring"""


         if not batched:
           _lowerCAmelCase	      =					image_inputs[0]
           if isinstance(__magic_name__   ,  Image.Image	):
             _lowerCAmelCase      ,   _lowerCAmelCase	      =					image.size
           else:
             _lowerCAmelCase      ,   _lowerCAmelCase	      =					image.shape[1], image.shape[2]
           if w < h:
             _lowerCAmelCase	      =					int(self.size['shortest_edge'] * h / w	)
             _lowerCAmelCase	      =					self.size['shortest_edge']
           elif w > h:
             _lowerCAmelCase	      =					self.size['shortest_edge']
             _lowerCAmelCase	      =					int(self.size['shortest_edge'] * w / h	)
           else:
             _lowerCAmelCase	      =					self.size['shortest_edge']
             _lowerCAmelCase	      =					self.size['shortest_edge']

         else:
           _lowerCAmelCase	      =					[]
           for image in image_inputs:
             _lowerCAmelCase      ,   _lowerCAmelCase	      =					self.get_expected_values([image]	)
             expected_values.append((expected_height, expected_width)	)
           _lowerCAmelCase	      =					max(__magic_name__   ,  key=lambda __magic_name__	: item[0]	)[0]
           _lowerCAmelCase	      =					max(__magic_name__   ,  key=lambda __magic_name__	: item[1]	)[1]

         return expected_height, expected_width





@require_torch
@require_vision
class __magic_name__   (       A__    ,unittest.TestCase		):
       UpperCamelCase    :						List[str]      =	ConditionalDetrImageProcessor if is_vision_available() else None
       def 		_lowerCamelCase   (     self	):





         """simple docstring"""


         _lowerCAmelCase	      =					ConditionalDetrImageProcessingTester(self	)
       @property
       def 		_lowerCamelCase   (     self	):





         """simple docstring"""


         return self.image_processor_tester.prepare_image_processor_dict()
       def 		_lowerCamelCase   (     self	):





         """simple docstring"""


         _lowerCAmelCase	      =					self.image_processing_class(**self.image_processor_dict	)
         self.assertTrue(hasattr(__magic_name__   ,  'image_mean'	)	)
         self.assertTrue(hasattr(__magic_name__   ,  'image_std'	)	)
         self.assertTrue(hasattr(__magic_name__   ,  'do_normalize'	)	)
         self.assertTrue(hasattr(__magic_name__   ,  'do_resize'	)	)
         self.assertTrue(hasattr(__magic_name__   ,  'size'	)	)
       def 		_lowerCamelCase   (     self	):





         """simple docstring"""


         _lowerCAmelCase	      =					self.image_processing_class.from_dict(self.image_processor_dict	)
         self.assertEqual(image_processor.size   ,  {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}	)
         self.assertEqual(image_processor.do_pad   ,  __magic_name__	)

         _lowerCAmelCase	      =					self.image_processing_class.from_dict(
             self.image_processor_dict   ,  size=4_2   ,  max_size=8_4   ,  pad_and_return_pixel_mask=__magic_name__	)
         self.assertEqual(image_processor.size   ,  {'shortest_edge': 4_2, 'longest_edge': 8_4}	)
         self.assertEqual(image_processor.do_pad   ,  __magic_name__	)
       def 		_lowerCamelCase   (     self	):





         """simple docstring"""


         pass
       def 		_lowerCamelCase   (     self	):





         """simple docstring"""


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

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

         _lowerCAmelCase      ,   _lowerCAmelCase	      =					self.image_processor_tester.get_expected_values(__magic_name__	)

         self.assertEqual(
             encoded_images.shape   ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)   ,  )

         # Test batched
         _lowerCAmelCase      ,   _lowerCAmelCase	      =					self.image_processor_tester.get_expected_values(__magic_name__   ,  batched=__magic_name__	)

         _lowerCAmelCase	      =					image_processing(__magic_name__   ,  return_tensors='pt'	).pixel_values
         self.assertEqual(
             encoded_images.shape   ,  (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )   ,  )
       def 		_lowerCamelCase   (     self	):





         """simple docstring"""


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

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

         _lowerCAmelCase      ,   _lowerCAmelCase	      =					self.image_processor_tester.get_expected_values(__magic_name__	)

         self.assertEqual(
             encoded_images.shape   ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)   ,  )

         # Test batched
         _lowerCAmelCase	      =					image_processing(__magic_name__   ,  return_tensors='pt'	).pixel_values

         _lowerCAmelCase      ,   _lowerCAmelCase	      =					self.image_processor_tester.get_expected_values(__magic_name__   ,  batched=__magic_name__	)

         self.assertEqual(
             encoded_images.shape   ,  (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )   ,  )
       def 		_lowerCamelCase   (     self	):





         """simple docstring"""


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

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

         _lowerCAmelCase      ,   _lowerCAmelCase	      =					self.image_processor_tester.get_expected_values(__magic_name__	)

         self.assertEqual(
             encoded_images.shape   ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)   ,  )

         # Test batched
         _lowerCAmelCase	      =					image_processing(__magic_name__   ,  return_tensors='pt'	).pixel_values

         _lowerCAmelCase      ,   _lowerCAmelCase	      =					self.image_processor_tester.get_expected_values(__magic_name__   ,  batched=__magic_name__	)

         self.assertEqual(
             encoded_images.shape   ,  (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )   ,  )
       @slow
       def 		_lowerCamelCase   (     self	):





         """simple docstring"""


         _lowerCAmelCase	      =					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
         with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt'   ,  'r'	) as f:
           _lowerCAmelCase	      =					json.loads(f.read()	)

         _lowerCAmelCase	      =					{'image_id': 3_9_7_6_9, 'annotations': target}

         # encode them
         _lowerCAmelCase	      =					ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50'	)
         _lowerCAmelCase	      =					image_processing(images=__magic_name__   ,  annotations=__magic_name__   ,  return_tensors='pt'	)

         # verify pixel values
         _lowerCAmelCase	      =					torch.Size([1, 3, 8_0_0, 1_0_6_6]	)
         self.assertEqual(encoding['pixel_values'].shape   ,  __magic_name__	)

         _lowerCAmelCase	      =					torch.tensor([0.27_96, 0.31_38, 0.34_81]	)
         self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]   ,  __magic_name__   ,  atol=1e-4	)	)

         # verify area
         _lowerCAmelCase	      =					torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['area']   ,  __magic_name__	)	)
         # verify boxes
         _lowerCAmelCase	      =					torch.Size([6, 4]	)
         self.assertEqual(encoding['labels'][0]['boxes'].shape   ,  __magic_name__	)
         _lowerCAmelCase	      =					torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]   ,  __magic_name__   ,  atol=1e-3	)	)
         # verify image_id
         _lowerCAmelCase	      =					torch.tensor([3_9_7_6_9]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']   ,  __magic_name__	)	)
         # verify is_crowd
         _lowerCAmelCase	      =					torch.tensor([0, 0, 0, 0, 0, 0]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']   ,  __magic_name__	)	)
         # verify class_labels
         _lowerCAmelCase	      =					torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']   ,  __magic_name__	)	)
         # verify orig_size
         _lowerCAmelCase	      =					torch.tensor([4_8_0, 6_4_0]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']   ,  __magic_name__	)	)
         # verify size
         _lowerCAmelCase	      =					torch.tensor([8_0_0, 1_0_6_6]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['size']   ,  __magic_name__	)	)
       @slow
       def 		_lowerCamelCase   (     self	):





         """simple docstring"""


         _lowerCAmelCase	      =					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
         with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt'   ,  'r'	) as f:
           _lowerCAmelCase	      =					json.loads(f.read()	)

         _lowerCAmelCase	      =					{'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target}

         _lowerCAmelCase	      =					pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic'	)

         # encode them
         _lowerCAmelCase	      =					ConditionalDetrImageProcessor(format='coco_panoptic'	)
         _lowerCAmelCase	      =					image_processing(images=__magic_name__   ,  annotations=__magic_name__   ,  masks_path=__magic_name__   ,  return_tensors='pt'	)

         # verify pixel values
         _lowerCAmelCase	      =					torch.Size([1, 3, 8_0_0, 1_0_6_6]	)
         self.assertEqual(encoding['pixel_values'].shape   ,  __magic_name__	)

         _lowerCAmelCase	      =					torch.tensor([0.27_96, 0.31_38, 0.34_81]	)
         self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]   ,  __magic_name__   ,  atol=1e-4	)	)

         # verify area
         _lowerCAmelCase	      =					torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['area']   ,  __magic_name__	)	)
         # verify boxes
         _lowerCAmelCase	      =					torch.Size([6, 4]	)
         self.assertEqual(encoding['labels'][0]['boxes'].shape   ,  __magic_name__	)
         _lowerCAmelCase	      =					torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]   ,  __magic_name__   ,  atol=1e-3	)	)
         # verify image_id
         _lowerCAmelCase	      =					torch.tensor([3_9_7_6_9]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']   ,  __magic_name__	)	)
         # verify is_crowd
         _lowerCAmelCase	      =					torch.tensor([0, 0, 0, 0, 0, 0]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']   ,  __magic_name__	)	)
         # verify class_labels
         _lowerCAmelCase	      =					torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']   ,  __magic_name__	)	)
         # verify masks
         _lowerCAmelCase	      =					8_2_2_8_7_3
         self.assertEqual(encoding['labels'][0]['masks'].sum().item()   ,  __magic_name__	)
         # verify orig_size
         _lowerCAmelCase	      =					torch.tensor([4_8_0, 6_4_0]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']   ,  __magic_name__	)	)
         # verify size
         _lowerCAmelCase	      =					torch.tensor([8_0_0, 1_0_6_6]	)
         self.assertTrue(torch.allclose(encoding['labels'][0]['size']   ,  __magic_name__	)	)











import copy

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


A__      :     Tuple       =					logging.get_logger(__name__)
class  _UpperCAmelCase   (			A__      ):

				"""simple docstring"""




				lowercase__											=			"""upernet"""




				def __init__(	self		:       Dict,    lowerCamelCase		:       Union[str, Any]=None,    lowerCamelCase		:       str=512,    lowerCamelCase		:       Optional[Any]=0.02,    lowerCamelCase		:       Optional[Any]=[1, 2, 3, 6],    lowerCamelCase		:       Optional[int]=True,    lowerCamelCase		:       Tuple=0.4,    lowerCamelCase		:       Optional[int]=384,    lowerCamelCase		:       Optional[int]=256,    lowerCamelCase		:       Dict=1,    lowerCamelCase		:       str=False,    lowerCamelCase		:       List[str]=255,    **lowerCamelCase		:       List[Any],    ):

								'''simple docstring'''
								super().__init__(**lowerCamelCase    )

								if backbone_config is None:
												logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.'''    )
												lowercase__  					=     CONFIG_MAPPING['''resnet'''](out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4''']    )
								elif isinstance(lowerCamelCase,    lowerCamelCase    ):
												lowercase__  					=     backbone_config.get('''model_type'''    )
												lowercase__  					=     CONFIG_MAPPING[backbone_model_type]
												lowercase__  					=     config_class.from_dict(lowerCamelCase    )

								lowercase__  					=     backbone_config
								lowercase__  					=     hidden_size
								lowercase__  					=     initializer_range
								lowercase__  					=     pool_scales
								lowercase__  					=     use_auxiliary_head
								lowercase__  					=     auxiliary_loss_weight
								lowercase__  					=     auxiliary_in_channels
								lowercase__  					=     auxiliary_channels
								lowercase__  					=     auxiliary_num_convs
								lowercase__  					=     auxiliary_concat_input
								lowercase__  					=     loss_ignore_index




				def 							lowercase__  (	self		:       str    ):

								'''simple docstring'''
								lowercase__  					=     copy.deepcopy(self.__dict__    )
								lowercase__  					=     self.backbone_config.to_dict()
								lowercase__  					=     self.__class__.model_type
								return output




