



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

from transformers.testing_utils import is_flaky, 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

if is_vision_available():
							from PIL import Image

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




				def __init__(						self					:						Dict,					__lowercase					:						int,					__lowercase					:						Union[str, Any]=7,					__lowercase					:						Union[str, Any]=3,					__lowercase					:						Any=18,					__lowercase					:						Union[str, Any]=30,					__lowercase					:						Any=400,					__lowercase					:						List[str]=True,					__lowercase					:						Dict=None,					__lowercase					:						List[str]=True,					__lowercase					:						int=False,					__lowercase					:						Union[str, Any]=True,					__lowercase					:						str=True,					__lowercase					:						Optional[int]=[0.5, 0.5, 0.5],					__lowercase					:						List[Any]=[0.5, 0.5, 0.5],					):
							lowercase__					  =				parent
							lowercase__					  =				batch_size
							lowercase__					  =				num_channels
							lowercase__					  =				image_size
							lowercase__					  =				min_resolution
							lowercase__					  =				max_resolution
							lowercase__					  =				do_resize
							lowercase__					  =				size if size is not None else {"height": 18, "width": 20}
							lowercase__					  =				do_thumbnail
							lowercase__					  =				do_align_axis
							lowercase__					  =				do_pad
							lowercase__					  =				do_normalize
							lowercase__					  =				image_mean
							lowercase__					  =				image_std




				def 							A__      (						self					:						Optional[Any]						):
							return {
							    "do_resize": self.do_resize,
							    "size": self.size,
							    "do_thumbnail": self.do_thumbnail,
							    "do_align_long_axis": self.do_align_axis,
							    "do_pad": self.do_pad,
							    "do_normalize": self.do_normalize,
							    "image_mean": self.image_mean,
							    "image_std": self.image_std,
							}
@require_torch
@require_vision
class 				_snake_case			(					lowercase__    ,	unittest.TestCase):
				UpperCamelCase__				:					Optional[int]     		=DonutImageProcessor if is_vision_available() else None




				def 							A__      (						self					:						str						):
							lowercase__					  =				DonutImageProcessingTester(self						)




				@property
				def 							A__      (						self					:						List[str]						):
							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_resize"						)						)
							self.assertTrue(hasattr(__lowercase,					"size"						)						)
							self.assertTrue(hasattr(__lowercase,					"do_thumbnail"						)						)
							self.assertTrue(hasattr(__lowercase,					"do_align_long_axis"						)						)
							self.assertTrue(hasattr(__lowercase,					"do_pad"						)						)
							self.assertTrue(hasattr(__lowercase,					"do_normalize"						)						)
							self.assertTrue(hasattr(__lowercase,					"image_mean"						)						)
							self.assertTrue(hasattr(__lowercase,					"image_std"						)						)




				def 							A__      (						self					:						str						):
							lowercase__					  =				self.image_processing_class.from_dict(self.image_processor_dict						)
							self.assertEqual(image_processor.size,					{"height": 18, "width": 20}						)

							lowercase__					  =				self.image_processing_class.from_dict(self.image_processor_dict,					size=42						)
							self.assertEqual(image_processor.size,					{"height": 42, "width": 42}						)

							# Previous config had dimensions in (width, height) order
							lowercase__					  =				self.image_processing_class.from_dict(self.image_processor_dict,					size=(42, 84)						)
							self.assertEqual(image_processor.size,					{"height": 84, "width": 42}						)




				def 							A__      (						self					:						List[str]						):
							pass




				@is_flaky()
				def 							A__      (						self					:						Dict						):
							# Initialize image_processing
							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__					  =				image_processing(image_inputs[0],					return_tensors="pt"						).pixel_values
							self.assertEqual(
							    encoded_images.shape,					(
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["height"],
							        self.image_processor_tester.size["width"],
							    ),					)

							# Test batched
							lowercase__					  =				image_processing(__lowercase,					return_tensors="pt"						).pixel_values
							self.assertEqual(
							    encoded_images.shape,					(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["height"],
							        self.image_processor_tester.size["width"],
							    ),					)




				@is_flaky()
				def 							A__      (						self					:						Optional[Any]						):
							# Initialize image_processing
							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						)

							# Test not batched input
							lowercase__					  =				image_processing(image_inputs[0],					return_tensors="pt"						).pixel_values
							self.assertEqual(
							    encoded_images.shape,					(
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["height"],
							        self.image_processor_tester.size["width"],
							    ),					)

							# Test batched
							lowercase__					  =				image_processing(__lowercase,					return_tensors="pt"						).pixel_values
							self.assertEqual(
							    encoded_images.shape,					(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["height"],
							        self.image_processor_tester.size["width"],
							    ),					)




				@is_flaky()
				def 							A__      (						self					:						Tuple						):
							# Initialize image_processing
							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__					  =				image_processing(image_inputs[0],					return_tensors="pt"						).pixel_values
							self.assertEqual(
							    encoded_images.shape,					(
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["height"],
							        self.image_processor_tester.size["width"],
							    ),					)

							# Test batched
							lowercase__					  =				image_processing(__lowercase,					return_tensors="pt"						).pixel_values
							self.assertEqual(
							    encoded_images.shape,					(
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.size["height"],
							        self.image_processor_tester.size["width"],
							    ),					)




