

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 _UpperCamelCase							(							unittest.TestCase   ):
   '''simple docstring'''







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

    """simple docstring"""

    SCREAMING_SNAKE_CASE   :      List[str]				     =       size if size is not None else {"shortest_edge": 18, "longest_edge": 1333}
    SCREAMING_SNAKE_CASE   :      Dict				     =       parent
    SCREAMING_SNAKE_CASE   :      Optional[int]				     =       batch_size
    SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       num_channels
    SCREAMING_SNAKE_CASE   :      str				     =       min_resolution
    SCREAMING_SNAKE_CASE   :      Tuple				     =       max_resolution
    SCREAMING_SNAKE_CASE   :      List[Any]				     =       do_resize
    SCREAMING_SNAKE_CASE   :      Dict				     =       size
    SCREAMING_SNAKE_CASE   :      List[str]				     =       do_normalize
    SCREAMING_SNAKE_CASE   :      Optional[int]				     =       image_mean
    SCREAMING_SNAKE_CASE   :      Optional[int]				     =       image_std
    SCREAMING_SNAKE_CASE   :      Any				     =       do_rescale
    SCREAMING_SNAKE_CASE   :      Optional[int]				     =       rescale_factor
    SCREAMING_SNAKE_CASE   :      int				     =       do_pad
   def 							__UpperCamelCase (			self							: Dict	)							->       Optional[int]:

    """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 							__UpperCamelCase (			self							: Optional[int]      ,      a							: Dict      ,      a							: List[Any]=False	)							->       Any:

    """simple docstring"""

    if not batched:
     SCREAMING_SNAKE_CASE   :      List[str]				     =       image_inputs[0]
     if isinstance(__A      ,      Image.Image	):
      SCREAMING_SNAKE_CASE   :      Tuple				     =       image.size
     else:
      SCREAMING_SNAKE_CASE   :      List[str]				     =       image.shape[1], image.shape[2]
     if w < h:
      SCREAMING_SNAKE_CASE   :      Dict				     =       int(self.size["shortest_edge"] * h / w	)
      SCREAMING_SNAKE_CASE   :      Optional[int]				     =       self.size["shortest_edge"]
     elif w > h:
      SCREAMING_SNAKE_CASE   :      List[Any]				     =       self.size["shortest_edge"]
      SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       int(self.size["shortest_edge"] * w / h	)
     else:
      SCREAMING_SNAKE_CASE   :      Dict				     =       self.size["shortest_edge"]
      SCREAMING_SNAKE_CASE   :      Dict				     =       self.size["shortest_edge"]

    else:
     SCREAMING_SNAKE_CASE   :      str				     =       []
     for image in image_inputs:
      SCREAMING_SNAKE_CASE   :      str				     =       self.get_expected_values([image]	)
      expected_values.append((expected_height, expected_width)	)
     SCREAMING_SNAKE_CASE   :      Dict				     =       max(__A      ,      key=lambda a	: item[0]	)[0]
     SCREAMING_SNAKE_CASE   :      Tuple				     =       max(__A      ,      key=lambda a	: item[1]	)[1]

    return expected_height, expected_width






@require_torch
@require_vision
class _UpperCamelCase							(							UpperCamelCase_							,	unittest.TestCase   ):
   '''simple docstring'''







   lowerCamelCase__           =ConditionalDetrImageProcessor if is_vision_available() else None
   def 							__UpperCamelCase (			self							: int	)							->       int:

    """simple docstring"""

    SCREAMING_SNAKE_CASE   :      Tuple				     =       ConditionalDetrImageProcessingTester(self	)
   @property
   def 							__UpperCamelCase (			self							: Any	)							->       Tuple:

    """simple docstring"""

    return self.image_processor_tester.prepare_image_processor_dict()
   def 							__UpperCamelCase (			self							: Any	)							->       Optional[Any]:

    """simple docstring"""

    SCREAMING_SNAKE_CASE   :      Dict				     =       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      ,      "size"	)	)
   def 							__UpperCamelCase (			self							: List[str]	)							->       Optional[Any]:

    """simple docstring"""

    SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       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	)

    SCREAMING_SNAKE_CASE   :      Any				     =       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 							__UpperCamelCase (			self							: Union[str, Any]	)							->       int:

    """simple docstring"""

    pass
   def 							__UpperCamelCase (			self							: List[str]	)							->       List[str]:

    """simple docstring"""

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

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

    SCREAMING_SNAKE_CASE   :      Union[str, 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
    SCREAMING_SNAKE_CASE   :      Tuple				     =       self.image_processor_tester.get_expected_values(__A      ,      batched=__A	)

    SCREAMING_SNAKE_CASE   :      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 							__UpperCamelCase (			self							: Tuple	)							->       List[Any]:

    """simple docstring"""

    SCREAMING_SNAKE_CASE   :      List[str]				     =       self.image_processing_class(**self.image_processor_dict	)
    # create random numpy tensors
    SCREAMING_SNAKE_CASE   :      List[str]				     =       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
    SCREAMING_SNAKE_CASE   :      int				     =       image_processing(image_inputs[0]      ,      return_tensors="pt"	).pixel_values

    SCREAMING_SNAKE_CASE   :      Dict				     =       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
    SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       image_processing(__A      ,      return_tensors="pt"	).pixel_values

    SCREAMING_SNAKE_CASE   :      str				     =       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 							__UpperCamelCase (			self							: Tuple	)							->       str:

    """simple docstring"""

    SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       self.image_processing_class(**self.image_processor_dict	)
    # create random PyTorch tensors
    SCREAMING_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
    SCREAMING_SNAKE_CASE   :      Tuple				     =       image_processing(image_inputs[0]      ,      return_tensors="pt"	).pixel_values

    SCREAMING_SNAKE_CASE   :      Optional[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
    SCREAMING_SNAKE_CASE   :      Dict				     =       image_processing(__A      ,      return_tensors="pt"	).pixel_values

    SCREAMING_SNAKE_CASE   :      int				     =       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 							__UpperCamelCase (			self							: List[Any]	)							->       Dict:

    """simple docstring"""

    SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
    with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt"      ,      "r"	) as f:
     SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       json.loads(f.read()	)

    SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       {"image_id": 3_9769, "annotations": target}

    # encode them
    SCREAMING_SNAKE_CASE   :      Tuple				     =       ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50"	)
    SCREAMING_SNAKE_CASE   :      int				     =       image_processing(images=__A      ,      annotations=__A      ,      return_tensors="pt"	)

    # verify pixel values
    SCREAMING_SNAKE_CASE   :      str				     =       torch.Size([1, 3, 800, 1066]	)
    self.assertEqual(encoding["pixel_values"].shape      ,      __A	)

    SCREAMING_SNAKE_CASE   :      Tuple				     =       torch.tensor([0.2796, 0.3138, 0.3481]	)
    self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]      ,      __A      ,      atol=1e-4	)	)

    # verify area
    SCREAMING_SNAKE_CASE   :      Optional[int]				     =       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"]      ,      __A	)	)
    # verify boxes
    SCREAMING_SNAKE_CASE   :      Tuple				     =       torch.Size([6, 4]	)
    self.assertEqual(encoding["labels"][0]["boxes"].shape      ,      __A	)
    SCREAMING_SNAKE_CASE   :      List[Any]				     =       torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]	)
    self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]      ,      __A      ,      atol=1e-3	)	)
    # verify image_id
    SCREAMING_SNAKE_CASE   :      str				     =       torch.tensor([3_9769]	)
    self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]      ,      __A	)	)
    # verify is_crowd
    SCREAMING_SNAKE_CASE   :      List[Any]				     =       torch.tensor([0, 0, 0, 0, 0, 0]	)
    self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]      ,      __A	)	)
    # verify class_labels
    SCREAMING_SNAKE_CASE   :      Optional[int]				     =       torch.tensor([75, 75, 63, 65, 17, 17]	)
    self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]      ,      __A	)	)
    # verify orig_size
    SCREAMING_SNAKE_CASE   :      Dict				     =       torch.tensor([480, 640]	)
    self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]      ,      __A	)	)
    # verify size
    SCREAMING_SNAKE_CASE   :      List[str]				     =       torch.tensor([800, 1066]	)
    self.assertTrue(torch.allclose(encoding["labels"][0]["size"]      ,      __A	)	)






   @slow
   def 							__UpperCamelCase (			self							: str	)							->       int:

    """simple docstring"""

    SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
    with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt"      ,      "r"	) as f:
     SCREAMING_SNAKE_CASE   :      int				     =       json.loads(f.read()	)

    SCREAMING_SNAKE_CASE   :      Optional[int]				     =       {"file_name": "000000039769.png", "image_id": 3_9769, "segments_info": target}

    SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic"	)

    # encode them
    SCREAMING_SNAKE_CASE   :      Optional[int]				     =       ConditionalDetrImageProcessor(format="coco_panoptic"	)
    SCREAMING_SNAKE_CASE   :      Tuple				     =       image_processing(images=__A      ,      annotations=__A      ,      masks_path=__A      ,      return_tensors="pt"	)

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

    SCREAMING_SNAKE_CASE   :      List[str]				     =       torch.tensor([0.2796, 0.3138, 0.3481]	)
    self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]      ,      __A      ,      atol=1e-4	)	)

    # verify area
    SCREAMING_SNAKE_CASE   :      Tuple				     =       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"]      ,      __A	)	)
    # verify boxes
    SCREAMING_SNAKE_CASE   :      Dict				     =       torch.Size([6, 4]	)
    self.assertEqual(encoding["labels"][0]["boxes"].shape      ,      __A	)
    SCREAMING_SNAKE_CASE   :      int				     =       torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]	)
    self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]      ,      __A      ,      atol=1e-3	)	)
    # verify image_id
    SCREAMING_SNAKE_CASE   :      str				     =       torch.tensor([3_9769]	)
    self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]      ,      __A	)	)
    # verify is_crowd
    SCREAMING_SNAKE_CASE   :      Tuple				     =       torch.tensor([0, 0, 0, 0, 0, 0]	)
    self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]      ,      __A	)	)
    # verify class_labels
    SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       torch.tensor([17, 17, 63, 75, 75, 93]	)
    self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]      ,      __A	)	)
    # verify masks
    SCREAMING_SNAKE_CASE   :      str				     =       82_2873
    self.assertEqual(encoding["labels"][0]["masks"].sum().item()      ,      __A	)
    # verify orig_size
    SCREAMING_SNAKE_CASE   :      int				     =       torch.tensor([480, 640]	)
    self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]      ,      __A	)	)
    # verify size
    SCREAMING_SNAKE_CASE   :      List[Any]				     =       torch.tensor([800, 1066]	)
    self.assertTrue(torch.allclose(encoding["labels"][0]["size"]      ,      __A	)	)


from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
			import tensorflow as tf

			from transformers import TFCvtForImageClassification, TFCvtModel
			from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import AutoImageProcessor






class _UpperCamelCase							(							__A   ):
			'''simple docstring'''







			def 							__UpperCamelCase (			self							: Any	)							->       Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       self.config_class(**self.inputs_dict	)
				self.parent.assertTrue(hasattr(a      ,      "embed_dim"	)	)
				self.parent.assertTrue(hasattr(a      ,      "num_heads"	)	)






class _UpperCamelCase							:
			'''simple docstring'''







			def __init__(			self							: Dict      ,      a							: int      ,      a							: List[str]=13      ,      a							: Optional[int]=64      ,      a							: List[str]=3      ,      a							: Dict=[16, 48, 96]      ,      a							: List[Any]=[1, 3, 6]      ,      a							: int=[1, 2, 10]      ,      a							: List[str]=[7, 3, 3]      ,      a							: List[Any]=[4, 2, 2]      ,      a							: Tuple=[2, 1, 1]      ,      a							: Union[str, Any]=[2, 2, 2]      ,      a							: List[str]=[False, False, True]      ,      a							: int=[0.0, 0.0, 0.0]      ,      a							: Dict=0.02      ,      a							: List[Any]=1e-12      ,      a							: Tuple=True      ,      a							: Optional[int]=True      ,      a							: Union[str, Any]=2      ,      )							->       Any:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Tuple				     =       parent
				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       batch_size
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       image_size
				SCREAMING_SNAKE_CASE   :      Dict				     =       patch_sizes
				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       patch_stride
				SCREAMING_SNAKE_CASE   :      str				     =       patch_padding
				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       is_training
				SCREAMING_SNAKE_CASE   :      Dict				     =       use_labels
				SCREAMING_SNAKE_CASE   :      List[str]				     =       num_labels
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       num_channels
				SCREAMING_SNAKE_CASE   :      Any				     =       embed_dim
				SCREAMING_SNAKE_CASE   :      str				     =       num_heads
				SCREAMING_SNAKE_CASE   :      Any				     =       stride_kv
				SCREAMING_SNAKE_CASE   :      Tuple				     =       depth
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       cls_token
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       attention_drop_rate
				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       initializer_range
				SCREAMING_SNAKE_CASE   :      Tuple				     =       layer_norm_eps
			def 							__UpperCamelCase (			self							: str	)							->       Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      int				     =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

				SCREAMING_SNAKE_CASE   :      Any				     =       None
				if self.use_labels:
					# create a random int32 tensor of given shape
					SCREAMING_SNAKE_CASE   :      str				     =       ids_tensor([self.batch_size]      ,      self.num_labels	)

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       self.get_config()
				return config, pixel_values, labels
			def 							__UpperCamelCase (			self							: Optional[Any]	)							->       Optional[int]:

				"""simple docstring"""

				return CvtConfig(
				    image_size=self.image_size      ,      num_labels=self.num_labels      ,      num_channels=self.num_channels      ,      embed_dim=self.embed_dim      ,      num_heads=self.num_heads      ,      patch_sizes=self.patch_sizes      ,      patch_padding=self.patch_padding      ,      patch_stride=self.patch_stride      ,      stride_kv=self.stride_kv      ,      depth=self.depth      ,      cls_token=self.cls_token      ,      attention_drop_rate=self.attention_drop_rate      ,      initializer_range=self.initializer_range      ,      )
			def 							__UpperCamelCase (			self							: Tuple      ,      a							: str      ,      a							: List[str]      ,      a							: str	)							->       Dict:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      str				     =       TFCvtModel(config=a	)
				SCREAMING_SNAKE_CASE   :      Any				     =       model(a      ,      training=a	)
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       (self.image_size, self.image_size)
				SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE   :      Any				     =       image_size[0], image_size[1]
				for i in range(len(self.depth	)	):
					SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1	)
					SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1	)
				self.parent.assertEqual(result.last_hidden_state.shape      ,      (self.batch_size, self.embed_dim[-1], height, width)	)
			def 							__UpperCamelCase (			self							: Union[str, Any]      ,      a							: int      ,      a							: List[Any]      ,      a							: List[str]	)							->       Union[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       self.num_labels
				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       TFCvtForImageClassification(a	)
				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       model(a      ,      labels=a      ,      training=a	)
				self.parent.assertEqual(result.logits.shape      ,      (self.batch_size, self.num_labels)	)






			def 							__UpperCamelCase (			self							: Optional[Any]	)							->       Any:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      int				     =       self.prepare_config_and_inputs()
				SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE   :      List[str]				     =       config_and_inputs
				SCREAMING_SNAKE_CASE   :      str				     =       {"pixel_values": pixel_values}
				return config, inputs_dict






@require_tf
class _UpperCamelCase							(							__A							,	__A							,	unittest.TestCase   ):
			'''simple docstring'''







			lowerCamelCase__           =(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
			lowerCamelCase__           =(
			    {'feature-extraction': TFCvtModel, 'image-classification': TFCvtForImageClassification}
			    if is_tf_available()
			    else {}
			)
			lowerCamelCase__           =False
			lowerCamelCase__           =False
			lowerCamelCase__           =False
			lowerCamelCase__           =False
			lowerCamelCase__           =False
			def 							__UpperCamelCase (			self							: List[Any]	)							->       int:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       TFCvtModelTester(self	)
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       TFCvtConfigTester(self      ,      config_class=a      ,      has_text_modality=a      ,      hidden_size=37	)
			def 							__UpperCamelCase (			self							: Optional[int]	)							->       Optional[int]:

				"""simple docstring"""

				self.config_tester.create_and_test_config_common_properties()
				self.config_tester.create_and_test_config_to_json_string()
				self.config_tester.create_and_test_config_to_json_file()
				self.config_tester.create_and_test_config_from_and_save_pretrained()
				self.config_tester.create_and_test_config_with_num_labels()
				self.config_tester.check_config_can_be_init_without_params()
				self.config_tester.check_config_arguments_init()
			@unittest.skip(reason="Cvt does not output attentions"	)
			def 							__UpperCamelCase (			self							: str	)							->       Optional[int]:

				"""simple docstring"""

				pass
			@unittest.skip(reason="Cvt does not use inputs_embeds"	)
			def 							__UpperCamelCase (			self							: Optional[int]	)							->       Optional[int]:

				"""simple docstring"""

				pass
			@unittest.skip(reason="Cvt does not support input and output embeddings"	)
			def 							__UpperCamelCase (			self							: List[Any]	)							->       Dict:

				"""simple docstring"""

				pass
			@unittest.skipIf(
			    not is_tf_available() or len(tf.config.list_physical_devices("GPU"	)	) == 0      ,      reason="TF does not support backprop for grouped convolutions on CPU."      ,      )
			def 							__UpperCamelCase (			self							: int	)							->       Tuple:

				"""simple docstring"""

				super().test_dataset_conversion()
			@unittest.skipIf(
			    not is_tf_available() or len(tf.config.list_physical_devices("GPU"	)	) == 0      ,      reason="TF does not support backprop for grouped convolutions on CPU."      ,      )
			@slow
			def 							__UpperCamelCase (			self							: List[str]	)							->       str:

				"""simple docstring"""

				super().test_keras_fit()
			@unittest.skip(reason="Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8"	)
			def 							__UpperCamelCase (			self							: Optional[int]	)							->       Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Tuple				     =       tf.keras.mixed_precision.Policy("mixed_float16"	)
				tf.keras.mixed_precision.set_global_policy(a	)
				super().test_keras_fit()
				tf.keras.mixed_precision.set_global_policy("float32"	)
			def 							__UpperCamelCase (			self							: List[str]	)							->       Optional[int]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE   :      Optional[int]				     =       self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					SCREAMING_SNAKE_CASE   :      List[Any]				     =       model_class(a	)
					SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       inspect.signature(model.call	)
					# signature.parameters is an OrderedDict => so arg_names order is deterministic
					SCREAMING_SNAKE_CASE   :      Tuple				     =       [*signature.parameters.keys()]

					SCREAMING_SNAKE_CASE   :      Tuple				     =       ["pixel_values"]
					self.assertListEqual(arg_names[:1]      ,      a	)
			def 							__UpperCamelCase (			self							: Optional[int]	)							->       str:

				"""simple docstring"""

				def check_hidden_states_output(a							: List[str]      ,      a							: Union[str, Any]      ,      a							: List[str]	):
					SCREAMING_SNAKE_CASE   :      Tuple				     =       model_class(a	)

					SCREAMING_SNAKE_CASE   :      Optional[int]				     =       model(**self._prepare_for_class(a      ,      a	)	)
					SCREAMING_SNAKE_CASE   :      List[str]				     =       outputs.hidden_states

					SCREAMING_SNAKE_CASE   :      int				     =       len(self.model_tester.depth	)
					self.assertEqual(len(a	)      ,      a	)

					# verify the first hidden states (first block)
					self.assertListEqual(
					    list(hidden_states[0].shape[-3:]	)      ,      [
					        self.model_tester.embed_dim[0],
					        self.model_tester.image_size // 4,
					        self.model_tester.image_size // 4,
					    ]      ,      )

				SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE   :      List[str]				     =       self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       True
					check_hidden_states_output(a      ,      a      ,      a	)

					# check that output_hidden_states also work using config
					del inputs_dict["output_hidden_states"]
					SCREAMING_SNAKE_CASE   :      str				     =       True

					check_hidden_states_output(a      ,      a      ,      a	)
			def 							__UpperCamelCase (			self							: Any	)							->       Union[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Dict				     =       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*a	)
			def 							__UpperCamelCase (			self							: Optional[int]	)							->       Dict:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      List[str]				     =       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*a	)






			@slow
			def 							__UpperCamelCase (			self							: Tuple	)							->       Optional[int]:

				"""simple docstring"""

				for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					SCREAMING_SNAKE_CASE   :      Tuple				     =       TFCvtModel.from_pretrained(a	)
					self.assertIsNotNone(a	)

def  lowerCamelCase__ (					):
	SCREAMING_SNAKE_CASE   :      Optional[int]				     =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
	return image






@require_tf
@require_vision
class _UpperCamelCase							(							unittest.TestCase   ):
			'''simple docstring'''







			@cached_property
			def 							__UpperCamelCase (			self							: Tuple	)							->       Tuple:

				"""simple docstring"""

				return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)






			@slow
			def 							__UpperCamelCase (			self							: Dict	)							->       Any:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)

				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       self.default_image_processor
				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       prepare_img()
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       image_processor(images=a      ,      return_tensors="tf"	)

				# forward pass
				SCREAMING_SNAKE_CASE   :      List[str]				     =       model(**a	)

				# verify the logits
				SCREAMING_SNAKE_CASE   :      Dict				     =       tf.TensorShape((1, 1000)	)
				self.assertEqual(outputs.logits.shape      ,      a	)

				SCREAMING_SNAKE_CASE   :      Tuple				     =       tf.constant([0.9285, 0.9015, -0.3150]	)
				self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()      ,      a      ,      atol=1e-4	)	)