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

					def __init__(    self      :       List[Any],_A      :       Dict,_A      :       List[Any]=3,_A      :       Optional[int]=32,_A      :       str=3,_A      :       Optional[int]=10,_A      :       int=[10, 20, 30, 40],_A      :       str=[1, 1, 2, 1],_A      :       Tuple=True,_A      :       List[Any]=True,_A      :       int="relu",_A      :       List[Any]=3,_A      :       Dict=None,):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    parent
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    batch_size
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    image_size
							SCREAMING_SNAKE_CASE_  :		int				      =    num_channels
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    embeddings_size
							SCREAMING_SNAKE_CASE_  :		int				      =    hidden_sizes
							SCREAMING_SNAKE_CASE_  :		Dict				      =    depths
							SCREAMING_SNAKE_CASE_  :		int				      =    is_training
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    use_labels
							SCREAMING_SNAKE_CASE_  :		Dict				      =    hidden_act
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    num_labels
							SCREAMING_SNAKE_CASE_  :		int				      =    scope
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    len(_A    )

					def 				__UpperCamelCase   (    self      :       Union[str, Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

							SCREAMING_SNAKE_CASE_  :		Dict				      =    None
							if self.use_labels:
									SCREAMING_SNAKE_CASE_  :		Any				      =    ids_tensor([self.batch_size],self.num_labels    )

							SCREAMING_SNAKE_CASE_  :		Dict				      =    self.get_config()

							return config, pixel_values, labels

					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""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 				__UpperCamelCase   (    self      :       Optional[Any],_A      :       int,_A      :       Tuple,_A      :       Union[str, Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		str				      =    TFResNetModel(config=_A    )
							SCREAMING_SNAKE_CASE_  :		str				      =    model(_A    )
							# 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 				__UpperCamelCase   (    self      :       Dict,_A      :       int,_A      :       Optional[Any],_A      :       Dict    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Dict				      =    self.num_labels
							SCREAMING_SNAKE_CASE_  :		str				      =    TFResNetForImageClassification(_A    )
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    model(_A,labels=_A    )
							self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels)    )






					def 				__UpperCamelCase   (    self      :       Union[str, Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    self.prepare_config_and_inputs()
							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Any				      =    config_and_inputs
							SCREAMING_SNAKE_CASE_  :		Dict				      =    {"pixel_values": pixel_values}
							return config, inputs_dict







@require_tf
class 		a__						(					A__    ,		A__    ,		unittest.TestCase					):
					A	       =							(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
					A	       =							(
					    {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
					    if is_tf_available()
					    else {}
					)

					A	       =							False
					A	       =							False
					A	       =							False
					A	       =							False
					A	       =							False

					def 				__UpperCamelCase   (    self      :       List[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    TFResNetModelTester(self    )
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    ConfigTester(self,config_class=_A,has_text_modality=_A    )

					def 				__UpperCamelCase   (    self      :       str    ):







							"""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 				__UpperCamelCase   (    self      :       Union[str, Any]    ):







							"""simple docstring"""






							return

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







							"""simple docstring"""






							pass

					@unittest.skip(reason="ResNet does not support input and output embeddings"    )
					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							pass

					def 				__UpperCamelCase   (    self      :       Tuple    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		List[Any]				      =    self.model_tester.prepare_config_and_inputs_for_common()

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

									SCREAMING_SNAKE_CASE_  :		List[Any]				      =    ["pixel_values"]
									self.assertListEqual(arg_names[:1],_A    )

					def 				__UpperCamelCase   (    self      :       str    ):







							"""simple docstring"""






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

					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






							def check_hidden_states_output(_A      :       int,_A      :       Tuple,_A      :       str    ):
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    model_class(_A    )
									SCREAMING_SNAKE_CASE_  :		Dict				      =    model(**self._prepare_for_class(_A,_A    )    )

									SCREAMING_SNAKE_CASE_  :		List[Any]				      =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

									SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    self.model_tester.num_stages
									self.assertEqual(len(_A    ),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],)

							SCREAMING_SNAKE_CASE_      ,    SCREAMING_SNAKE_CASE_  :		Any				      =    self.model_tester.prepare_config_and_inputs_for_common()
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    ["basic", "bottleneck"]
							for model_class in self.all_model_classes:
									for layer_type in layers_type:
											SCREAMING_SNAKE_CASE_  :		List[str]				      =    layer_type
											SCREAMING_SNAKE_CASE_  :		str				      =    True
											check_hidden_states_output(_A,_A,_A    )

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											SCREAMING_SNAKE_CASE_  :		Tuple				      =    True

											check_hidden_states_output(_A,_A,_A    )

					def 				__UpperCamelCase   (    self      :       int    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Tuple				      =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_A    )






					@slow
					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""simple docstring"""






							for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    TFResNetModel.from_pretrained(_A    )
									self.assertIsNotNone(_A    )







def       _snake_case	(   ):
		"""simple docstring"""







		SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
		return image







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

					@cached_property
					def 				__UpperCamelCase   (    self      :       Optional[int]    ):







							"""simple docstring"""






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






					@slow
					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Tuple				      =    TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )

							SCREAMING_SNAKE_CASE_  :		int				      =    self.default_image_processor
							SCREAMING_SNAKE_CASE_  :		Dict				      =    prepare_img()
							SCREAMING_SNAKE_CASE_  :		int				      =    image_processor(images=_A,return_tensors="tf"    )

							# forward pass
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    model(**_A    )

							# verify the logits
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    tf.TensorShape((1, 1000)    )
							self.assertEqual(outputs.logits.shape,_A    )

							SCREAMING_SNAKE_CASE_  :		Tuple				      =    tf.constant([-11.1069, -9.7877, -8.3777]    )

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







from typing import TYPE_CHECKING

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


__A				:    Union[str, Any]       =   {
    "configuration_speech_to_text": ["SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Speech2TextConfig"],
    "processing_speech_to_text": ["Speech2TextProcessor"],
}

try:
				if not is_sentencepiece_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				__A				:    List[Any]       =   ["Speech2TextTokenizer"]

try:
				if not is_speech_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				__A				:    List[Any]       =   ["Speech2TextFeatureExtractor"]

try:
				if not is_tf_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				__A				:    int       =   [
				    "TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST",
				    "TFSpeech2TextForConditionalGeneration",
				    "TFSpeech2TextModel",
				    "TFSpeech2TextPreTrainedModel",
				]

try:
				if not is_torch_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				__A				:    Tuple       =   [
				    "SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST",
				    "Speech2TextForConditionalGeneration",
				    "Speech2TextModel",
				    "Speech2TextPreTrainedModel",
				]


if TYPE_CHECKING:
				from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig
				from .processing_speech_to_text import SpeechaTextProcessor

				try:
								if not is_sentencepiece_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .tokenization_speech_to_text import SpeechaTextTokenizer

				try:
								if not is_speech_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor

				try:
								if not is_tf_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_tf_speech_to_text import (
								    TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
								    TFSpeechaTextForConditionalGeneration,
								    TFSpeechaTextModel,
								    TFSpeechaTextPreTrainedModel,
								)

				try:
								if not is_torch_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_speech_to_text import (
								    SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
								    SpeechaTextForConditionalGeneration,
								    SpeechaTextModel,
								    SpeechaTextPreTrainedModel,
								)

else:
				import sys

				__A				:    Dict       =   _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)



