

import unittest

import numpy as np
import requests

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

      from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
      __lowercase				      =						False

if is_vision_available():
      from PIL import Image

      from transformers import PixaStructImageProcessor

class    _lowercase				(					unittest.TestCase			):

   def __init__(				self	:    str			,						lowerCamelCase__	:    str			,						lowerCamelCase__	:    List[Any]=7			,						lowerCamelCase__	:    List[str]=3			,						lowerCamelCase__	:    Optional[int]=1_8			,						lowerCamelCase__	:    Union[str, Any]=3_0			,						lowerCamelCase__	:    Union[str, Any]=4_0_0			,						lowerCamelCase__	:    Optional[Any]=None			,						lowerCamelCase__	:    Optional[Any]=True			,						lowerCamelCase__	:    Tuple=True			,						lowerCamelCase__	:    Optional[Any]=None			,						) ->			Dict:
         """simple docstring"""





         A_							       =		size if size is not None else {'''height''': 2_0, '''width''': 2_0}
         A_							       =		parent
         A_							       =		batch_size
         A_							       =		num_channels
         A_							       =		image_size
         A_							       =		min_resolution
         A_							       =		max_resolution
         A_							       =		size
         A_							       =		do_normalize
         A_							       =		do_convert_rgb
         A_							       =		[5_1_2, 1_0_2_4, 2_0_4_8, 4_0_9_6]
         A_							       =		patch_size if patch_size is not None else {'''height''': 1_6, '''width''': 1_6}

   def     UpperCamelCase					(				self	:    str       ) ->			int:
         """simple docstring"""





         return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}





   def     UpperCamelCase					(				self	:    List[Any]       ) ->			Any:
         """simple docstring"""





         A_							       =		'''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
         A_							       =		Image.open(requests.get(lowerCamelCase__			,						stream=lowerCamelCase__       ).raw       ).convert('''RGB'''       )
         return raw_image



@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11,reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.',)
@require_torch
@require_vision
class    _lowercase				(					__lowerCamelCase,unittest.TestCase			):
   _lowercase     :       Tuple  					=    PixaStructImageProcessor if is_vision_available() else None

   def     UpperCamelCase					(				self	:    Optional[Any]       ) ->			List[str]:
         """simple docstring"""





         A_							       =		PixaStructImageProcessingTester(self       )

   @property
   def     UpperCamelCase					(				self	:    List[str]       ) ->			str:
         """simple docstring"""





         return self.image_processor_tester.prepare_image_processor_dict()

   def     UpperCamelCase					(				self	:    Optional[int]       ) ->			List[Any]:
         """simple docstring"""





         A_							       =		self.image_processing_class(**self.image_processor_dict       )
         self.assertTrue(hasattr(lowerCamelCase__			,						'''do_normalize'''       )       )
         self.assertTrue(hasattr(lowerCamelCase__			,						'''do_convert_rgb'''       )       )

   def     UpperCamelCase					(				self	:    Optional[Any]       ) ->			Union[str, Any]:
         """simple docstring"""





         A_							       =		self.image_processor_tester.prepare_dummy_image()

         A_							       =		self.image_processing_class(**self.image_processor_dict       )
         A_							       =		2_0_4_8

         A_							       =		image_processor(lowerCamelCase__			,						return_tensors='''pt'''			,						max_patches=lowerCamelCase__       )
         self.assertTrue(torch.allclose(inputs.flattened_patches.mean()			,						torch.tensor(0.0606       )			,						atol=1e-3			,						rtol=1e-3       )       )

   def     UpperCamelCase					(				self	:    Union[str, Any]       ) ->			Optional[int]:
         """simple docstring"""





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

         # Test not batched input
         A_							       =		(
             (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
             * self.image_processor_tester.num_channels
         ) + 2

         for max_patch in self.image_processor_tester.max_patches:
               # Test not batched input
               A_							       =		image_processor(
                   image_inputs[0]			,						return_tensors='''pt'''			,						max_patches=lowerCamelCase__       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape			,						(1, max_patch, expected_hidden_dim)			,						)

               # Test batched
               A_							       =		image_processor(
                   lowerCamelCase__			,						return_tensors='''pt'''			,						max_patches=lowerCamelCase__       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape			,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,						)

   def     UpperCamelCase					(				self	:    Any       ) ->			Dict:
         """simple docstring"""





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

         # Test not batched input
         A_							       =		(
             (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
             * self.image_processor_tester.num_channels
         ) + 2

         A_							       =		True

         for max_patch in self.image_processor_tester.max_patches:
               # Test not batched input
               with self.assertRaises(lowerCamelCase__       ):
                     A_							       =		image_processor(
                         image_inputs[0]			,						return_tensors='''pt'''			,						max_patches=lowerCamelCase__       ).flattened_patches

               A_							       =		'''Hello'''

               A_							       =		image_processor(
                   image_inputs[0]			,						return_tensors='''pt'''			,						max_patches=lowerCamelCase__			,						header_text=lowerCamelCase__       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape			,						(1, max_patch, expected_hidden_dim)			,						)

               # Test batched
               A_							       =		image_processor(
                   lowerCamelCase__			,						return_tensors='''pt'''			,						max_patches=lowerCamelCase__			,						header_text=lowerCamelCase__       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape			,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,						)

   def     UpperCamelCase					(				self	:    Optional[int]       ) ->			Any:
         """simple docstring"""





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

         A_							       =		(
             (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
             * self.image_processor_tester.num_channels
         ) + 2

         for max_patch in self.image_processor_tester.max_patches:
               # Test not batched input
               A_							       =		image_processor(
                   image_inputs[0]			,						return_tensors='''pt'''			,						max_patches=lowerCamelCase__       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape			,						(1, max_patch, expected_hidden_dim)			,						)

               # Test batched
               A_							       =		image_processor(
                   lowerCamelCase__			,						return_tensors='''pt'''			,						max_patches=lowerCamelCase__       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape			,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,						)





   def     UpperCamelCase					(				self	:    Union[str, Any]       ) ->			List[str]:
         """simple docstring"""





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

         # Test not batched input
         A_							       =		(
             (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
             * self.image_processor_tester.num_channels
         ) + 2

         for max_patch in self.image_processor_tester.max_patches:
               # Test not batched input
               A_							       =		image_processor(
                   image_inputs[0]			,						return_tensors='''pt'''			,						max_patches=lowerCamelCase__       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape			,						(1, max_patch, expected_hidden_dim)			,						)

               # Test batched
               A_							       =		image_processor(
                   lowerCamelCase__			,						return_tensors='''pt'''			,						max_patches=lowerCamelCase__       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape			,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,						)



@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11,reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.',)
@require_torch
@require_vision
class    _lowercase				(					__lowerCamelCase,unittest.TestCase			):
   _lowercase     :       Any  					=    PixaStructImageProcessor if is_vision_available() else None

   def     UpperCamelCase					(				self	:    Optional[int]       ) ->			int:
         """simple docstring"""





         A_							       =		PixaStructImageProcessingTester(self			,						num_channels=4       )
         A_							       =		3

   @property
   def     UpperCamelCase					(				self	:    List[str]       ) ->			List[Any]:
         """simple docstring"""





         return self.image_processor_tester.prepare_image_processor_dict()

   def     UpperCamelCase					(				self	:    str       ) ->			List[Any]:
         """simple docstring"""





         A_							       =		self.image_processing_class(**self.image_processor_dict       )
         self.assertTrue(hasattr(lowerCamelCase__			,						'''do_normalize'''       )       )
         self.assertTrue(hasattr(lowerCamelCase__			,						'''do_convert_rgb'''       )       )





   def     UpperCamelCase					(				self	:    Any       ) ->			List[Any]:
         """simple docstring"""





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

         # Test not batched input
         A_							       =		(
             (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
             * (self.image_processor_tester.num_channels - 1)
         ) + 2

         for max_patch in self.image_processor_tester.max_patches:
               # Test not batched input
               A_							       =		image_processor(
                   image_inputs[0]			,						return_tensors='''pt'''			,						max_patches=lowerCamelCase__       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape			,						(1, max_patch, expected_hidden_dim)			,						)

               # Test batched
               A_							       =		image_processor(
                   lowerCamelCase__			,						return_tensors='''pt'''			,						max_patches=lowerCamelCase__       ).flattened_patches
               self.assertEqual(
                   encoded_images.shape			,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,						)








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


__lowercase				      =						logging.get_logger(__name__)

__lowercase				      =						{
    """microsoft/table-transformer-detection""": (
        """https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json"""
    ),
}

class    _lowercase				(					__lowerCamelCase			):
   _lowercase     :       Any  					=    'table-transformer'
   _lowercase     :       List[Any]  					=    ['past_key_values']
   _lowercase     :       Union[str, Any]  					=    {
       'hidden_size': 'd_model',
       'num_attention_heads': 'encoder_attention_heads',
   }

   def __init__(				self	:    List[Any]			,						lowerCamelCase__	:    Any=True			,						lowerCamelCase__	:    List[Any]=None			,						lowerCamelCase__	:    Any=3			,						lowerCamelCase__	:    Any=1_0_0			,						lowerCamelCase__	:    int=6			,						lowerCamelCase__	:    List[Any]=2_0_4_8			,						lowerCamelCase__	:    List[str]=8			,						lowerCamelCase__	:    int=6			,						lowerCamelCase__	:    List[str]=2_0_4_8			,						lowerCamelCase__	:    Optional[int]=8			,						lowerCamelCase__	:    Union[str, Any]=0.0			,						lowerCamelCase__	:    Any=0.0			,						lowerCamelCase__	:    str=True			,						lowerCamelCase__	:    Optional[Any]="relu"			,						lowerCamelCase__	:    Optional[int]=2_5_6			,						lowerCamelCase__	:    List[str]=0.1			,						lowerCamelCase__	:    str=0.0			,						lowerCamelCase__	:    Optional[int]=0.0			,						lowerCamelCase__	:    Dict=0.02			,						lowerCamelCase__	:    Union[str, Any]=1.0			,						lowerCamelCase__	:    Union[str, Any]=False			,						lowerCamelCase__	:    Optional[int]="sine"			,						lowerCamelCase__	:    str="resnet50"			,						lowerCamelCase__	:    List[str]=True			,						lowerCamelCase__	:    Optional[Any]=False			,						lowerCamelCase__	:    Any=1			,						lowerCamelCase__	:    int=5			,						lowerCamelCase__	:    Union[str, Any]=2			,						lowerCamelCase__	:    List[str]=1			,						lowerCamelCase__	:    Union[str, Any]=1			,						lowerCamelCase__	:    Optional[Any]=5			,						lowerCamelCase__	:    Tuple=2			,						lowerCamelCase__	:    List[str]=0.1			,						**lowerCamelCase__	:    List[str]			,						) ->			Dict:
         """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.'''       )
                     A_							       =		CONFIG_MAPPING['''resnet'''](out_features=['''stage4''']       )
               elif isinstance(lowerCamelCase__			,						lowerCamelCase__       ):
                     A_							       =		backbone_config.get('''model_type'''       )
                     A_							       =		CONFIG_MAPPING[backbone_model_type]
                     A_							       =		config_class.from_dict(lowerCamelCase__       )
               # set timm attributes to None
               A_       ,A_       ,A_							       =		None, None, None

         A_							       =		use_timm_backbone
         A_							       =		backbone_config
         A_							       =		num_channels
         A_							       =		num_queries
         A_							       =		d_model
         A_							       =		encoder_ffn_dim
         A_							       =		encoder_layers
         A_							       =		encoder_attention_heads
         A_							       =		decoder_ffn_dim
         A_							       =		decoder_layers
         A_							       =		decoder_attention_heads
         A_							       =		dropout
         A_							       =		attention_dropout
         A_							       =		activation_dropout
         A_							       =		activation_function
         A_							       =		init_std
         A_							       =		init_xavier_std
         A_							       =		encoder_layerdrop
         A_							       =		decoder_layerdrop
         A_							       =		encoder_layers
         A_							       =		auxiliary_loss
         A_							       =		position_embedding_type
         A_							       =		backbone
         A_							       =		use_pretrained_backbone
         A_							       =		dilation
         # Hungarian matcher
         A_							       =		class_cost
         A_							       =		bbox_cost
         A_							       =		giou_cost
         # Loss coefficients
         A_							       =		mask_loss_coefficient
         A_							       =		dice_loss_coefficient
         A_							       =		bbox_loss_coefficient
         A_							       =		giou_loss_coefficient
         A_							       =		eos_coefficient
         super().__init__(is_encoder_decoder=lowerCamelCase__			,						**lowerCamelCase__       )

   @property
   def     UpperCamelCase					(				self	:    Optional[Any]       ) ->			int:
         """simple docstring"""





         return self.encoder_attention_heads





   @property
   def     UpperCamelCase					(				self	:    Any       ) ->			int:
         """simple docstring"""





         return self.d_model



class    _lowercase				(					__lowerCamelCase			):
   _lowercase     :       Tuple  					=    version.parse('1.11'			)

   @property
   def     UpperCamelCase					(				self	:    Any       ) ->			Mapping[str, Mapping[int, str]]:
         """simple docstring"""





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

   @property
   def     UpperCamelCase					(				self	:    List[Any]       ) ->			float:
         """simple docstring"""





         return 1e-5





   @property
   def     UpperCamelCase					(				self	:    List[Any]       ) ->			int:
         """simple docstring"""





         return 1_2





