"""simple docstring"""




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_   (  __UpperCamelCase      ):




					def     _SCREAMING_SNAKE_CASE    (						self    :  str  ):
							lowerCAmelCase__   = self.config_class(**self.inputs_dict  )
							self.parent.assertTrue(hasattr(snake_case__	,    """embed_dim"""  )  )
							self.parent.assertTrue(hasattr(snake_case__	,    """num_heads"""  )  )

class    a_   :




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




					def     _SCREAMING_SNAKE_CASE    (						self    :  Any  ):
							lowerCAmelCase__   = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

							lowerCAmelCase__   = None
							if self.use_labels:
									lowerCAmelCase__   = ids_tensor([self.batch_size]	,    self.num_labels  )

							lowerCAmelCase__   = self.get_config()
							return config, pixel_values, labels




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




					def     _SCREAMING_SNAKE_CASE    (						self    :  Tuple  ):
							lowerCAmelCase__   = self.prepare_config_and_inputs()
							lowerCAmelCase__ ,       lowerCAmelCase__ ,       lowerCAmelCase__   = config_and_inputs
							lowerCAmelCase__   = {"""pixel_values""": pixel_values}
							return config, inputs_dict

@require_torch
class    a_   (  __UpperCamelCase			,		__UpperCamelCase			,		unittest.TestCase      ):
					UpperCamelCase_			:						Any      =     (CvtModel, CvtForImageClassification) if is_torch_available() else ()
					UpperCamelCase_			:						int      =     (
					    {"feature-extraction": CvtModel, "image-classification": CvtForImageClassification}
					    if is_torch_available()
					    else {}
					)

					UpperCamelCase_			:						List[str]      =     False
					UpperCamelCase_			:						List[Any]      =     False
					UpperCamelCase_			:						List[str]      =     False
					UpperCamelCase_			:						List[Any]      =     False
					UpperCamelCase_			:						Any      =     False




					def     _SCREAMING_SNAKE_CASE    (						self    :  List[Any]  ):
							lowerCAmelCase__   = CvtModelTester(self  )
							lowerCAmelCase__   = ConfigTester(self	,    config_class=snake_case__	,    has_text_modality=snake_case__	,    hidden_size=37  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  Union[str, Any]  ):
							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     _SCREAMING_SNAKE_CASE    (						self    :  List[str]  ):
							return




					@unittest.skip(reason="""Cvt does not output attentions"""  )
					def     _SCREAMING_SNAKE_CASE    (						self    :  str  ):
							pass




					@unittest.skip(reason="""Cvt does not use inputs_embeds"""  )
					def     _SCREAMING_SNAKE_CASE    (						self    :  List[str]  ):
							pass




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




					def     _SCREAMING_SNAKE_CASE    (						self    :  Dict  ):
							lowerCAmelCase__ ,       lowerCAmelCase__   = self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									lowerCAmelCase__   = model_class(snake_case__  )
									lowerCAmelCase__   = inspect.signature(model.forward  )
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									lowerCAmelCase__   = [*signature.parameters.keys()]

									lowerCAmelCase__   = ["""pixel_values"""]
									self.assertListEqual(arg_names[:1]	,    snake_case__  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  Dict  ):
							lowerCAmelCase__   = self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*snake_case__  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  Union[str, Any]  ):
							def check_hidden_states_output(snake_case__    :  str	,    snake_case__    :  str	,    snake_case__    :  Optional[int]  ):
									lowerCAmelCase__   = model_class(snake_case__  )
									model.to(snake_case__  )
									model.eval()

									with torch.no_grad():
											lowerCAmelCase__   = model(**self._prepare_for_class(snake_case__	,    snake_case__  )  )

									lowerCAmelCase__   = outputs.hidden_states

									lowerCAmelCase__   = len(self.model_tester.depth  )
									self.assertEqual(len(snake_case__  )	,    snake_case__  )

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

							lowerCAmelCase__ ,       lowerCAmelCase__   = self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									lowerCAmelCase__   = True
									check_hidden_states_output(snake_case__	,    snake_case__	,    snake_case__  )

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									lowerCAmelCase__   = True

									check_hidden_states_output(snake_case__	,    snake_case__	,    snake_case__  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  List[str]  ):
							lowerCAmelCase__   = self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*snake_case__  )




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




					@slow
					def     _SCREAMING_SNAKE_CASE    (						self    :  Any  ):
							for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowerCAmelCase__   = CvtModel.from_pretrained(snake_case__  )
									self.assertIsNotNone(snake_case__  )







def 				_UpperCAmelCase		(							):





		"""simple docstring"""




		lowerCAmelCase__   = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""  )
		return image






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




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




					@slow
					def     _SCREAMING_SNAKE_CASE    (						self    :  Dict  ):
							lowerCAmelCase__   = CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  ).to(snake_case__  )

							lowerCAmelCase__   = self.default_image_processor
							lowerCAmelCase__   = prepare_img()
							lowerCAmelCase__   = image_processor(images=snake_case__	,    return_tensors="""pt"""  ).to(snake_case__  )

							# forward pass
							with torch.no_grad():
									lowerCAmelCase__   = model(**snake_case__  )

							# verify the logits
							lowerCAmelCase__   = torch.Size((1, 1000)  )
							self.assertEqual(outputs.logits.shape	,    snake_case__  )

							lowerCAmelCase__   = torch.tensor([0.9285, 0.9015, -0.3150]  ).to(snake_case__  )

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





"""simple docstring"""




import unittest

import numpy as np
import requests

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
			import torch

			from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
			__lowerCAmelCase     :				int    				=    False

if is_vision_available():
			from PIL import Image

			from transformers import PixaStructImageProcessor

class    a_   (  unittest.TestCase      ):




					def __init__(						self    :  Tuple	,    snake_case__    :  Any	,    snake_case__    :  Union[str, Any]=7	,    snake_case__    :  Optional[int]=3	,    snake_case__    :  int=18	,    snake_case__    :  Dict=30	,    snake_case__    :  Optional[Any]=400	,    snake_case__    :  Tuple=None	,    snake_case__    :  List[Any]=True	,    snake_case__    :  Any=True	,    snake_case__    :  Dict=None	,    ):
							lowerCAmelCase__   = size if size is not None else {"""height""": 20, """width""": 20}
							lowerCAmelCase__   = parent
							lowerCAmelCase__   = batch_size
							lowerCAmelCase__   = num_channels
							lowerCAmelCase__   = image_size
							lowerCAmelCase__   = min_resolution
							lowerCAmelCase__   = max_resolution
							lowerCAmelCase__   = size
							lowerCAmelCase__   = do_normalize
							lowerCAmelCase__   = do_convert_rgb
							lowerCAmelCase__   = [512, 1024, 2048, 4096]
							lowerCAmelCase__   = patch_size if patch_size is not None else {"""height""": 16, """width""": 16}




					def     _SCREAMING_SNAKE_CASE    (						self    :  str  ):
							return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}




					def     _SCREAMING_SNAKE_CASE    (						self    :  Optional[int]  ):
							lowerCAmelCase__   = """https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"""
							lowerCAmelCase__   = Image.open(requests.get(snake_case__	,    stream=snake_case__  ).raw  ).convert("""RGB"""  )
							return raw_image

@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11			,		reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`."			,		)
@require_torch
@require_vision
class    a_   (  __UpperCamelCase			,		unittest.TestCase      ):
					UpperCamelCase_			:						Optional[Any]      =     PixaStructImageProcessor if is_vision_available() else None




					def     _SCREAMING_SNAKE_CASE    (						self    :  Tuple  ):
							lowerCAmelCase__   = PixaStructImageProcessingTester(self  )




					@property
					def     _SCREAMING_SNAKE_CASE    (						self    :  Any  ):
							return self.image_processor_tester.prepare_image_processor_dict()




					def     _SCREAMING_SNAKE_CASE    (						self    :  Any  ):
							lowerCAmelCase__   = self.image_processing_class(**self.image_processor_dict  )
							self.assertTrue(hasattr(snake_case__	,    """do_normalize"""  )  )
							self.assertTrue(hasattr(snake_case__	,    """do_convert_rgb"""  )  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  List[str]  ):
							lowerCAmelCase__   = self.image_processor_tester.prepare_dummy_image()

							lowerCAmelCase__   = self.image_processing_class(**self.image_processor_dict  )
							lowerCAmelCase__   = 2048

							lowerCAmelCase__   = image_processor(snake_case__	,    return_tensors="""pt"""	,    max_patches=snake_case__  )
							self.assertTrue(torch.allclose(inputs.flattened_patches.mean()	,    torch.tensor(0.0606  )	,    atol=1E-3	,    rtol=1E-3  )  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  Dict  ):
							# Initialize image_processor
							lowerCAmelCase__   = self.image_processing_class(**self.image_processor_dict  )
							# create random PIL images
							lowerCAmelCase__   = prepare_image_inputs(self.image_processor_tester	,    equal_resolution=snake_case__  )
							for image in image_inputs:
									self.assertIsInstance(snake_case__	,    Image.Image  )

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

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

									# Test batched
									lowerCAmelCase__   = image_processor(
									    snake_case__	,    return_tensors="""pt"""	,    max_patches=snake_case__  ).flattened_patches
									self.assertEqual(
									    encoded_images.shape	,    (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)	,    )




					def     _SCREAMING_SNAKE_CASE    (						self    :  str  ):
							# Initialize image_processor
							lowerCAmelCase__   = self.image_processing_class(**self.image_processor_dict  )
							# create random PIL images
							lowerCAmelCase__   = prepare_image_inputs(self.image_processor_tester	,    equal_resolution=snake_case__  )
							for image in image_inputs:
									self.assertIsInstance(snake_case__	,    Image.Image  )

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

							lowerCAmelCase__   = True

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

									lowerCAmelCase__   = """Hello"""

									lowerCAmelCase__   = image_processor(
									    image_inputs[0]	,    return_tensors="""pt"""	,    max_patches=snake_case__	,    header_text=snake_case__  ).flattened_patches
									self.assertEqual(
									    encoded_images.shape	,    (1, max_patch, expected_hidden_dim)	,    )

									# Test batched
									lowerCAmelCase__   = image_processor(
									    snake_case__	,    return_tensors="""pt"""	,    max_patches=snake_case__	,    header_text=snake_case__  ).flattened_patches
									self.assertEqual(
									    encoded_images.shape	,    (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)	,    )




					def     _SCREAMING_SNAKE_CASE    (						self    :  Dict  ):
							# Initialize image_processor
							lowerCAmelCase__   = self.image_processing_class(**self.image_processor_dict  )
							# create random numpy tensors
							lowerCAmelCase__   = prepare_image_inputs(self.image_processor_tester	,    equal_resolution=snake_case__	,    numpify=snake_case__  )
							for image in image_inputs:
									self.assertIsInstance(snake_case__	,    np.ndarray  )

							lowerCAmelCase__   = (
							    (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
							    * self.image_processor_tester.num_channels
							) + 2

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

									# Test batched
									lowerCAmelCase__   = image_processor(
									    snake_case__	,    return_tensors="""pt"""	,    max_patches=snake_case__  ).flattened_patches
									self.assertEqual(
									    encoded_images.shape	,    (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)	,    )




					def     _SCREAMING_SNAKE_CASE    (						self    :  Dict  ):
							# Initialize image_processor
							lowerCAmelCase__   = self.image_processing_class(**self.image_processor_dict  )
							# create random PyTorch tensors
							lowerCAmelCase__   = prepare_image_inputs(self.image_processor_tester	,    equal_resolution=snake_case__	,    torchify=snake_case__  )
							for image in image_inputs:
									self.assertIsInstance(snake_case__	,    torch.Tensor  )

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

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

									# Test batched
									lowerCAmelCase__   = image_processor(
									    snake_case__	,    return_tensors="""pt"""	,    max_patches=snake_case__  ).flattened_patches
									self.assertEqual(
									    encoded_images.shape	,    (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)	,    )

@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11			,		reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`."			,		)
@require_torch
@require_vision
class    a_   (  __UpperCamelCase			,		unittest.TestCase      ):
					UpperCamelCase_			:						List[Any]      =     PixaStructImageProcessor if is_vision_available() else None




					def     _SCREAMING_SNAKE_CASE    (						self    :  Optional[int]  ):
							lowerCAmelCase__   = PixaStructImageProcessingTester(self	,    num_channels=4  )
							lowerCAmelCase__   = 3




					@property
					def     _SCREAMING_SNAKE_CASE    (						self    :  Optional[Any]  ):
							return self.image_processor_tester.prepare_image_processor_dict()




					def     _SCREAMING_SNAKE_CASE    (						self    :  int  ):
							lowerCAmelCase__   = self.image_processing_class(**self.image_processor_dict  )
							self.assertTrue(hasattr(snake_case__	,    """do_normalize"""  )  )
							self.assertTrue(hasattr(snake_case__	,    """do_convert_rgb"""  )  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  Union[str, Any]  ):
							# Initialize image_processor
							lowerCAmelCase__   = self.image_processing_class(**self.image_processor_dict  )
							# create random PIL images
							lowerCAmelCase__   = prepare_image_inputs(self.image_processor_tester	,    equal_resolution=snake_case__  )
							for image in image_inputs:
									self.assertIsInstance(snake_case__	,    Image.Image  )

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

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

									# Test batched
									lowerCAmelCase__   = image_processor(
									    snake_case__	,    return_tensors="""pt"""	,    max_patches=snake_case__  ).flattened_patches
									self.assertEqual(
									    encoded_images.shape	,    (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)	,    )




