


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        lowerCamelCase__	:






			"""simple docstring"""






			def __init__(							self      ,						snake_case      ,						snake_case=3      ,						snake_case=32      ,						snake_case=3      ,						snake_case=10      ,						snake_case=[10, 20, 30, 40]      ,						snake_case=[1, 1, 2, 1]      ,						snake_case=True      ,						snake_case=True      ,						snake_case="relu"      ,						snake_case=3      ,						snake_case=None      ,						):

						'''simple docstring'''


						UpperCamelCase__					=       parent
						UpperCamelCase__					=       batch_size
						UpperCamelCase__					=       image_size
						UpperCamelCase__					=       num_channels
						UpperCamelCase__					=       embeddings_size
						UpperCamelCase__					=       hidden_sizes
						UpperCamelCase__					=       depths
						UpperCamelCase__					=       is_training
						UpperCamelCase__					=       use_labels
						UpperCamelCase__					=       hidden_act
						UpperCamelCase__					=       num_labels
						UpperCamelCase__					=       scope
						UpperCamelCase__					=       len(snake_case     )




			def 				snake_case__				(							self     ):

						'''simple docstring'''


						UpperCamelCase__					=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

						UpperCamelCase__					=       self.get_config()

						return config, pixel_values, labels




			def 				snake_case__				(							self     ):

						'''simple docstring'''


						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 				snake_case__				(							self      ,						snake_case      ,						snake_case      ,						snake_case     ):

						'''simple docstring'''


						UpperCamelCase__					=       TFResNetModel(config=snake_case     )
						UpperCamelCase__					=       model(snake_case     )
						# 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 				snake_case__				(							self      ,						snake_case      ,						snake_case      ,						snake_case     ):

						'''simple docstring'''


						UpperCamelCase__					=       self.num_labels
						UpperCamelCase__					=       TFResNetForImageClassification(snake_case     )
						UpperCamelCase__					=       model(snake_case      ,						labels=snake_case     )
						self.parent.assertEqual(result.logits.shape      ,						(self.batch_size, self.num_labels)     )







			def 				snake_case__				(							self     ):

						'''simple docstring'''


						UpperCamelCase__					=       self.prepare_config_and_inputs()
						UpperCamelCase__,      UpperCamelCase__,      UpperCamelCase__					=       config_and_inputs
						UpperCamelCase__					=       {"pixel_values": pixel_values}
						return config, inputs_dict







@require_tf
class        lowerCamelCase__	(							UpperCAmelCase					,	UpperCAmelCase					,	unittest.TestCase      ):






			"""simple docstring"""






			_UpperCamelCase		:					int    =		(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
			_UpperCamelCase		:					str    =		(
			    {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
			    if is_tf_available()
			    else {}
			)

			_UpperCamelCase		:					Union[str, Any]    =		False
			_UpperCamelCase		:					List[Any]    =		False
			_UpperCamelCase		:					List[Any]    =		False
			_UpperCamelCase		:					List[Any]    =		False
			_UpperCamelCase		:					List[str]    =		False




			def 				snake_case__				(							self     ):

						'''simple docstring'''


						UpperCamelCase__					=       TFResNetModelTester(self     )
						UpperCamelCase__					=       ConfigTester(self      ,						config_class=snake_case      ,						has_text_modality=snake_case     )




			def 				snake_case__				(							self     ):

						'''simple docstring'''


						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 				snake_case__				(							self     ):

						'''simple docstring'''


						return




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

						'''simple docstring'''


						pass




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

						'''simple docstring'''


						pass




			def 				snake_case__				(							self     ):

						'''simple docstring'''


						UpperCamelCase__,      UpperCamelCase__					=       self.model_tester.prepare_config_and_inputs_for_common()

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

									UpperCamelCase__					=       ["pixel_values"]
									self.assertListEqual(arg_names[:1]      ,						snake_case     )




			def 				snake_case__				(							self     ):

						'''simple docstring'''


						UpperCamelCase__					=       self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*snake_case     )




			def 				snake_case__				(							self     ):

						'''simple docstring'''


						def check_hidden_states_output(snake_case      ,						snake_case      ,						snake_case     ):
									UpperCamelCase__					=       model_class(snake_case     )
									UpperCamelCase__					=       model(**self._prepare_for_class(snake_case      ,						snake_case     )     )

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

									UpperCamelCase__					=       self.model_tester.num_stages
									self.assertEqual(len(snake_case     )      ,						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]      ,						)

						UpperCamelCase__,      UpperCamelCase__					=       self.model_tester.prepare_config_and_inputs_for_common()
						UpperCamelCase__					=       ["basic", "bottleneck"]
						for model_class in self.all_model_classes:
									for layer_type in layers_type:
												UpperCamelCase__					=       layer_type
												UpperCamelCase__					=       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"]
												UpperCamelCase__					=       True

												check_hidden_states_output(snake_case      ,						snake_case      ,						snake_case     )




			def 				snake_case__				(							self     ):

						'''simple docstring'''


						UpperCamelCase__					=       self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*snake_case     )







			@slow
			def 				snake_case__				(							self     ):

						'''simple docstring'''


						for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									UpperCamelCase__					=       TFResNetModel.from_pretrained(snake_case     )
									self.assertIsNotNone(snake_case     )



def        UpperCamelCase_(				)->		str:
			UpperCamelCase__					=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
			return image







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






			"""simple docstring"""






			@cached_property
			def 				snake_case__				(							self     ):

						'''simple docstring'''


						return (
						    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )
						    if is_vision_available()
						    else None
						)







			@slow
			def 				snake_case__				(							self     ):

						'''simple docstring'''


						UpperCamelCase__					=       TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )

						UpperCamelCase__					=       self.default_image_processor
						UpperCamelCase__					=       prepare_img()
						UpperCamelCase__					=       image_processor(images=snake_case      ,						return_tensors="tf"     )

						# forward pass
						UpperCamelCase__					=       model(**snake_case     )

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

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

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






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_torch_available,
)


__UpperCamelCase    		=       {
    'configuration_trocr': ['TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TrOCRConfig'],
    'processing_trocr': ['TrOCRProcessor'],
}


try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						__UpperCamelCase    		=       [
						    'TROCR_PRETRAINED_MODEL_ARCHIVE_LIST',
						    'TrOCRForCausalLM',
						    'TrOCRPreTrainedModel',
						]


if TYPE_CHECKING:
						from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
						from .processing_trocr import TrOCRProcessor

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel

else:
						import sys

						__UpperCamelCase    		=       _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)


