






import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import CvtForImageClassification, CvtModel
       from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor
class     a    ( lowercase__   ):



      """simple docstring"""


      def 	UpperCAmelCase      (      self					:			Tuple					)							->      Any:
        __UpperCAmelCase							:	Optional[Any]           =  self.config_class(**self.inputs_dict					)
        self.parent.assertTrue(hasattr(__lowercase		,      """embed_dim"""					)					)
        self.parent.assertTrue(hasattr(__lowercase		,      """num_heads"""					)					)


class     a    :



      """simple docstring"""


      def __init__(      self					:			Tuple		,      __lowercase					:			Optional[int]		,      __lowercase					:			Dict=13		,      __lowercase					:			str=64		,      __lowercase					:			str=3		,      __lowercase					:			Tuple=[16, 48, 96]		,      __lowercase					:			Dict=[1, 3, 6]		,      __lowercase					:			Union[str, Any]=[1, 2, 10]		,      __lowercase					:			Optional[int]=[7, 3, 3]		,      __lowercase					:			Tuple=[4, 2, 2]		,      __lowercase					:			List[str]=[2, 1, 1]		,      __lowercase					:			List[str]=[2, 2, 2]		,      __lowercase					:			Optional[Any]=[False, False, True]		,      __lowercase					:			Optional[Any]=[0.0, 0.0, 0.0]		,      __lowercase					:			Tuple=0.02		,      __lowercase					:			Tuple=1e-1_2		,      __lowercase					:			List[str]=True		,      __lowercase					:			Dict=True		,      __lowercase					:			Optional[int]=2		,      )							->      Optional[Any]:
        __UpperCAmelCase							:	Any           =  parent
        __UpperCAmelCase							:	List[Any]           =  batch_size
        __UpperCAmelCase							:	Optional[int]           =  image_size
        __UpperCAmelCase							:	Optional[int]           =  patch_sizes
        __UpperCAmelCase							:	Optional[int]           =  patch_stride
        __UpperCAmelCase							:	Optional[Any]           =  patch_padding
        __UpperCAmelCase							:	Tuple           =  is_training
        __UpperCAmelCase							:	Any           =  use_labels
        __UpperCAmelCase							:	List[str]           =  num_labels
        __UpperCAmelCase							:	int           =  num_channels
        __UpperCAmelCase							:	Optional[Any]           =  embed_dim
        __UpperCAmelCase							:	Optional[Any]           =  num_heads
        __UpperCAmelCase							:	Optional[Any]           =  stride_kv
        __UpperCAmelCase							:	Union[str, Any]           =  depth
        __UpperCAmelCase							:	Optional[int]           =  cls_token
        __UpperCAmelCase							:	Tuple           =  attention_drop_rate
        __UpperCAmelCase							:	str           =  initializer_range
        __UpperCAmelCase							:	Union[str, Any]           =  layer_norm_eps
      def 	UpperCAmelCase      (      self					:			List[Any]					)							->      Union[str, Any]:
        __UpperCAmelCase							:	Union[str, Any]           =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

        __UpperCAmelCase							:	int           =  None
        if self.use_labels:
          __UpperCAmelCase							:	Dict           =  ids_tensor([self.batch_size]		,      self.num_labels					)

        __UpperCAmelCase							:	Optional[int]           =  self.get_config()
        return config, pixel_values, labels
      def 	UpperCAmelCase      (      self					:			str					)							->      Optional[int]:
        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					:			Optional[int]		,      __lowercase					:			Any		,      __lowercase					:			Dict		,      __lowercase					:			Dict					)							->      List[Any]:
        __UpperCAmelCase							:	Optional[int]           =  CvtModel(config=__lowercase					)
        model.to(__lowercase					)
        model.eval()
        __UpperCAmelCase							:	int           =  model(__lowercase					)
        __UpperCAmelCase							:	Tuple           =  (self.image_size, self.image_size)
        __UpperCAmelCase      , __UpperCAmelCase							:	Union[str, Any]           =  image_size[0], image_size[1]
        for i in range(len(self.depth					)					):
          __UpperCAmelCase							:	Tuple           =  floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1					)
          __UpperCAmelCase							:	Union[str, 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					:			str		,      __lowercase					:			Any		,      __lowercase					:			Optional[int]		,      __lowercase					:			Optional[Any]					)							->      int:
        __UpperCAmelCase							:	Dict           =  self.num_labels
        __UpperCAmelCase							:	List[str]           =  CvtForImageClassification(__lowercase					)
        model.to(__lowercase					)
        model.eval()
        __UpperCAmelCase							:	Any           =  model(__lowercase		,      labels=__lowercase					)
        self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels)					)




      def 	UpperCAmelCase      (      self					:			Optional[Any]					)							->      List[str]:
        __UpperCAmelCase							:	Any           =  self.prepare_config_and_inputs()
        __UpperCAmelCase      , __UpperCAmelCase      , __UpperCAmelCase							:	Union[str, Any]           =  config_and_inputs
        __UpperCAmelCase							:	str           =  {"""pixel_values""": pixel_values}
        return config, inputs_dict


@require_torch
class     a    ( lowercase__							,       lowercase__							,       unittest.TestCase   ):



      """simple docstring"""


      a  : Union[str, Any]							       =	(CvtModel, CvtForImageClassification) if is_torch_available() else ()
      a  : List[str]							       =	(
          {'feature-extraction': CvtModel, 'image-classification': CvtForImageClassification}
          if is_torch_available()
          else {}
      )

      a  : int							       =	False
      a  : str							       =	False
      a  : Tuple							       =	False
      a  : List[Any]							       =	False
      a  : Optional[Any]							       =	False
      def 	UpperCAmelCase      (      self					:			List[str]					)							->      Any:
        __UpperCAmelCase							:	Union[str, Any]           =  CvtModelTester(self					)
        __UpperCAmelCase							:	Any           =  ConfigTester(self		,      config_class=__lowercase		,      has_text_modality=__lowercase		,      hidden_size=37					)
      def 	UpperCAmelCase      (      self					:			Optional[Any]					)							->      List[str]:
        self.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()
      def 	UpperCAmelCase      (      self					:			Union[str, Any]					)							->      Union[str, Any]:
        return
      @unittest.skip(reason="""Cvt does not output attentions"""					)
      def 	UpperCAmelCase      (      self					:			Optional[Any]					)							->      str:
        pass
      @unittest.skip(reason="""Cvt does not use inputs_embeds"""					)
      def 	UpperCAmelCase      (      self					:			List[str]					)							->      Union[str, Any]:
        pass
      @unittest.skip(reason="""Cvt does not support input and output embeddings"""					)
      def 	UpperCAmelCase      (      self					:			Tuple					)							->      Union[str, Any]:
        pass
      def 	UpperCAmelCase      (      self					:			int					)							->      str:
        __UpperCAmelCase      , __UpperCAmelCase							:	Optional[Any]           =  self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          __UpperCAmelCase							:	str           =  model_class(__lowercase					)
          __UpperCAmelCase							:	Dict           =  inspect.signature(model.forward					)
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          __UpperCAmelCase							:	Optional[int]           =  [*signature.parameters.keys()]

          __UpperCAmelCase							:	List[str]           =  ["""pixel_values"""]
          self.assertListEqual(arg_names[:1]		,      __lowercase					)
      def 	UpperCAmelCase      (      self					:			int					)							->      Optional[int]:
        __UpperCAmelCase							:	int           =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__lowercase					)
      def 	UpperCAmelCase      (      self					:			str					)							->      List[str]:
        def check_hidden_states_output(__lowercase					:			str		,      __lowercase					:			Any		,      __lowercase					:			Tuple					):
          __UpperCAmelCase							:	int           =  model_class(__lowercase					)
          model.to(__lowercase					)
          model.eval()

          with torch.no_grad():
            __UpperCAmelCase							:	Optional[int]           =  model(**self._prepare_for_class(__lowercase		,      __lowercase					)					)

          __UpperCAmelCase							:	Optional[int]           =  outputs.hidden_states

          __UpperCAmelCase							:	Union[str, Any]           =  len(self.model_tester.depth					)
          self.assertEqual(len(__lowercase					)		,      __lowercase					)

          # 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,
              ]		,      )

        __UpperCAmelCase      , __UpperCAmelCase							:	str           =  self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          __UpperCAmelCase							:	Union[str, Any]           =  True
          check_hidden_states_output(__lowercase		,      __lowercase		,      __lowercase					)

          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          __UpperCAmelCase							:	List[Any]           =  True

          check_hidden_states_output(__lowercase		,      __lowercase		,      __lowercase					)
      def 	UpperCAmelCase      (      self					:			int					)							->      Any:
        __UpperCAmelCase							:	Tuple           =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__lowercase					)
      @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""					)
      def 	UpperCAmelCase      (      self					:			str					)							->      Optional[Any]:
        pass




      @slow
      def 	UpperCAmelCase      (      self					:			List[str]					)							->      Union[str, Any]:
        for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          __UpperCAmelCase							:	Dict           =  CvtModel.from_pretrained(__lowercase					)
          self.assertIsNotNone(__lowercase					)






def 				lowerCamelCase__      (    ):
  __UpperCAmelCase							:	Union[str, Any]           =  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
  return image







@require_torch
@require_vision
class     a    ( unittest.TestCase   ):



      """simple docstring"""


      @cached_property
      def 	UpperCAmelCase      (      self					:			Optional[Any]					)							->      List[str]:
        return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)




      @slow
      def 	UpperCAmelCase      (      self					:			Dict					)							->      Any:
        __UpperCAmelCase							:	Union[str, Any]           =  CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]					).to(__lowercase					)

        __UpperCAmelCase							:	Optional[int]           =  self.default_image_processor
        __UpperCAmelCase							:	Dict           =  prepare_img()
        __UpperCAmelCase							:	Any           =  image_processor(images=__lowercase		,      return_tensors="""pt"""					).to(__lowercase					)

        # forward pass
        with torch.no_grad():
          __UpperCAmelCase							:	str           =  model(**__lowercase					)

        # verify the logits
        __UpperCAmelCase							:	str           =  torch.Size((1, 1000)					)
        self.assertEqual(outputs.logits.shape		,      __lowercase					)

        __UpperCAmelCase							:	Optional[Any]           =  torch.tensor([0.9_285, 0.9_015, -0.3_150]					).to(__lowercase					)

        self.assertTrue(torch.allclose(outputs.logits[0, :3]		,      __lowercase		,      atol=1e-4					)					)










from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
       import PIL


a		:       Union[str, Any]			     = logging.get_logger(__name__)
class     a    ( lowercase__   ):



      """simple docstring"""


      a  : Any							       =	['pixel_values']
      def __init__(      self					:			Optional[int]		,      __lowercase					:			bool = True		,      __lowercase					:			Dict[str, int] = None		,      __lowercase					:			int = 0.9		,      __lowercase					:			PILImageResampling = PILImageResampling.BICUBIC		,      __lowercase					:			bool = True		,      __lowercase					:			Dict[str, int] = None		,      __lowercase					:			Union[int, float] = 1 / 255		,      __lowercase					:			bool = True		,      __lowercase					:			bool = True		,      __lowercase					:			Optional[Union[float, List[float]]] = None		,      __lowercase					:			Optional[Union[float, List[float]]] = None		,      **__lowercase					:			Any		,      )							->      None:
        super().__init__(**__lowercase					)
        __UpperCAmelCase							:	Tuple           =  size if size is not None else {"""shortest_edge""": 224}
        __UpperCAmelCase							:	Union[str, Any]           =  get_size_dict(__lowercase		,      default_to_square=__lowercase					)
        __UpperCAmelCase							:	Union[str, Any]           =  crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
        __UpperCAmelCase							:	Any           =  get_size_dict(__lowercase		,      param_name="""crop_size"""					)

        __UpperCAmelCase							:	Dict           =  do_resize
        __UpperCAmelCase							:	Dict           =  size
        __UpperCAmelCase							:	Tuple           =  crop_pct
        __UpperCAmelCase							:	List[Any]           =  resample
        __UpperCAmelCase							:	List[Any]           =  do_center_crop
        __UpperCAmelCase							:	List[Any]           =  crop_size
        __UpperCAmelCase							:	Any           =  do_rescale
        __UpperCAmelCase							:	Tuple           =  rescale_factor
        __UpperCAmelCase							:	int           =  do_normalize
        __UpperCAmelCase							:	List[Any]           =  image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
        __UpperCAmelCase							:	List[str]           =  image_std if image_std is not None else IMAGENET_DEFAULT_STD
      def 	UpperCAmelCase      (      self					:			Tuple		,      __lowercase					:			np.ndarray		,      __lowercase					:			Dict[str, int]		,      __lowercase					:			Optional[float] = None		,      __lowercase					:			PILImageResampling = PILImageResampling.BICUBIC		,      __lowercase					:			Optional[Union[str, ChannelDimension]] = None		,      **__lowercase					:			Optional[int]		,      )							->      np.ndarray:
        __UpperCAmelCase							:	Tuple           =  get_size_dict(__lowercase		,      default_to_square=__lowercase					)
        if "shortest_edge" not in size and ("height" not in size or "width" not in size):
          raise ValueError(f"""size must contain 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}"""					)
        if crop_pct is not None:
          if "shortest_edge" in size:
            __UpperCAmelCase							:	Union[str, Any]           =  int(size["""shortest_edge"""] / crop_pct					)
          elif "height" in size and "width" in size:
            if size["height"] == size["width"]:
              __UpperCAmelCase							:	Tuple           =  int(size["""height"""] / crop_pct					)
            else:
              __UpperCAmelCase							:	str           =  (int(size["""height"""] / crop_pct					), int(size["""width"""] / crop_pct					))
          else:
            raise ValueError("""Invalid size for resize: {}""".format(__lowercase					)					)

          __UpperCAmelCase							:	str           =  get_resize_output_image_size(__lowercase		,      size=__lowercase		,      default_to_square=__lowercase					)
        else:
          if "shortest_edge" in size:
            __UpperCAmelCase							:	List[str]           =  get_resize_output_image_size(__lowercase		,      size=size["""shortest_edge"""]		,      default_to_square=__lowercase					)
          elif "height" in size and "width" in size:
            __UpperCAmelCase							:	int           =  (size["""height"""], size["""width"""])
          else:
            raise ValueError("""Invalid size for resize: {}""".format(__lowercase					)					)

        return resize(__lowercase		,      size=__lowercase		,      resample=__lowercase		,      data_format=__lowercase		,      **__lowercase					)
      def 	UpperCAmelCase      (      self					:			Dict		,      __lowercase					:			np.ndarray		,      __lowercase					:			Dict[str, int]		,      __lowercase					:			Optional[Union[str, ChannelDimension]] = None		,      **__lowercase					:			Union[str, Any]		,      )							->      np.ndarray:
        __UpperCAmelCase							:	Optional[Any]           =  get_size_dict(__lowercase					)
        if "height" not in size or "width" not in size:
          raise ValueError(f"""size must contain 'height' and 'width' as keys. Got {size.keys()}"""					)
        return center_crop(__lowercase		,      size=(size["""height"""], size["""width"""])		,      data_format=__lowercase		,      **__lowercase					)
      def 	UpperCAmelCase      (      self					:			List[str]		,      __lowercase					:			np.ndarray		,      __lowercase					:			Union[int, float]		,      __lowercase					:			Optional[Union[str, ChannelDimension]] = None		,      **__lowercase					:			int		,      )							->      int:
        return rescale(__lowercase		,      scale=__lowercase		,      data_format=__lowercase		,      **__lowercase					)
      def 	UpperCAmelCase      (      self					:			List[Any]		,      __lowercase					:			np.ndarray		,      __lowercase					:			Union[float, List[float]]		,      __lowercase					:			Union[float, List[float]]		,      __lowercase					:			Optional[Union[str, ChannelDimension]] = None		,      **__lowercase					:			List[Any]		,      )							->      np.ndarray:
        return normalize(__lowercase		,      mean=__lowercase		,      std=__lowercase		,      data_format=__lowercase		,      **__lowercase					)




      def 	UpperCAmelCase      (      self					:			Any		,      __lowercase					:			ImageInput		,      __lowercase					:			bool = None		,      __lowercase					:			Dict[str, int] = None		,      __lowercase					:			int = None		,      __lowercase					:			PILImageResampling = None		,      __lowercase					:			bool = None		,      __lowercase					:			Dict[str, int] = None		,      __lowercase					:			bool = None		,      __lowercase					:			float = None		,      __lowercase					:			bool = None		,      __lowercase					:			Optional[Union[float, List[float]]] = None		,      __lowercase					:			Optional[Union[float, List[float]]] = None		,      __lowercase					:			Optional[Union[str, TensorType]] = None		,      __lowercase					:			ChannelDimension = ChannelDimension.FIRST		,      **__lowercase					:			List[str]		,      )							->      PIL.Image.Image:
        __UpperCAmelCase							:	Any           =  do_resize if do_resize is not None else self.do_resize
        __UpperCAmelCase							:	Optional[int]           =  crop_pct if crop_pct is not None else self.crop_pct
        __UpperCAmelCase							:	Optional[Any]           =  resample if resample is not None else self.resample
        __UpperCAmelCase							:	List[Any]           =  do_center_crop if do_center_crop is not None else self.do_center_crop
        __UpperCAmelCase							:	Dict           =  do_rescale if do_rescale is not None else self.do_rescale
        __UpperCAmelCase							:	Tuple           =  rescale_factor if rescale_factor is not None else self.rescale_factor
        __UpperCAmelCase							:	Union[str, Any]           =  do_normalize if do_normalize is not None else self.do_normalize
        __UpperCAmelCase							:	Tuple           =  image_mean if image_mean is not None else self.image_mean
        __UpperCAmelCase							:	Any           =  image_std if image_std is not None else self.image_std

        __UpperCAmelCase							:	Optional[int]           =  size if size is not None else self.size
        __UpperCAmelCase							:	Dict           =  get_size_dict(__lowercase		,      default_to_square=__lowercase					)
        __UpperCAmelCase							:	Tuple           =  crop_size if crop_size is not None else self.crop_size
        __UpperCAmelCase							:	Tuple           =  get_size_dict(__lowercase		,      param_name="""crop_size"""					)

        __UpperCAmelCase							:	Dict           =  make_list_of_images(__lowercase					)

        if not valid_images(__lowercase					):
          raise ValueError(
              """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
              """torch.Tensor, tf.Tensor or jax.ndarray."""					)

        if do_resize and size is None or resample is None:
          raise ValueError("""Size and resample must be specified if do_resize is True."""					)

        if do_center_crop and crop_pct is None:
          raise ValueError("""Crop_pct must be specified if do_center_crop is True."""					)

        if do_rescale and rescale_factor is None:
          raise ValueError("""Rescale factor must be specified if do_rescale is True."""					)

        if do_normalize and (image_mean is None or image_std is None):
          raise ValueError("""Image mean and std must be specified if do_normalize is True."""					)

        # All transformations expect numpy arrays.
        __UpperCAmelCase							:	str           =  [to_numpy_array(__lowercase					) for image in images]

        if do_resize:
          __UpperCAmelCase							:	str           =  [self.resize(image=__lowercase		,      size=__lowercase		,      crop_pct=__lowercase		,      resample=__lowercase					) for image in images]

        if do_center_crop:
          __UpperCAmelCase							:	Any           =  [self.center_crop(image=__lowercase		,      size=__lowercase					) for image in images]

        if do_rescale:
          __UpperCAmelCase							:	List[str]           =  [self.rescale(image=__lowercase		,      scale=__lowercase					) for image in images]

        if do_normalize:
          __UpperCAmelCase							:	str           =  [self.normalize(image=__lowercase		,      mean=__lowercase		,      std=__lowercase					) for image in images]

        __UpperCAmelCase							:	List[str]           =  [to_channel_dimension_format(__lowercase		,      __lowercase					) for image in images]

        __UpperCAmelCase							:	Any           =  {"""pixel_values""": images}
        return BatchFeature(data=__lowercase		,      tensor_type=__lowercase					)


