



"""simple docstring"""
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:							str						,     snake_case:							Dict						,     snake_case:							List[Any]=3						,     snake_case:							Any=32						,     snake_case:							Optional[int]=3						,     snake_case:							List[Any]=10						,     snake_case:							List[str]=[10, 20, 30, 40]						,     snake_case:							Dict=[1, 1, 2, 1]						,     snake_case:							Optional[int]=True						,     snake_case:							Dict=True						,     snake_case:							Union[str, Any]="relu"						,     snake_case:							List[Any]=3						,     snake_case:							Dict=None						,     )   ->	Dict:
											snake_case_ :str						=			parent
											snake_case_ :List[Any]						=			batch_size
											snake_case_ :int						=			image_size
											snake_case_ :Dict						=			num_channels
											snake_case_ :Any						=			embeddings_size
											snake_case_ :str						=			hidden_sizes
											snake_case_ :Tuple						=			depths
											snake_case_ :str						=			is_training
											snake_case_ :int						=			use_labels
											snake_case_ :Optional[int]						=			hidden_act
											snake_case_ :Dict						=			num_labels
											snake_case_ :Tuple						=			scope
											snake_case_ :List[Any]						=			len(snake_case						)






					def    lowerCAmelCase_				(       self:							Optional[Any]						)   ->	Optional[Any]:
											snake_case_ :Dict						=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

											snake_case_ :Union[str, Any]						=			self.get_config()

											return config, pixel_values, labels






					def    lowerCAmelCase_				(       self:							Optional[int]						)   ->	Union[str, Any]:
											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    lowerCAmelCase_				(       self:							int						,     snake_case:							List[str]						,     snake_case:							Any						,     snake_case:							Optional[int]						)   ->	Tuple:
											snake_case_ :Dict						=			TFResNetModel(config=snake_case						)
											snake_case_ :Dict						=			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    lowerCAmelCase_				(       self:							str						,     snake_case:							List[str]						,     snake_case:							Union[str, Any]						,     snake_case:							Any						)   ->	int:
											snake_case_ :Any						=			self.num_labels
											snake_case_ :Optional[int]						=			TFResNetForImageClassification(snake_case						)
											snake_case_ :List[Any]						=			model(snake_case						,     labels=snake_case						)
											self.parent.assertEqual(result.logits.shape						,     (self.batch_size, self.num_labels)						)






					def    lowerCAmelCase_				(       self:							Tuple						)   ->	Union[str, Any]:
											snake_case_ :Optional[int]						=			self.prepare_config_and_inputs()
											snake_case_,       snake_case_,       snake_case_ :Tuple						=			config_and_inputs
											snake_case_ :Tuple						=			{"""pixel_values""": pixel_values}
											return config, inputs_dict

@require_tf
class 				lowerCamelCase  (			_lowerCAmelCase    ,						_lowerCAmelCase    ,						unittest.TestCase				):






					'''simple docstring'''





					_A		:			Union[str, Any]						=     (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
					_A		:			List[str]						=     (
					    {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification}
					    if is_tf_available()
					    else {}
					)

					_A		:			List[str]						=     False
					_A		:			Any						=     False
					_A		:			int						=     False
					_A		:			List[Any]						=     False
					_A		:			Any						=     False






					def    lowerCAmelCase_				(       self:							str						)   ->	Optional[Any]:
											snake_case_ :List[str]						=			TFResNetModelTester(self						)
											snake_case_ :List[Any]						=			ConfigTester(self						,     config_class=snake_case						,     has_text_modality=snake_case						)






					def    lowerCAmelCase_				(       self:							int						)   ->	List[Any]:
											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    lowerCAmelCase_				(       self:							List[str]						)   ->	List[str]:
											return






					@unittest.skip(reason="""ResNet does not use inputs_embeds"""						)
					def    lowerCAmelCase_				(       self:							Dict						)   ->	Optional[Any]:
											pass






					@unittest.skip(reason="""ResNet does not support input and output embeddings"""						)
					def    lowerCAmelCase_				(       self:							Dict						)   ->	Optional[Any]:
											pass






					def    lowerCAmelCase_				(       self:							Dict						)   ->	Optional[int]:
											snake_case_,       snake_case_ :Tuple						=			self.model_tester.prepare_config_and_inputs_for_common()

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

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






					def    lowerCAmelCase_				(       self:							List[Any]						)   ->	List[str]:
											snake_case_ :Dict						=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*snake_case						)






					def    lowerCAmelCase_				(       self:							str						)   ->	List[Any]:
											def check_hidden_states_output(snake_case:							List[str]						,     snake_case:							List[str]						,     snake_case:							str						):
																	snake_case_ :Optional[Any]						=			model_class(snake_case						)
																	snake_case_ :Optional[int]						=			model(**self._prepare_for_class(snake_case						,     snake_case						)						)

																	snake_case_ :List[str]						=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																	snake_case_ :List[str]						=			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]						,     )

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

																							check_hidden_states_output(snake_case						,     snake_case						,     snake_case						)






					def    lowerCAmelCase_				(       self:							List[Any]						)   ->	Optional[Any]:
											snake_case_ :str						=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*snake_case						)






					@slow
					def    lowerCAmelCase_				(       self:							Dict						)   ->	Optional[int]:
											for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	snake_case_ :int						=			TFResNetModel.from_pretrained(snake_case						)
																	self.assertIsNotNone(snake_case						)

def    A_  (			):







						'''simple docstring'''


						snake_case_ :Dict						=			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
						return image

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






					'''simple docstring'''





					@cached_property
					def    lowerCAmelCase_				(       self:							Optional[Any]						)   ->	Any:
											return (
											    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
											    if is_vision_available()
											    else None
											)






					@slow
					def    lowerCAmelCase_				(       self:							Optional[Any]						)   ->	List[str]:
											snake_case_ :Any						=			TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)

											snake_case_ :int						=			self.default_image_processor
											snake_case_ :Union[str, Any]						=			prepare_img()
											snake_case_ :Optional[Any]						=			image_processor(images=snake_case						,     return_tensors="""tf"""						)

											# forward pass
											snake_case_ :List[str]						=			model(**snake_case						)

											# verify the logits
											snake_case_ :Optional[Any]						=			tf.TensorShape((1, 1_000)						)
											self.assertEqual(outputs.logits.shape						,     snake_case						)

											snake_case_ :Any						=			tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]						)

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


import unicodedata
from dataclasses import dataclass
from typing import Optional, Union

import numpy as np

from transformers.data.data_collator import DataCollatorMixin
from transformers.file_utils import PaddingStrategy
from transformers.tokenization_utils_base import PreTrainedTokenizerBase






def   lowerCAmelCase_						(					_snake_case      :  List[str]      ,   _snake_case      :  Tuple      ,   _snake_case      :  List[Any]      ,   _snake_case      :  Optional[Any]   )				->		Optional[Any]:







	'''simple docstring'''


	if isinstance(_snake_case      ,   _snake_case   ):
		__magic_name__		:		Union[str, Any]	   =     np.full((len(_snake_case   ), sequence_length, 2)      ,   _snake_case   )
	else:
		__magic_name__		:		List[Any]	   =     np.full((len(_snake_case   ), sequence_length)      ,   _snake_case   )

	for i, tensor in enumerate(_snake_case   ):
		if padding_side == "right":
			if isinstance(_snake_case      ,   _snake_case   ):
				__magic_name__		:		Optional[Any]	   =     tensor[:sequence_length]
			else:
				__magic_name__		:		Union[str, Any]	   =     tensor[:sequence_length]
		else:
			if isinstance(_snake_case      ,   _snake_case   ):
				__magic_name__		:		List[Any]	   =     tensor[:sequence_length]
			else:
				__magic_name__		:		Optional[Any]	   =     tensor[:sequence_length]

	return out_tensor.tolist()






def   lowerCAmelCase_						(					_snake_case      :  Optional[int]   )				->		Tuple:







	'''simple docstring'''


	__magic_name__		:		Union[str, Any]	   =     ord(_snake_case   )
	if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126):
		return True
	__magic_name__		:		Any	   =     unicodedata.category(_snake_case   )
	if cat.startswith("P"   ):
		return True
	return False





@dataclass
class       _snake_case					(     snake_case				):
			UpperCamelCase__          =    42
			UpperCamelCase__          =    True
			UpperCamelCase__          =    None
			UpperCamelCase__          =    None
			UpperCamelCase__          =    -100
			UpperCamelCase__          =    "pt"







			def 			SCREAMING_SNAKE_CASE    (				self						,   _a		):
				import torch

				__magic_name__		:		List[str]	   =     "label" if "label" in features[0].keys() else "labels"
				__magic_name__		:		Union[str, Any]	   =     [feature[label_name] for feature in features] if label_name in features[0].keys() else None
				__magic_name__		:		Optional[int]	   =     self.tokenizer.pad(
				    _a						,   padding=self.padding						,   max_length=self.max_length						,   pad_to_multiple_of=self.pad_to_multiple_of						,   return_tensors="pt" if labels is None else None						,   )

				if labels is None:
					return batch

				__magic_name__		:		Dict	   =     torch.tensor(batch["entity_ids"]		).shape[1]
				__magic_name__		:		List[Any]	   =     self.tokenizer.padding_side
				if padding_side == "right":
					__magic_name__		:		str	   =     [
					    list(_a		) + [self.label_pad_token_id] * (sequence_length - len(_a		)) for label in labels
					]
				else:
					__magic_name__		:		int	   =     [
					    [self.label_pad_token_id] * (sequence_length - len(_a		)) + list(_a		) for label in labels
					]

				__magic_name__		:		Dict	   =     [feature["ner_tags"] for feature in features]
				__magic_name__		:		List[Any]	   =     padding_tensor(_a						,   -1						,   _a						,   _a		)
				__magic_name__		:		Any	   =     [feature["original_entity_spans"] for feature in features]
				__magic_name__		:		Any	   =     padding_tensor(_a						,   (-1, -1)						,   _a						,   _a		)
				__magic_name__		:		List[Any]	   =     {k: torch.tensor(_a						,   dtype=torch.intaa		) for k, v in batch.items()}

				return batch
