
"""simple docstring"""




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   _lowercase						(       unittest.TestCase				):



     def __init__(      self ,			__UpperCamelCase ,			__UpperCamelCase = True ,			__UpperCamelCase = None ,			__UpperCamelCase = 32 ,			__UpperCamelCase = True ,			__UpperCamelCase = 1 / 2_55 ,			__UpperCamelCase = True ,			__UpperCamelCase = True ,			__UpperCamelCase = [0.4814_5466, 0.457_8275, 0.4082_1073] ,			__UpperCamelCase = [0.2686_2954, 0.2613_0258, 0.2757_7711] ,			__UpperCamelCase = True ,			__UpperCamelCase=7 ,			__UpperCamelCase=30 ,			__UpperCamelCase=4_00 ,			__UpperCamelCase=3 ,			)->					List[str]:
          UpperCAmelCase__							: List[str] 							=						parent
          UpperCAmelCase__							: Any 							=						do_resize
          UpperCAmelCase__							: Tuple 							=						size if size is not None else {"shortest_edge": 2_88}
          UpperCAmelCase__							: int 							=						size_divisor
          UpperCAmelCase__							: Optional[int] 							=						do_rescale
          UpperCAmelCase__							: int 							=						rescale_factor
          UpperCAmelCase__							: Optional[int] 							=						do_normalize
          UpperCAmelCase__							: List[Any] 							=						do_center_crop
          UpperCAmelCase__							: Optional[int] 							=						image_mean
          UpperCAmelCase__							: Any 							=						image_std
          UpperCAmelCase__							: Union[str, Any] 							=						do_pad
          UpperCAmelCase__							: str 							=						batch_size
          UpperCAmelCase__							: Union[str, Any] 							=						num_channels
          UpperCAmelCase__							: str 							=						min_resolution
          UpperCAmelCase__							: Optional[Any] 							=						max_resolution



     def  lowerCAmelCase__       (      self  )->					Tuple:
          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  lowerCAmelCase__       (      self ,			__UpperCamelCase ,			__UpperCamelCase=False  )->					Dict:
          if not batched:
               UpperCAmelCase__							: str 							=						self.size["shortest_edge"]
               UpperCAmelCase__							: List[Any] 							=						image_inputs[0]
               if isinstance(__UpperCamelCase ,			Image.Image  ):
                    UpperCAmelCase__							: str 							=						image.size
               else:
                    UpperCAmelCase__							: Union[str, Any] 							=						image.shape[1], image.shape[2]
               UpperCAmelCase__							: List[str] 							=						size / min(__UpperCamelCase ,			__UpperCamelCase  )
               if h < w:
                    UpperCAmelCase__							: Dict 							=						size, scale * w
               else:
                    UpperCAmelCase__							: Optional[Any] 							=						scale * h, size

               UpperCAmelCase__							: List[Any] 							=						int((13_33 / 8_00) * size  )
               if max(__UpperCamelCase ,			__UpperCamelCase  ) > max_size:
                    UpperCAmelCase__							: int 							=						max_size / max(__UpperCamelCase ,			__UpperCamelCase  )
                    UpperCAmelCase__							: Any 							=						newh * scale
                    UpperCAmelCase__							: Union[str, Any] 							=						neww * scale

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

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

          return expected_height, expected_width







@require_torch
@require_vision
class   _lowercase						(       lowerCAmelCase_	,   unittest.TestCase				):
     _A								=							BridgeTowerImageProcessor if is_vision_available() else None



     def  lowerCAmelCase__       (      self  )->					Optional[Any]:
          UpperCAmelCase__							: str 							=						BridgeTowerImageProcessingTester(self  )



     @property
     def  lowerCAmelCase__       (      self  )->					Union[str, Any]:
          return self.image_processor_tester.prepare_image_processor_dict()



     def  lowerCAmelCase__       (      self  )->					str:
          UpperCAmelCase__							: Optional[int] 							=						self.image_processing_class(**self.image_processor_dict  )
          self.assertTrue(hasattr(__UpperCamelCase ,			"image_mean"  )  )
          self.assertTrue(hasattr(__UpperCamelCase ,			"image_std"  )  )
          self.assertTrue(hasattr(__UpperCamelCase ,			"do_normalize"  )  )
          self.assertTrue(hasattr(__UpperCamelCase ,			"do_resize"  )  )
          self.assertTrue(hasattr(__UpperCamelCase ,			"size"  )  )
          self.assertTrue(hasattr(__UpperCamelCase ,			"size_divisor"  )  )



     def  lowerCAmelCase__       (      self  )->					Optional[int]:
          pass



     def  lowerCAmelCase__       (      self  )->					Any:
          # Initialize image processor
          UpperCAmelCase__							: str 							=						self.image_processing_class(**self.image_processor_dict  )
          # create random PIL images
          UpperCAmelCase__							: int 							=						prepare_image_inputs(self.image_processor_tester ,			equal_resolution=__UpperCamelCase  )
          for image in image_inputs:
               self.assertIsInstance(__UpperCamelCase ,			Image.Image  )

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

          UpperCAmelCase__							: List[str] 							=						self.image_processor_tester.get_expected_values(__UpperCamelCase  )
          self.assertEqual(
              encoded_images.shape ,			(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,			)

          # Test batched
          UpperCAmelCase__							: Union[str, Any] 							=						image_processing(__UpperCamelCase ,			return_tensors="pt"  ).pixel_values

          UpperCAmelCase__							: Optional[Any] 							=						self.image_processor_tester.get_expected_values(__UpperCamelCase ,			batched=__UpperCamelCase  )
          self.assertEqual(
              encoded_images.shape ,			(
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  expected_height,
                  expected_width,
              ) ,			)



     def  lowerCAmelCase__       (      self  )->					List[Any]:
          # Initialize image processor
          UpperCAmelCase__							: Dict 							=						self.image_processing_class(**self.image_processor_dict  )
          # create random numpy tensors
          UpperCAmelCase__							: Optional[int] 							=						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
          UpperCAmelCase__							: Dict 							=						image_processing(image_inputs[0] ,			return_tensors="pt"  ).pixel_values

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

          # Test batched
          UpperCAmelCase__							: Optional[int] 							=						image_processing(__UpperCamelCase ,			return_tensors="pt"  ).pixel_values

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



     def  lowerCAmelCase__       (      self  )->					Any:
          # Initialize image processor
          UpperCAmelCase__							: Tuple 							=						self.image_processing_class(**self.image_processor_dict  )
          # create random PyTorch tensors
          UpperCAmelCase__							: 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
          UpperCAmelCase__							: Any 							=						image_processing(image_inputs[0] ,			return_tensors="pt"  ).pixel_values

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

          # Test batched
          UpperCAmelCase__							: Optional[int] 							=						image_processing(__UpperCamelCase ,			return_tensors="pt"  ).pixel_values

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





"""simple docstring"""




from collections import OrderedDict
from typing import Mapping

from packaging import version

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


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

A__      :	Optional[int]          =    {
    """microsoft/table-transformer-detection""": (
        """https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json"""
    ),
}







class   _lowercase						(       lowerCAmelCase_				):


     '''simple docstring'''





     _A								=							'table-transformer'
     _A								=							['past_key_values']
     _A								=							{
         'hidden_size': 'd_model',
         'num_attention_heads': 'encoder_attention_heads',
     }



     def __init__(      self ,			__UpperCamelCase=True ,			__UpperCamelCase=None ,			__UpperCamelCase=3 ,			__UpperCamelCase=1_00 ,			__UpperCamelCase=6 ,			__UpperCamelCase=20_48 ,			__UpperCamelCase=8 ,			__UpperCamelCase=6 ,			__UpperCamelCase=20_48 ,			__UpperCamelCase=8 ,			__UpperCamelCase=0.0 ,			__UpperCamelCase=0.0 ,			__UpperCamelCase=True ,			__UpperCamelCase="relu" ,			__UpperCamelCase=2_56 ,			__UpperCamelCase=0.1 ,			__UpperCamelCase=0.0 ,			__UpperCamelCase=0.0 ,			__UpperCamelCase=0.02 ,			__UpperCamelCase=1.0 ,			__UpperCamelCase=False ,			__UpperCamelCase="sine" ,			__UpperCamelCase="resnet50" ,			__UpperCamelCase=True ,			__UpperCamelCase=False ,			__UpperCamelCase=1 ,			__UpperCamelCase=5 ,			__UpperCamelCase=2 ,			__UpperCamelCase=1 ,			__UpperCamelCase=1 ,			__UpperCamelCase=5 ,			__UpperCamelCase=2 ,			__UpperCamelCase=0.1 ,			**__UpperCamelCase ,			)->					List[Any]:
          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."  )
                    UpperCAmelCase__							: Any 							=						CONFIG_MAPPING["resnet"](out_features=["stage4"]  )
               elif isinstance(__UpperCamelCase ,			__UpperCamelCase  ):
                    UpperCAmelCase__							: int 							=						backbone_config.get("model_type"  )
                    UpperCAmelCase__							: Optional[Any] 							=						CONFIG_MAPPING[backbone_model_type]
                    UpperCAmelCase__							: int 							=						config_class.from_dict(__UpperCamelCase  )
               # set timm attributes to None
               UpperCAmelCase__							,	UpperCAmelCase__							,	UpperCAmelCase__							: List[str] 							=						None, None, None

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



     @property
     def  lowerCAmelCase__       (      self  )->					int:
          return self.encoder_attention_heads



     @property
     def  lowerCAmelCase__       (      self  )->					int:
          return self.d_model







class   _lowercase						(       lowerCAmelCase_				):


     '''simple docstring'''





     _A								=							version.parse('1.11'				)



     @property
     def  lowerCAmelCase__       (      self  )->					Mapping[str, Mapping[int, str]]:
          return OrderedDict(
              [
                  ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
                  ("pixel_mask", {0: "batch"}),
              ]  )



     @property
     def  lowerCAmelCase__       (      self  )->					float:
          return 1E-5



     @property
     def  lowerCAmelCase__       (      self  )->					int:
          return 12



