

"""simple docstring"""





from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging


if is_torch_available():
							import torch


__UpperCamelCase  :      str							      =		logging.get_logger(__name__)







class 				SCREAMING_SNAKE_CASE					(		a_       ):






					"""simple docstring"""



					lowercase__				 =       ["pixel_values"]







					def __init__(       self			:				List[str]   ,lowercase_			:				bool = True   ,lowercase_			:				Optional[Dict[str, int]] = None   ,lowercase_			:				PILImageResampling = PILImageResampling.BILINEAR   ,lowercase_			:				bool = True   ,lowercase_			:				Dict[str, int] = None   ,lowercase_			:				bool = True   ,lowercase_			:				Union[int, float] = 1 / 2_5_5   ,lowercase_			:				bool = True   ,lowercase_			:				Optional[Union[float, List[float]]] = None   ,lowercase_			:				Optional[Union[float, List[float]]] = None   ,**lowercase_			:				int   ,):
						super().__init__(**lowercase_		)
						lowerCAmelCase__	:						int  				=	size if size is not None else {'''shortest_edge''': 2_5_6}
						lowerCAmelCase__	:						Dict  				=	get_size_dict(lowercase_   ,default_to_square=lowercase_		)
						lowerCAmelCase__	:						Optional[int]  				=	crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
						lowerCAmelCase__	:						Dict  				=	get_size_dict(lowercase_   ,param_name='''crop_size'''		)
						lowerCAmelCase__	:						Optional[int]  				=	do_resize
						lowerCAmelCase__	:						List[str]  				=	size
						lowerCAmelCase__	:						Tuple  				=	resample
						lowerCAmelCase__	:						str  				=	do_center_crop
						lowerCAmelCase__	:						int  				=	crop_size
						lowerCAmelCase__	:						Any  				=	do_rescale
						lowerCAmelCase__	:						Optional[Any]  				=	rescale_factor
						lowerCAmelCase__	:						int  				=	do_normalize
						lowerCAmelCase__	:						Optional[int]  				=	image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
						lowerCAmelCase__	:						Dict  				=	image_std if image_std is not None else IMAGENET_STANDARD_STD







					def        __lowerCAmelCase (       self			:				Optional[Any]   ,lowercase_			:				np.ndarray   ,lowercase_			:				Dict[str, int]   ,lowercase_			:				PILImageResampling = PILImageResampling.BICUBIC   ,lowercase_			:				Optional[Union[str, ChannelDimension]] = None   ,**lowercase_			:				Union[str, Any]   ,):
						lowerCAmelCase__	:						Tuple  				=	get_size_dict(lowercase_   ,default_to_square=lowercase_		)
						if "shortest_edge" not in size:
							raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'		)
						lowerCAmelCase__	:						Optional[int]  				=	get_resize_output_image_size(lowercase_   ,size=size['''shortest_edge''']   ,default_to_square=lowercase_		)
						return resize(lowercase_   ,size=lowercase_   ,resample=lowercase_   ,data_format=lowercase_   ,**lowercase_		)







					def        __lowerCAmelCase (       self			:				List[Any]   ,lowercase_			:				np.ndarray   ,lowercase_			:				Dict[str, int]   ,lowercase_			:				Optional[Union[str, ChannelDimension]] = None   ,**lowercase_			:				Any   ,):
						lowerCAmelCase__	:						List[str]  				=	get_size_dict(lowercase_		)
						if "height" not in size or "width" not in size:
							raise ValueError(F'The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}'		)
						return center_crop(lowercase_   ,size=(size['''height'''], size['''width'''])   ,data_format=lowercase_   ,**lowercase_		)







					def        __lowerCAmelCase (       self			:				Dict   ,lowercase_			:				np.ndarray   ,lowercase_			:				float   ,lowercase_			:				Optional[Union[str, ChannelDimension]] = None   ,**lowercase_			:				List[str]		):
						return rescale(lowercase_   ,scale=lowercase_   ,data_format=lowercase_   ,**lowercase_		)







					def        __lowerCAmelCase (       self			:				List[Any]   ,lowercase_			:				np.ndarray   ,lowercase_			:				Union[float, List[float]]   ,lowercase_			:				Union[float, List[float]]   ,lowercase_			:				Optional[Union[str, ChannelDimension]] = None   ,**lowercase_			:				List[Any]   ,):
						return normalize(lowercase_   ,mean=lowercase_   ,std=lowercase_   ,data_format=lowercase_   ,**lowercase_		)







					def        __lowerCAmelCase (       self			:				Tuple   ,lowercase_			:				ImageInput   ,lowercase_			:				Optional[bool] = None   ,lowercase_			:				Dict[str, int] = None   ,lowercase_			:				PILImageResampling = None   ,lowercase_			:				bool = None   ,lowercase_			:				Dict[str, int] = None   ,lowercase_			:				Optional[bool] = None   ,lowercase_			:				Optional[float] = None   ,lowercase_			:				Optional[bool] = None   ,lowercase_			:				Optional[Union[float, List[float]]] = None   ,lowercase_			:				Optional[Union[float, List[float]]] = None   ,lowercase_			:				Optional[Union[str, TensorType]] = None   ,lowercase_			:				Union[str, ChannelDimension] = ChannelDimension.FIRST   ,**lowercase_			:				Optional[int]   ,):
						lowerCAmelCase__	:						int  				=	do_resize if do_resize is not None else self.do_resize
						lowerCAmelCase__	:						Optional[Any]  				=	size if size is not None else self.size
						lowerCAmelCase__	:						Optional[Any]  				=	get_size_dict(lowercase_   ,default_to_square=lowercase_		)
						lowerCAmelCase__	:						Union[str, Any]  				=	resample if resample is not None else self.resample
						lowerCAmelCase__	:						int  				=	do_center_crop if do_center_crop is not None else self.do_center_crop
						lowerCAmelCase__	:						str  				=	crop_size if crop_size is not None else self.crop_size
						lowerCAmelCase__	:						int  				=	get_size_dict(lowercase_   ,param_name='''crop_size'''		)
						lowerCAmelCase__	:						Tuple  				=	do_rescale if do_rescale is not None else self.do_rescale
						lowerCAmelCase__	:						Tuple  				=	rescale_factor if rescale_factor is not None else self.rescale_factor
						lowerCAmelCase__	:						str  				=	do_normalize if do_normalize is not None else self.do_normalize
						lowerCAmelCase__	:						List[str]  				=	image_mean if image_mean is not None else self.image_mean
						lowerCAmelCase__	:						Any  				=	image_std if image_std is not None else self.image_std

						lowerCAmelCase__	:						Union[str, Any]  				=	make_list_of_images(lowercase_		)

						if not valid_images(lowercase_		):
							raise ValueError(
							    '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
							    '''torch.Tensor, tf.Tensor or jax.ndarray.'''		)

						if do_resize and size is None:
							raise ValueError('''Size must be specified if do_resize is True.'''		)

						if do_center_crop and crop_size is None:
							raise ValueError('''Crop size must be specified if do_center_crop is True.'''		)

						if do_rescale and rescale_factor is None:
							raise ValueError('''Rescale factor must be specified if do_rescale is True.'''		)

						if do_normalize and (image_mean is None or image_std is None):
							raise ValueError('''Image mean and std must be specified if do_normalize is True.'''		)

						# All transformations expect numpy arrays.
						lowerCAmelCase__	:						Dict  				=	[to_numpy_array(lowercase_		) for image in images]

						if do_resize:
							lowerCAmelCase__	:						int  				=	[self.resize(image=lowercase_   ,size=lowercase_   ,resample=lowercase_		) for image in images]

						if do_center_crop:
							lowerCAmelCase__	:						Optional[int]  				=	[self.center_crop(image=lowercase_   ,size=lowercase_		) for image in images]

						if do_rescale:
							lowerCAmelCase__	:						str  				=	[self.rescale(image=lowercase_   ,scale=lowercase_		) for image in images]

						if do_normalize:
							lowerCAmelCase__	:						Union[str, Any]  				=	[self.normalize(image=lowercase_   ,mean=lowercase_   ,std=lowercase_		) for image in images]

						lowerCAmelCase__	:						int  				=	[to_channel_dimension_format(lowercase_   ,lowercase_		) for image in images]

						lowerCAmelCase__	:						Union[str, Any]  				=	{'''pixel_values''': images}
						return BatchFeature(data=lowercase_   ,tensor_type=lowercase_		)







					def        __lowerCAmelCase (       self			:				Optional[Any]   ,lowercase_			:				List[str]   ,lowercase_			:				List[Tuple] = None		):
						lowerCAmelCase__	:						Optional[Any]  				=	outputs.logits

						# Resize logits and compute semantic segmentation maps
						if target_sizes is not None:
							if len(lowercase_		) != len(lowercase_		):
								raise ValueError(
								    '''Make sure that you pass in as many target sizes as the batch dimension of the logits'''		)

							if is_torch_tensor(lowercase_		):
								lowerCAmelCase__	:						Optional[int]  				=	target_sizes.numpy()

							lowerCAmelCase__	:						Any  				=	[]

							for idx in range(len(lowercase_		)		):
								lowerCAmelCase__	:						Optional[int]  				=	torch.nn.functional.interpolate(
								    logits[idx].unsqueeze(dim=0		)   ,size=target_sizes[idx]   ,mode='''bilinear'''   ,align_corners=lowercase_		)
								lowerCAmelCase__	:						List[str]  				=	resized_logits[0].argmax(dim=0		)
								semantic_segmentation.append(lowercase_		)
						else:
							lowerCAmelCase__	:						Dict  				=	logits.argmax(dim=1		)
							lowerCAmelCase__	:						Dict  				=	[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]		)]

						return semantic_segmentation












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       ,    UpperCAmelCase       ,    UpperCAmelCase=3       ,    UpperCAmelCase=32       ,    UpperCAmelCase=3       ,    UpperCAmelCase=10       ,    UpperCAmelCase=[10, 20, 30, 40]       ,    UpperCAmelCase=[1, 1, 2, 1]       ,    UpperCAmelCase=True       ,    UpperCAmelCase=True       ,    UpperCAmelCase="relu"       ,    UpperCAmelCase=3       ,    UpperCAmelCase=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(UpperCAmelCase    )

	def        UpperCamelCase    (							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        UpperCamelCase    (							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        UpperCamelCase    (							self       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
							"""simple docstring"""







							_UpperCAmelCase									=			TFResNetModel(config=UpperCAmelCase    )
							_UpperCAmelCase									=			model(UpperCAmelCase    )
							# 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       ,    UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
							"""simple docstring"""







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

	def        UpperCamelCase    (							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 (      snake_case__     ,       snake_case__     ,       unittest.TestCase):





	"""simple docstring"""






	UpperCamelCase__								=      (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
	UpperCamelCase__								=      (
	    {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
	    if is_tf_available()
	    else {}
	)

	UpperCamelCase__								=      False
	UpperCamelCase__								=      False
	UpperCamelCase__								=      False
	UpperCamelCase__								=      False
	UpperCamelCase__								=      False

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			TFResNetModelTester(self    )
							_UpperCAmelCase									=			ConfigTester(self       ,    config_class=UpperCAmelCase       ,    has_text_modality=UpperCAmelCase    )

	def        UpperCamelCase    (							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        UpperCamelCase    (							self    ):
							"""simple docstring"""







							return

	@unittest.skip(reason='ResNet does not use inputs_embeds'    )
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							pass

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







							pass

	def        UpperCamelCase    (							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(UpperCAmelCase    )
													_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]       ,    UpperCAmelCase    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCAmelCase    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							def check_hidden_states_output(UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    ):
													_UpperCAmelCase									=			model_class(UpperCAmelCase    )
													_UpperCAmelCase									=			model(**self._prepare_for_class(UpperCAmelCase       ,    UpperCAmelCase    )    )

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

													_UpperCAmelCase									=			self.model_tester.num_stages
													self.assertEqual(len(UpperCAmelCase    )       ,    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(UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    )

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

																			check_hidden_states_output(UpperCAmelCase       ,    UpperCAmelCase       ,    UpperCAmelCase    )

	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







							_UpperCAmelCase									=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase    )

	@slow
	def        UpperCamelCase    (							self    ):
							"""simple docstring"""







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



def __A    (      )->  Optional[Any]:





						"""simple docstring"""



						_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        UpperCamelCase    (							self    ):
							"""simple docstring"""







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

	@slow
	def        UpperCamelCase    (							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=UpperCAmelCase       ,    return_tensors='tf'    )

							# forward pass
							_UpperCAmelCase									=			model(**UpperCAmelCase    )

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

							_UpperCAmelCase									=			tf.constant([-11.10_69, -9.78_77, -8.37_77]    )

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