



'''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 DeformableDetrImageProcessor



class  snake_case__						(    unittest.TestCase				):
 def __init__(   self						:							Dict      ,     __a						:							Union[str, Any]      ,     __a						:							Tuple=7      ,     __a						:							List[str]=3      ,     __a						:							Tuple=30      ,     __a						:							str=400      ,     __a						:							Union[str, Any]=True      ,     __a						:							Tuple=None      ,     __a						:							Optional[int]=True      ,     __a						:							str=[0.5, 0.5, 0.5]      ,     __a						:							Tuple=[0.5, 0.5, 0.5]      ,     __a						:							Tuple=True      ,     __a						:							str=1 / 255      ,     __a						:							int=True      ,     )      ->   int:







       '''simple docstring'''
       # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
       __snake_case :   Optional[Any]													=    size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333}
       __snake_case :   Union[str, Any]													=    parent
       __snake_case :   int													=    batch_size
       __snake_case :   Union[str, Any]													=    num_channels
       __snake_case :   Tuple													=    min_resolution
       __snake_case :   List[Any]													=    max_resolution
       __snake_case :   List[str]													=    do_resize
       __snake_case :   Dict													=    size
       __snake_case :   Optional[int]													=    do_normalize
       __snake_case :   Optional[int]													=    image_mean
       __snake_case :   str													=    image_std
       __snake_case :   Optional[int]													=    do_rescale
       __snake_case :   List[Any]													=    rescale_factor
       __snake_case :   List[Any]													=    do_pad
 def A_   (   self						:							List[str]  )      ->   List[str]:







       '''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 A_   (   self						:							Union[str, Any]      ,     __a						:							Any      ,     __a						:							int=False  )      ->   Dict:







       '''simple docstring'''
       if not batched:
             __snake_case :   Dict													=    image_inputs[0]
             if isinstance(__a      ,     Image.Image  ):
                   __snake_case							,     __snake_case :   Optional[int]													=    image.size
             else:
                   __snake_case							,     __snake_case :   Any													=    image.shape[1], image.shape[2]
             if w < h:
                   __snake_case :   Optional[Any]													=    int(self.size['shortest_edge'] * h / w  )
                   __snake_case :   Tuple													=    self.size['shortest_edge']
             elif w > h:
                   __snake_case :   Tuple													=    self.size['shortest_edge']
                   __snake_case :   Any													=    int(self.size['shortest_edge'] * w / h  )
             else:
                   __snake_case :   int													=    self.size['shortest_edge']
                   __snake_case :   int													=    self.size['shortest_edge']

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

       return expected_height, expected_width



@require_torch
@require_vision
class  snake_case__						(    SCREAMING_SNAKE_CASE_  ,     unittest.TestCase				):
 A__				= DeformableDetrImageProcessor if is_vision_available() else None
 def A_   (   self						:							str  )      ->   Dict:







       '''simple docstring'''
       __snake_case :   Optional[Any]													=    DeformableDetrImageProcessingTester(self  )
 @property
 def A_   (   self						:							List[str]  )      ->   Union[str, Any]:







       '''simple docstring'''
       return self.image_processor_tester.prepare_image_processor_dict()
 def A_   (   self						:							str  )      ->   Tuple:







       '''simple docstring'''
       __snake_case :   str													=    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      ,     'do_rescale'  )  )
       self.assertTrue(hasattr(__a      ,     'do_pad'  )  )
       self.assertTrue(hasattr(__a      ,     'size'  )  )
 def A_   (   self						:							List[Any]  )      ->   Optional[Any]:







       '''simple docstring'''
       __snake_case :   str													=    self.image_processing_class.from_dict(self.image_processor_dict  )
       self.assertEqual(image_processor.size      ,     {'shortest_edge': 18, 'longest_edge': 1333}  )
       self.assertEqual(image_processor.do_pad      ,     __a  )

       __snake_case :   int													=    self.image_processing_class.from_dict(
           self.image_processor_dict      ,     size=42      ,     max_size=84      ,     pad_and_return_pixel_mask=__a  )
       self.assertEqual(image_processor.size      ,     {'shortest_edge': 42, 'longest_edge': 84}  )
       self.assertEqual(image_processor.do_pad      ,     __a  )
 def A_   (   self						:							Union[str, Any]  )      ->   Dict:







       '''simple docstring'''
       pass
 def A_   (   self						:							int  )      ->   Dict:







       '''simple docstring'''
       # Initialize image_processing
       __snake_case :   List[Any]													=    self.image_processing_class(**self.image_processor_dict  )
       # create random PIL images
       __snake_case :   List[str]													=    prepare_image_inputs(self.image_processor_tester      ,     equal_resolution=__a  )
       for image in image_inputs:
             self.assertIsInstance(__a      ,     Image.Image  )

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

       __snake_case							,     __snake_case :   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
       __snake_case							,     __snake_case :   List[Any]													=    self.image_processor_tester.get_expected_values(__a      ,     batched=__a  )

       __snake_case :   Optional[int]													=    image_processing(__a      ,     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 A_   (   self						:							Dict  )      ->   List[str]:







       '''simple docstring'''
       # Initialize image_processing
       __snake_case :   List[Any]													=    self.image_processing_class(**self.image_processor_dict  )
       # create random numpy tensors
       __snake_case :   Optional[int]													=    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
       __snake_case :   Tuple													=    image_processing(image_inputs[0]      ,     return_tensors='pt'  ).pixel_values

       __snake_case							,     __snake_case :   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
       __snake_case :   Union[str, Any]													=    image_processing(__a      ,     return_tensors='pt'  ).pixel_values

       __snake_case							,     __snake_case :   Union[str, 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 A_   (   self						:							Optional[int]  )      ->   int:







       '''simple docstring'''
       # Initialize image_processing
       __snake_case :   Optional[int]													=    self.image_processing_class(**self.image_processor_dict  )
       # create random PyTorch tensors
       __snake_case :   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
       __snake_case :   Any													=    image_processing(image_inputs[0]      ,     return_tensors='pt'  ).pixel_values

       __snake_case							,     __snake_case :   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
       __snake_case :   Union[str, Any]													=    image_processing(__a      ,     return_tensors='pt'  ).pixel_values

       __snake_case							,     __snake_case :   Optional[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,
           )      ,     )
 @slow
 def A_   (   self						:							Union[str, Any]  )      ->   Optional[Any]:







       '''simple docstring'''
       # prepare image and target
       __snake_case :   str													=    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
       with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt'      ,     'r'  ) as f:
             __snake_case :   Union[str, Any]													=    json.loads(f.read()  )

       __snake_case :   List[Any]													=    {'image_id': 39769, 'annotations': target}

       # encode them
       __snake_case :   Dict													=    DeformableDetrImageProcessor()
       __snake_case :   Any													=    image_processing(images=__a      ,     annotations=__a      ,     return_tensors='pt'  )

       # verify pixel values
       __snake_case :   List[Any]													=    torch.Size([1, 3, 800, 1066]  )
       self.assertEqual(encoding['pixel_values'].shape      ,     __a  )

       __snake_case :   int													=    torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]  )
       self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]      ,     __a      ,     atol=1e-4  )  )

       # verify area
       __snake_case :   Tuple													=    torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['area']      ,     __a  )  )
       # verify boxes
       __snake_case :   Tuple													=    torch.Size([6, 4]  )
       self.assertEqual(encoding['labels'][0]['boxes'].shape      ,     __a  )
       __snake_case :   Any													=    torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]      ,     __a      ,     atol=1e-3  )  )
       # verify image_id
       __snake_case :   Union[str, Any]													=    torch.tensor([39769]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']      ,     __a  )  )
       # verify is_crowd
       __snake_case :   Optional[int]													=    torch.tensor([0, 0, 0, 0, 0, 0]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']      ,     __a  )  )
       # verify class_labels
       __snake_case :   List[str]													=    torch.tensor([75, 75, 63, 65, 17, 17]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']      ,     __a  )  )
       # verify orig_size
       __snake_case :   str													=    torch.tensor([480, 640]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']      ,     __a  )  )
       # verify size
       __snake_case :   Any													=    torch.tensor([800, 1066]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['size']      ,     __a  )  )





 @slow
 def A_   (   self						:							List[str]  )      ->   Tuple:







       '''simple docstring'''
       # prepare image, target and masks_path
       __snake_case :   Any													=    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
       with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt'      ,     'r'  ) as f:
             __snake_case :   Optional[int]													=    json.loads(f.read()  )

       __snake_case :   Optional[Any]													=    {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target}

       __snake_case :   List[Any]													=    pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic'  )

       # encode them
       __snake_case :   List[Any]													=    DeformableDetrImageProcessor(format='coco_panoptic'  )
       __snake_case :   Optional[int]													=    image_processing(images=__a      ,     annotations=__a      ,     masks_path=__a      ,     return_tensors='pt'  )

       # verify pixel values
       __snake_case :   Dict													=    torch.Size([1, 3, 800, 1066]  )
       self.assertEqual(encoding['pixel_values'].shape      ,     __a  )

       __snake_case :   Optional[int]													=    torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]  )
       self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]      ,     __a      ,     atol=1e-4  )  )

       # verify area
       __snake_case :   int													=    torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['area']      ,     __a  )  )
       # verify boxes
       __snake_case :   str													=    torch.Size([6, 4]  )
       self.assertEqual(encoding['labels'][0]['boxes'].shape      ,     __a  )
       __snake_case :   List[Any]													=    torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]      ,     __a      ,     atol=1e-3  )  )
       # verify image_id
       __snake_case :   int													=    torch.tensor([39769]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']      ,     __a  )  )
       # verify is_crowd
       __snake_case :   str													=    torch.tensor([0, 0, 0, 0, 0, 0]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']      ,     __a  )  )
       # verify class_labels
       __snake_case :   Dict													=    torch.tensor([17, 17, 63, 75, 75, 93]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']      ,     __a  )  )
       # verify masks
       __snake_case :   Any													=    822873
       self.assertEqual(encoding['labels'][0]['masks'].sum().item()      ,     __a  )
       # verify orig_size
       __snake_case :   Any													=    torch.tensor([480, 640]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']      ,     __a  )  )
       # verify size
       __snake_case :   int													=    torch.tensor([800, 1066]  )
       self.assertTrue(torch.allclose(encoding['labels'][0]['size']      ,     __a  )  )








'''simple docstring'''





import copy

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


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



class  snake_case__						(    SCREAMING_SNAKE_CASE_				):
 A__				= '''upernet'''
 def __init__(   self						:							Optional[int]      ,     __a						:							Dict=None      ,     __a						:							List[str]=512      ,     __a						:							int=0.0_2      ,     __a						:							Optional[Any]=[1, 2, 3, 6]      ,     __a						:							Union[str, Any]=True      ,     __a						:							Any=0.4      ,     __a						:							int=384      ,     __a						:							int=256      ,     __a						:							str=1      ,     __a						:							List[Any]=False      ,     __a						:							Dict=255      ,     **__a						:							Dict      ,     )      ->   Optional[int]:







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

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

       __snake_case :   Any													=    backbone_config
       __snake_case :   Tuple													=    hidden_size
       __snake_case :   str													=    initializer_range
       __snake_case :   Dict													=    pool_scales
       __snake_case :   Optional[Any]													=    use_auxiliary_head
       __snake_case :   Optional[Any]													=    auxiliary_loss_weight
       __snake_case :   Optional[int]													=    auxiliary_in_channels
       __snake_case :   Dict													=    auxiliary_channels
       __snake_case :   Any													=    auxiliary_num_convs
       __snake_case :   Optional[Any]													=    auxiliary_concat_input
       __snake_case :   List[str]													=    loss_ignore_index





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







       '''simple docstring'''
       __snake_case :   Union[str, Any]													=    copy.deepcopy(self.__dict__  )
       __snake_case :   str													=    self.backbone_config.to_dict()
       __snake_case :   Optional[int]													=    self.__class__.model_type
       return output



