






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 						UpperCAmelCase__ (							__snake_case							):







		def  A__      (					self		):
						_A	:				Tuple   =      self.config_class(**self.inputs_dict		)
						self.parent.assertTrue(hasattr(A__       ,'''embed_dim'''		)		)
						self.parent.assertTrue(hasattr(A__       ,'''num_heads'''		)		)






class 						UpperCAmelCase__ :







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







		def  A__      (					self		):
						_A	:				Union[str, Any]   =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

						_A	:				int   =      None
						if self.use_labels:
										_A	:				Union[str, Any]   =      ids_tensor([self.batch_size]       ,self.num_labels		)

						_A	:				Union[str, Any]   =      self.get_config()
						return config, pixel_values, labels







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







		def  A__      (					self		):
						_A	:				Tuple   =      self.prepare_config_and_inputs()
						_A  ,				_A  ,				_A	:				List[str]   =      config_and_inputs
						_A	:				int   =      {'''pixel_values''': pixel_values}
						return config, inputs_dict






@require_torch
class 						UpperCAmelCase__ (							__snake_case     ,				__snake_case     ,				unittest.TestCase							):
		__snake_case      :       Optional[int]     =   (CvtModel, CvtForImageClassification) if is_torch_available() else ()
		__snake_case      :       str     =   (
		    {"feature-extraction": CvtModel, "image-classification": CvtForImageClassification}
		    if is_torch_available()
		    else {}
		)

		__snake_case      :       Tuple     =   False
		__snake_case      :       List[str]     =   False
		__snake_case      :       List[Any]     =   False
		__snake_case      :       Any     =   False
		__snake_case      :       Dict     =   False







		def  A__      (					self		):
						_A	:				Dict   =      CvtModelTester(self		)
						_A	:				Any   =      ConfigTester(self       ,config_class=A__       ,has_text_modality=A__       ,hidden_size=37		)







		def  A__      (					self		):
						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  A__      (					self		):
						return







		@unittest.skip(reason='''Cvt does not output attentions'''		)
		def  A__      (					self		):
						pass







		@unittest.skip(reason='''Cvt does not use inputs_embeds'''		)
		def  A__      (					self		):
						pass







		@unittest.skip(reason='''Cvt does not support input and output embeddings'''		)
		def  A__      (					self		):
						pass







		def  A__      (					self		):
						_A  ,				_A	:				Tuple   =      self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
										_A	:				List[Any]   =      model_class(A__		)
										_A	:				Union[str, Any]   =      inspect.signature(model.forward		)
										# signature.parameters is an OrderedDict => so arg_names order is deterministic
										_A	:				List[str]   =      [*signature.parameters.keys()]

										_A	:				List[str]   =      ['''pixel_values''']
										self.assertListEqual(arg_names[:1]       ,A__		)







		def  A__      (					self		):
						_A	:				str   =      self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*A__		)







		def  A__      (					self		):
						def check_hidden_states_output(A__       ,A__       ,A__		):
										_A	:				List[str]   =      model_class(A__		)
										model.to(A__		)
										model.eval()

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

										_A	:				str   =      outputs.hidden_states

										_A	:				Any   =      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,
										    ]       ,)

						_A  ,				_A	:				Optional[Any]   =      self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
										_A	:				str   =      True
										check_hidden_states_output(A__       ,A__       ,A__		)

										# check that output_hidden_states also work using config
										del inputs_dict["output_hidden_states"]
										_A	:				Union[str, Any]   =      True

										check_hidden_states_output(A__       ,A__       ,A__		)







		def  A__      (					self		):
						_A	:				List[Any]   =      self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*A__		)







		@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''		)
		def  A__      (					self		):
						pass







		@slow
		def  A__      (					self		):
						for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										_A	:				Dict   =      CvtModel.from_pretrained(A__		)
										self.assertIsNotNone(A__		)



def  a__ ()		-> Optional[Any]:
				_A	:				Optional[int]   =      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
				return image






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







		@cached_property
		def  A__      (					self		):
						return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)







		@slow
		def  A__      (					self		):
						_A	:				List[str]   =      CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(A__		)

						_A	:				Optional[Any]   =      self.default_image_processor
						_A	:				Dict   =      prepare_img()
						_A	:				Optional[int]   =      image_processor(images=A__       ,return_tensors='''pt'''		).to(A__		)

						# forward pass
						with torch.no_grad():
										_A	:				str   =      model(**A__		)

						# verify the logits
						_A	:				Any   =      torch.Size((1, 1000)		)
						self.assertEqual(outputs.logits.shape       ,A__		)

						_A	:				int   =      torch.tensor([0.92_85, 0.90_15, -0.31_50]		).to(A__		)

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











from typing import Dict, List, Optional, Union

import numpy as np

from transformers.utils import is_vision_available
from transformers.utils.generic import TensorType

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_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_valid_image,
    to_numpy_array,
    valid_images,
)
from ...utils import logging


if is_vision_available():
	import PIL

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



def  a__ (__lowercase							:str   )		-> List[List[ImageInput]]:
				if isinstance(__lowercase					,  (list, tuple)   ) and isinstance(videos[0]					,  (list, tuple)   ) and is_valid_image(videos[0][0]   ):
								return videos

				elif isinstance(__lowercase					,  (list, tuple)   ) and is_valid_image(videos[0]   ):
								return [videos]

				elif is_valid_image(__lowercase   ):
								return [[videos]]

				raise ValueError(f"""Could not make batched video from {videos}"""   )






class 						UpperCAmelCase__ (							__snake_case							):
		__snake_case      :       Optional[int]     =   ["pixel_values"]







		def __init__(					self       ,A__ = True       ,A__ = None       ,A__ = PILImageResampling.BILINEAR       ,A__ = True       ,A__ = None       ,A__ = True       ,A__ = 1 / 255       ,A__ = True       ,A__ = True       ,A__ = None       ,A__ = None       ,**A__       ,):
						super().__init__(**A__		)
						_A	:				Tuple   =      size if size is not None else {'''shortest_edge''': 256}
						_A	:				str   =      get_size_dict(A__       ,default_to_square=A__		)
						_A	:				str   =      crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
						_A	:				str   =      get_size_dict(A__       ,param_name='''crop_size'''		)

						_A	:				Tuple   =      do_resize
						_A	:				Optional[Any]   =      size
						_A	:				Optional[Any]   =      do_center_crop
						_A	:				List[str]   =      crop_size
						_A	:				Dict   =      resample
						_A	:				Tuple   =      do_rescale
						_A	:				int   =      rescale_factor
						_A	:				List[str]   =      offset
						_A	:				List[Any]   =      do_normalize
						_A	:				List[Any]   =      image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
						_A	:				List[str]   =      image_std if image_std is not None else IMAGENET_STANDARD_STD







		def  A__      (					self       ,A__       ,A__       ,A__ = PILImageResampling.BILINEAR       ,A__ = None       ,**A__       ,):
						_A	:				str   =      get_size_dict(A__       ,default_to_square=A__		)
						if "shortest_edge" in size:
										_A	:				Optional[Any]   =      get_resize_output_image_size(A__       ,size['''shortest_edge''']       ,default_to_square=A__		)
						elif "height" in size and "width" in size:
										_A	:				str   =      (size['''height'''], size['''width'''])
						else:
										raise ValueError(f"""Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}"""		)
						return resize(A__       ,size=A__       ,resample=A__       ,data_format=A__       ,**A__		)







		def  A__      (					self       ,A__       ,A__       ,A__ = None       ,**A__       ,):
						_A	:				Optional[int]   =      get_size_dict(A__		)
						if "height" not in size or "width" not in size:
										raise ValueError(f"""Size must have 'height' and 'width' as keys. Got {size.keys()}"""		)
						return center_crop(A__       ,size=(size['''height'''], size['''width'''])       ,data_format=A__       ,**A__		)







		def  A__      (					self       ,A__       ,A__       ,A__ = True       ,A__ = None       ,**A__       ,):
						_A	:				Any   =      image.astype(np.floataa		)
						if offset:
										_A	:				List[str]   =      image - (scale / 2)
						return rescale(A__       ,scale=A__       ,data_format=A__       ,**A__		)







		def  A__      (					self       ,A__       ,A__       ,A__       ,A__ = None       ,**A__       ,):
						return normalize(A__       ,mean=A__       ,std=A__       ,data_format=A__       ,**A__		)







		def  A__      (					self       ,A__       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = ChannelDimension.FIRST       ,):
						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_size is None:
										raise ValueError('''Crop size 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.'''		)

						if offset and not do_rescale:
										raise ValueError('''For offset, do_rescale must also be set to True.'''		)

						# All transformations expect numpy arrays.
						_A	:				Dict   =      to_numpy_array(A__		)

						if do_resize:
										_A	:				Any   =      self.resize(image=A__       ,size=A__       ,resample=A__		)

						if do_center_crop:
										_A	:				str   =      self.center_crop(A__       ,size=A__		)

						if do_rescale:
										_A	:				Optional[int]   =      self.rescale(image=A__       ,scale=A__       ,offset=A__		)

						if do_normalize:
										_A	:				Dict   =      self.normalize(image=A__       ,mean=A__       ,std=A__		)

						_A	:				Union[str, Any]   =      to_channel_dimension_format(A__       ,A__		)
						return image







		def  A__      (					self       ,A__       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = None       ,A__ = ChannelDimension.FIRST       ,**A__       ,):
						_A	:				Optional[int]   =      do_resize if do_resize is not None else self.do_resize
						_A	:				List[str]   =      resample if resample is not None else self.resample
						_A	:				Union[str, Any]   =      do_center_crop if do_center_crop is not None else self.do_center_crop
						_A	:				Tuple   =      do_rescale if do_rescale is not None else self.do_rescale
						_A	:				List[str]   =      rescale_factor if rescale_factor is not None else self.rescale_factor
						_A	:				List[str]   =      offset if offset is not None else self.offset
						_A	:				Optional[int]   =      do_normalize if do_normalize is not None else self.do_normalize
						_A	:				Optional[Any]   =      image_mean if image_mean is not None else self.image_mean
						_A	:				Dict   =      image_std if image_std is not None else self.image_std

						_A	:				str   =      size if size is not None else self.size
						_A	:				int   =      get_size_dict(A__       ,default_to_square=A__		)
						_A	:				Any   =      crop_size if crop_size is not None else self.crop_size
						_A	:				Optional[int]   =      get_size_dict(A__       ,param_name='''crop_size'''		)

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

						_A	:				List[str]   =      make_batched(A__		)

						_A	:				Tuple   =      [
						    [
						        self._preprocess_image(
						            image=A__       ,do_resize=A__       ,size=A__       ,resample=A__       ,do_center_crop=A__       ,crop_size=A__       ,do_rescale=A__       ,rescale_factor=A__       ,offset=A__       ,do_normalize=A__       ,image_mean=A__       ,image_std=A__       ,data_format=A__       ,)
						        for img in video
						    ]
						    for video in videos
						]

						_A	:				Optional[int]   =      {'''pixel_values''': videos}
						return BatchFeature(data=A__       ,tensor_type=A__		)



