


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



  """simple docstring"""



  def __init__( self			:  int				,				lowerCamelCase__			:  List[str]				,				lowerCamelCase__			:  str=7				,				lowerCamelCase__			:  Optional[Any]=3				,				lowerCamelCase__			:  Dict=30				,				lowerCamelCase__			:  Optional[int]=400				,				lowerCamelCase__			:  str=True				,				lowerCamelCase__			:  List[Any]=None				,				lowerCamelCase__			:  Dict=True				,				lowerCamelCase__			:  List[str]=[0.5, 0.5, 0.5]				,				lowerCamelCase__			:  Optional[int]=[0.5, 0.5, 0.5]				,				lowerCamelCase__			:  List[Any]=True				,				lowerCamelCase__			:  List[str]=1 / 255				,				lowerCamelCase__			:  str=True				,				):
        # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
        a__	:  List[str]     =   size if size is not None else {"shortest_edge": 18, "longest_edge": 1_333}
        a__	:  Optional[Any]     =   parent
        a__	:  Union[str, Any]     =   batch_size
        a__	:  Tuple     =   num_channels
        a__	:  Union[str, Any]     =   min_resolution
        a__	:  Union[str, Any]     =   max_resolution
        a__	:  Union[str, Any]     =   do_resize
        a__	:  Tuple     =   size
        a__	:  str     =   do_normalize
        a__	:  Optional[int]     =   image_mean
        a__	:  Optional[Any]     =   image_std
        a__	:  str     =   do_rescale
        a__	:  Dict     =   rescale_factor
        a__	:  int     =   do_pad

  def    _UpperCamelCase( self			:  str       ):
        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    _UpperCamelCase( self			:  Dict				,				lowerCamelCase__			:  Any				,				lowerCamelCase__			:  Tuple=False       ):
        if not batched:
              a__	:  str     =   image_inputs[0]
              if isinstance(lowerCamelCase__				,				Image.Image       ):
                    a__,	a__	:  Tuple     =   image.size
              else:
                    a__,	a__	:  int     =   image.shape[1], image.shape[2]
              if w < h:
                    a__	:  str     =   int(self.size["shortest_edge"] * h / w       )
                    a__	:  int     =   self.size["shortest_edge"]
              elif w > h:
                    a__	:  int     =   self.size["shortest_edge"]
                    a__	:  Dict     =   int(self.size["shortest_edge"] * w / h       )
              else:
                    a__	:  Dict     =   self.size["shortest_edge"]
                    a__	:  Tuple     =   self.size["shortest_edge"]

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

        return expected_height, expected_width




@require_torch
@require_vision
class A__     ( A__				,		unittest.TestCase  ):



  """simple docstring"""



  _lowercase									=		ConditionalDetrImageProcessor if is_vision_available() else None

  def    _UpperCamelCase( self			:  Optional[int]       ):
        a__	:  Tuple     =   ConditionalDetrImageProcessingTester(self       )

  @property
  def    _UpperCamelCase( self			:  Dict       ):
        return self.image_processor_tester.prepare_image_processor_dict()

  def    _UpperCamelCase( self			:  Optional[Any]       ):
        a__	:  List[str]     =   self.image_processing_class(**self.image_processor_dict       )
        self.assertTrue(hasattr(lowerCamelCase__				,				"image_mean"       )       )
        self.assertTrue(hasattr(lowerCamelCase__				,				"image_std"       )       )
        self.assertTrue(hasattr(lowerCamelCase__				,				"do_normalize"       )       )
        self.assertTrue(hasattr(lowerCamelCase__				,				"do_resize"       )       )
        self.assertTrue(hasattr(lowerCamelCase__				,				"size"       )       )

  def    _UpperCamelCase( self			:  Tuple       ):
        a__	:  Any     =   self.image_processing_class.from_dict(self.image_processor_dict       )
        self.assertEqual(image_processor.size				,				{"shortest_edge": 18, "longest_edge": 1_333}       )
        self.assertEqual(image_processor.do_pad				,				lowerCamelCase__       )

        a__	:  str     =   self.image_processing_class.from_dict(
            self.image_processor_dict				,				size=42				,				max_size=84				,				pad_and_return_pixel_mask=lowerCamelCase__       )
        self.assertEqual(image_processor.size				,				{"shortest_edge": 42, "longest_edge": 84}       )
        self.assertEqual(image_processor.do_pad				,				lowerCamelCase__       )

  def    _UpperCamelCase( self			:  Any       ):
        pass

  def    _UpperCamelCase( self			:  Optional[Any]       ):
        # Initialize image_processing
        a__	:  int     =   self.image_processing_class(**self.image_processor_dict       )
        # create random PIL images
        a__	:  Optional[int]     =   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__	:  Any     =   image_processing(image_inputs[0]				,				return_tensors="pt"       ).pixel_values

        a__,	a__	:  Optional[Any]     =   self.image_processor_tester.get_expected_values(lowerCamelCase__       )

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

        # Test batched
        a__,	a__	:  Dict     =   self.image_processor_tester.get_expected_values(lowerCamelCase__				,				batched=lowerCamelCase__       )

        a__	:  Union[str, Any]     =   image_processing(lowerCamelCase__				,				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    _UpperCamelCase( self			:  str       ):
        # Initialize image_processing
        a__	:  List[Any]     =   self.image_processing_class(**self.image_processor_dict       )
        # create random numpy tensors
        a__	:  List[str]     =   prepare_image_inputs(self.image_processor_tester				,				equal_resolution=lowerCamelCase__				,				numpify=lowerCamelCase__       )
        for image in image_inputs:
              self.assertIsInstance(lowerCamelCase__				,				np.ndarray       )

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

        a__,	a__	:  Optional[int]     =   self.image_processor_tester.get_expected_values(lowerCamelCase__       )

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

        # Test batched
        a__	:  Any     =   image_processing(lowerCamelCase__				,				return_tensors="pt"       ).pixel_values

        a__,	a__	:  Optional[Any]     =   self.image_processor_tester.get_expected_values(lowerCamelCase__				,				batched=lowerCamelCase__       )

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

  def    _UpperCamelCase( self			:  Optional[Any]       ):
        # Initialize image_processing
        a__	:  List[str]     =   self.image_processing_class(**self.image_processor_dict       )
        # create random PyTorch tensors
        a__	:  List[Any]     =   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__	:  Dict     =   image_processing(image_inputs[0]				,				return_tensors="pt"       ).pixel_values

        a__,	a__	:  Union[str, Any]     =   self.image_processor_tester.get_expected_values(lowerCamelCase__       )

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

        # Test batched
        a__	:  Tuple     =   image_processing(lowerCamelCase__				,				return_tensors="pt"       ).pixel_values

        a__,	a__	:  Optional[Any]     =   self.image_processor_tester.get_expected_values(lowerCamelCase__				,				batched=lowerCamelCase__       )

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

  @slow
  def    _UpperCamelCase( self			:  Tuple       ):
        # prepare image and target
        a__	:  Optional[Any]     =   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
        with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt"				,				"r"       ) as f:
              a__	:  Tuple     =   json.loads(f.read()       )

        a__	:  Any     =   {"image_id": 39_769, "annotations": target}

        # encode them
        a__	:  List[str]     =   ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50"       )
        a__	:  str     =   image_processing(images=lowerCamelCase__				,				annotations=lowerCamelCase__				,				return_tensors="pt"       )

        # verify pixel values
        a__	:  Optional[Any]     =   torch.Size([1, 3, 800, 1_066]       )
        self.assertEqual(encoding["pixel_values"].shape				,				lowerCamelCase__       )

        a__	:  int     =   torch.tensor([0.2796, 0.3138, 0.3481]       )
        self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]				,				lowerCamelCase__				,				atol=1E-4       )       )

        # verify area
        a__	:  List[Any]     =   torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["area"]				,				lowerCamelCase__       )       )
        # verify boxes
        a__	:  Any     =   torch.Size([6, 4]       )
        self.assertEqual(encoding["labels"][0]["boxes"].shape				,				lowerCamelCase__       )
        a__	:  int     =   torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]				,				lowerCamelCase__				,				atol=1E-3       )       )
        # verify image_id
        a__	:  Any     =   torch.tensor([39_769]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]				,				lowerCamelCase__       )       )
        # verify is_crowd
        a__	:  Any     =   torch.tensor([0, 0, 0, 0, 0, 0]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]				,				lowerCamelCase__       )       )
        # verify class_labels
        a__	:  int     =   torch.tensor([75, 75, 63, 65, 17, 17]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]				,				lowerCamelCase__       )       )
        # verify orig_size
        a__	:  Union[str, Any]     =   torch.tensor([480, 640]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]				,				lowerCamelCase__       )       )
        # verify size
        a__	:  List[Any]     =   torch.tensor([800, 1_066]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["size"]				,				lowerCamelCase__       )       )

  @slow
  def    _UpperCamelCase( self			:  Optional[int]       ):
        # prepare image, target and masks_path
        a__	:  Union[str, Any]     =   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
        with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt"				,				"r"       ) as f:
              a__	:  int     =   json.loads(f.read()       )

        a__	:  Any     =   {"file_name": "000000039769.png", "image_id": 39_769, "segments_info": target}

        a__	:  Dict     =   pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic"       )

        # encode them
        a__	:  str     =   ConditionalDetrImageProcessor(format="coco_panoptic"       )
        a__	:  Optional[int]     =   image_processing(images=lowerCamelCase__				,				annotations=lowerCamelCase__				,				masks_path=lowerCamelCase__				,				return_tensors="pt"       )

        # verify pixel values
        a__	:  int     =   torch.Size([1, 3, 800, 1_066]       )
        self.assertEqual(encoding["pixel_values"].shape				,				lowerCamelCase__       )

        a__	:  Dict     =   torch.tensor([0.2796, 0.3138, 0.3481]       )
        self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]				,				lowerCamelCase__				,				atol=1E-4       )       )

        # verify area
        a__	:  Optional[int]     =   torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["area"]				,				lowerCamelCase__       )       )
        # verify boxes
        a__	:  int     =   torch.Size([6, 4]       )
        self.assertEqual(encoding["labels"][0]["boxes"].shape				,				lowerCamelCase__       )
        a__	:  Dict     =   torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]				,				lowerCamelCase__				,				atol=1E-3       )       )
        # verify image_id
        a__	:  Dict     =   torch.tensor([39_769]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]				,				lowerCamelCase__       )       )
        # verify is_crowd
        a__	:  Dict     =   torch.tensor([0, 0, 0, 0, 0, 0]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]				,				lowerCamelCase__       )       )
        # verify class_labels
        a__	:  str     =   torch.tensor([17, 17, 63, 75, 75, 93]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]				,				lowerCamelCase__       )       )
        # verify masks
        a__	:  Union[str, Any]     =   822_873
        self.assertEqual(encoding["labels"][0]["masks"].sum().item()				,				lowerCamelCase__       )
        # verify orig_size
        a__	:  int     =   torch.tensor([480, 640]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]				,				lowerCamelCase__       )       )
        # verify size
        a__	:  Dict     =   torch.tensor([800, 1_066]       )
        self.assertTrue(torch.allclose(encoding["labels"][0]["size"]				,				lowerCamelCase__       )       )







from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase__					:  str      							=				logging.get_logger(__name__)

lowerCamelCase__					:  Tuple      							=				{
    'funnel-transformer/small': 'https://huggingface.co/funnel-transformer/small/resolve/main/config.json',
    'funnel-transformer/small-base': 'https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json',
    'funnel-transformer/medium': 'https://huggingface.co/funnel-transformer/medium/resolve/main/config.json',
    'funnel-transformer/medium-base': 'https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json',
    'funnel-transformer/intermediate': (
        'https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json'
    ),
    'funnel-transformer/intermediate-base': (
        'https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json'
    ),
    'funnel-transformer/large': 'https://huggingface.co/funnel-transformer/large/resolve/main/config.json',
    'funnel-transformer/large-base': 'https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json',
    'funnel-transformer/xlarge': 'https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json',
    'funnel-transformer/xlarge-base': 'https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json',
}





class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE   ):


 '''simple docstring'''







 lowercase_							       =       "funnel"
 lowercase_							       =       {
     "hidden_size": "d_model",
     "num_attention_heads": "n_head",
 }



 def __init__(				self    :						int							,							_lowerCAmelCase    :						Optional[int]=30_522							,							_lowerCAmelCase    :						List[str]=[4, 4, 4]							,							_lowerCAmelCase    :						Tuple=None							,							_lowerCAmelCase    :						Optional[int]=2							,							_lowerCAmelCase    :						int=768							,							_lowerCAmelCase    :						Optional[Any]=12							,							_lowerCAmelCase    :						Optional[Any]=64							,							_lowerCAmelCase    :						Optional[Any]=3_072							,							_lowerCAmelCase    :						List[str]="gelu_new"							,							_lowerCAmelCase    :						Any=0.1							,							_lowerCAmelCase    :						int=0.1							,							_lowerCAmelCase    :						Tuple=0.0							,							_lowerCAmelCase    :						List[Any]=0.1							,							_lowerCAmelCase    :						Dict=None							,							_lowerCAmelCase    :						str=1E-9							,							_lowerCAmelCase    :						Any="mean"							,							_lowerCAmelCase    :						Union[str, Any]="relative_shift"							,							_lowerCAmelCase    :						Optional[Any]=True							,							_lowerCAmelCase    :						Dict=True							,							_lowerCAmelCase    :						Tuple=True							,							**_lowerCAmelCase    :						Optional[Any]							,							):
       SCREAMING_SNAKE_CASE_      		=     vocab_size
       SCREAMING_SNAKE_CASE_      		=     block_sizes
       SCREAMING_SNAKE_CASE_      		=     [1] * len(_lowerCAmelCase		) if block_repeats is None else block_repeats
       assert len(_lowerCAmelCase		) == len(
           self.block_repeats		), "`block_sizes` and `block_repeats` should have the same length."
       SCREAMING_SNAKE_CASE_      		=     num_decoder_layers
       SCREAMING_SNAKE_CASE_      		=     d_model
       SCREAMING_SNAKE_CASE_      		=     n_head
       SCREAMING_SNAKE_CASE_      		=     d_head
       SCREAMING_SNAKE_CASE_      		=     d_inner
       SCREAMING_SNAKE_CASE_      		=     hidden_act
       SCREAMING_SNAKE_CASE_      		=     hidden_dropout
       SCREAMING_SNAKE_CASE_      		=     attention_dropout
       SCREAMING_SNAKE_CASE_      		=     activation_dropout
       SCREAMING_SNAKE_CASE_      		=     initializer_range
       SCREAMING_SNAKE_CASE_      		=     initializer_std
       SCREAMING_SNAKE_CASE_      		=     layer_norm_eps
       assert pooling_type in [
           "mean",
           "max",
       ], F"Got {pooling_type} for `pooling_type` but only 'mean' and 'max' are supported."
       SCREAMING_SNAKE_CASE_      		=     pooling_type
       assert attention_type in [
           "relative_shift",
           "factorized",
       ], F"Got {attention_type} for `attention_type` but only 'relative_shift' and 'factorized' are supported."
       SCREAMING_SNAKE_CASE_      		=     attention_type
       SCREAMING_SNAKE_CASE_      		=     separate_cls
       SCREAMING_SNAKE_CASE_      		=     truncate_seq
       SCREAMING_SNAKE_CASE_      		=     pool_q_only

       super().__init__(**_lowerCAmelCase		)



 @property
 def  lowerCAmelCase_    (				self    :						Optional[int]		):
       return sum(self.block_sizes		)



 @num_hidden_layers.setter
 def  lowerCAmelCase_    (				self    :						int							,							_lowerCAmelCase    :						List[Any]		):
       raise NotImplementedError(
           'This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.'		)



 @property
 def  lowerCAmelCase_    (				self    :						List[Any]		):
       return len(self.block_sizes		)




 @num_blocks.setter
 def  lowerCAmelCase_    (				self    :						Dict							,							_lowerCAmelCase    :						Union[str, Any]		):
       raise NotImplementedError('This model does not support the setting of `num_blocks`. Please set `block_sizes`.'		)