



from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
							from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor
class 				_snake_case			:




				def __init__(						self					:						Tuple,					__lowercase					:						Union[str, Any],					__lowercase					:						Any=3,					__lowercase					:						str=32,					__lowercase					:						List[str]=3,					__lowercase					:						Union[str, Any]=10,					__lowercase					:						Tuple=[10, 20, 30, 40],					__lowercase					:						Optional[int]=[1, 1, 2, 1],					__lowercase					:						Union[str, Any]=True,					__lowercase					:						Dict=True,					__lowercase					:						int="relu",					__lowercase					:						Dict=3,					__lowercase					:						List[str]=None,					):
							lowercase__					  =				parent
							lowercase__					  =				batch_size
							lowercase__					  =				image_size
							lowercase__					  =				num_channels
							lowercase__					  =				embeddings_size
							lowercase__					  =				hidden_sizes
							lowercase__					  =				depths
							lowercase__					  =				is_training
							lowercase__					  =				use_labels
							lowercase__					  =				hidden_act
							lowercase__					  =				num_labels
							lowercase__					  =				scope
							lowercase__					  =				len(__lowercase						)




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

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

							lowercase__					  =				self.get_config()

							return config, pixel_values, labels




				def 							A__      (						self					:						str						):
							return ResNetConfig(
							    num_channels=self.num_channels,					embeddings_size=self.embeddings_size,					hidden_sizes=self.hidden_sizes,					depths=self.depths,					hidden_act=self.hidden_act,					num_labels=self.num_labels,					image_size=self.image_size,					)




				def 							A__      (						self					:						Tuple,					__lowercase					:						Optional[Any],					__lowercase					:						Dict,					__lowercase					:						Dict						):
							lowercase__					  =				TFResNetModel(config=__lowercase						)
							lowercase__					  =				model(__lowercase						)
							# expected last hidden states: B, C, H // 32, W // 32
							self.parent.assertEqual(
							    result.last_hidden_state.shape,					(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32),					)




				def 							A__      (						self					:						Any,					__lowercase					:						Dict,					__lowercase					:						Optional[int],					__lowercase					:						List[Any]						):
							lowercase__					  =				self.num_labels
							lowercase__					  =				TFResNetForImageClassification(__lowercase						)
							lowercase__					  =				model(__lowercase,					labels=__lowercase						)
							self.parent.assertEqual(result.logits.shape,					(self.batch_size, self.num_labels)						)




				def 							A__      (						self					:						Any						):
							lowercase__					  =				self.prepare_config_and_inputs()
							lowercase__  ,       lowercase__  ,       lowercase__					  =				config_and_inputs
							lowercase__					  =				{"pixel_values": pixel_values}
							return config, inputs_dict
@require_tf
class 				_snake_case			(					lowercase__    ,	lowercase__    ,	unittest.TestCase):
				UpperCamelCase__				:					Optional[Any]     		=(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
				UpperCamelCase__				:					List[Any]     		=(
				    {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification}
				    if is_tf_available()
				    else {}
				)

				UpperCamelCase__				:					List[str]     		=False
				UpperCamelCase__				:					int     		=False
				UpperCamelCase__				:					Any     		=False
				UpperCamelCase__				:					Union[str, Any]     		=False
				UpperCamelCase__				:					Dict     		=False




				def 							A__      (						self					:						Optional[Any]						):
							lowercase__					  =				TFResNetModelTester(self						)
							lowercase__					  =				ConfigTester(self,					config_class=__lowercase,					has_text_modality=__lowercase						)




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




				@unittest.skip(reason="ResNet does not use inputs_embeds"						)
				def 							A__      (						self					:						Dict						):
							pass




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




				def 							A__      (						self					:						Any						):
							lowercase__  ,       lowercase__					  =				self.model_tester.prepare_config_and_inputs_for_common()

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

										lowercase__					  =				["pixel_values"]
										self.assertListEqual(arg_names[:1],					__lowercase						)




				def 							A__      (						self					:						Tuple						):
							lowercase__					  =				self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__lowercase						)




				def 							A__      (						self					:						Optional[int]						):
							def check_hidden_states_output(__lowercase					:						Optional[int],					__lowercase					:						str,					__lowercase					:						Dict						):
										lowercase__					  =				model_class(__lowercase						)
										lowercase__					  =				model(**self._prepare_for_class(__lowercase,					__lowercase						)						)

										lowercase__					  =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

										lowercase__					  =				self.model_tester.num_stages
										self.assertEqual(len(__lowercase						),					expected_num_stages + 1						)

										# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
										self.assertListEqual(
										    list(hidden_states[0].shape[-2:]						),					[self.model_tester.image_size // 4, self.model_tester.image_size // 4],					)

							lowercase__  ,       lowercase__					  =				self.model_tester.prepare_config_and_inputs_for_common()
							lowercase__					  =				["basic", "bottleneck"]
							for model_class in self.all_model_classes:
										for layer_type in layers_type:
													lowercase__					  =				layer_type
													lowercase__					  =				True
													check_hidden_states_output(__lowercase,					__lowercase,					__lowercase						)

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

													check_hidden_states_output(__lowercase,					__lowercase,					__lowercase						)




				def 							A__      (						self					:						str						):
							lowercase__					  =				self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__lowercase						)




				@slow
				def 							A__      (						self					:						Optional[Any]						):
							for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										lowercase__					  =				TFResNetModel.from_pretrained(__lowercase						)
										self.assertIsNotNone(__lowercase						)



def __lowerCAmelCase (     ):
			lowercase__					  =				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
			return image




@require_tf
@require_vision
class 				_snake_case			(					unittest.TestCase):




				@cached_property
				def 							A__      (						self					:						Dict						):
							return (
							    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
							    if is_vision_available()
							    else None
							)




				@slow
				def 							A__      (						self					:						List[str]						):
							lowercase__					  =				TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)

							lowercase__					  =				self.default_image_processor
							lowercase__					  =				prepare_img()
							lowercase__					  =				image_processor(images=__lowercase,					return_tensors="tf"						)

							# forward pass
							lowercase__					  =				model(**__lowercase						)

							# verify the logits
							lowercase__					  =				tf.TensorShape((1, 1000)						)
							self.assertEqual(outputs.logits.shape,					__lowercase						)

							lowercase__					  =				tf.constant([-11.1069, -9.7877, -8.3777]						)

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









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:
							lowercase_								=     False

if is_vision_available():
							from PIL import Image

							from transformers import PixaStructImageProcessor
class 				_snake_case			(					unittest.TestCase):




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




				def 							A__      (						self					:						List[str]						):
							return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}




				def 							A__      (						self					:						Any						):
							lowercase__					  =				"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"
							lowercase__					  =				Image.open(requests.get(__lowercase,					stream=__lowercase						).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 				_snake_case			(					lowercase__    ,	unittest.TestCase):
				UpperCamelCase__				:					Any     		=PixaStructImageProcessor if is_vision_available() else None




				def 							A__      (						self					:						Any						):
							lowercase__					  =				PixaStructImageProcessingTester(self						)




				@property
				def 							A__      (						self					:						Union[str, Any]						):
							return self.image_processor_tester.prepare_image_processor_dict()




				def 							A__      (						self					:						Optional[Any]						):
							lowercase__					  =				self.image_processing_class(**self.image_processor_dict						)
							self.assertTrue(hasattr(__lowercase,					"do_normalize"						)						)
							self.assertTrue(hasattr(__lowercase,					"do_convert_rgb"						)						)




				def 							A__      (						self					:						Optional[int]						):
							lowercase__					  =				self.image_processor_tester.prepare_dummy_image()

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

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




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

							# Test not batched input
							lowercase__					  =				(
							    (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
										lowercase__					  =				image_processor(
										    image_inputs[0],					return_tensors="pt",					max_patches=__lowercase						).flattened_patches
										self.assertEqual(
										    encoded_images.shape,					(1, max_patch, expected_hidden_dim),					)

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




				def 							A__      (						self					:						int						):
							# Initialize image_processor
							lowercase__					  =				self.image_processing_class(**self.image_processor_dict						)
							# create random PIL images
							lowercase__					  =				prepare_image_inputs(self.image_processor_tester,					equal_resolution=__lowercase						)
							for image in image_inputs:
										self.assertIsInstance(__lowercase,					Image.Image						)

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

							lowercase__					  =				True

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

										lowercase__					  =				"Hello"

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

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




				def 							A__      (						self					:						Tuple						):
							# Initialize image_processor
							lowercase__					  =				self.image_processing_class(**self.image_processor_dict						)
							# create random numpy tensors
							lowercase__					  =				prepare_image_inputs(self.image_processor_tester,					equal_resolution=__lowercase,					numpify=__lowercase						)
							for image in image_inputs:
										self.assertIsInstance(__lowercase,					np.ndarray						)

							lowercase__					  =				(
							    (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
										lowercase__					  =				image_processor(
										    image_inputs[0],					return_tensors="pt",					max_patches=__lowercase						).flattened_patches
										self.assertEqual(
										    encoded_images.shape,					(1, max_patch, expected_hidden_dim),					)

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




				def 							A__      (						self					:						Any						):
							# Initialize image_processor
							lowercase__					  =				self.image_processing_class(**self.image_processor_dict						)
							# create random PyTorch tensors
							lowercase__					  =				prepare_image_inputs(self.image_processor_tester,					equal_resolution=__lowercase,					torchify=__lowercase						)
							for image in image_inputs:
										self.assertIsInstance(__lowercase,					torch.Tensor						)

							# Test not batched input
							lowercase__					  =				(
							    (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
										lowercase__					  =				image_processor(
										    image_inputs[0],					return_tensors="pt",					max_patches=__lowercase						).flattened_patches
										self.assertEqual(
										    encoded_images.shape,					(1, max_patch, expected_hidden_dim),					)

										# Test batched
										lowercase__					  =				image_processor(
										    __lowercase,					return_tensors="pt",					max_patches=__lowercase						).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 				_snake_case			(					lowercase__    ,	unittest.TestCase):
				UpperCamelCase__				:					Optional[int]     		=PixaStructImageProcessor if is_vision_available() else None




				def 							A__      (						self					:						Optional[int]						):
							lowercase__					  =				PixaStructImageProcessingTester(self,					num_channels=4						)
							lowercase__					  =				3




				@property
				def 							A__      (						self					:						Union[str, Any]						):
							return self.image_processor_tester.prepare_image_processor_dict()




				def 							A__      (						self					:						Dict						):
							lowercase__					  =				self.image_processing_class(**self.image_processor_dict						)
							self.assertTrue(hasattr(__lowercase,					"do_normalize"						)						)
							self.assertTrue(hasattr(__lowercase,					"do_convert_rgb"						)						)




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

							# Test not batched input
							lowercase__					  =				(
							    (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
										lowercase__					  =				image_processor(
										    image_inputs[0],					return_tensors="pt",					max_patches=__lowercase						).flattened_patches
										self.assertEqual(
										    encoded_images.shape,					(1, max_patch, expected_hidden_dim),					)

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




