






'''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 _lowercase	:




							def __init__(							self:				List[Any]			,							UpperCamelCase__:				Optional[Any]			,							UpperCamelCase__:				int=3			,							UpperCamelCase__:				Union[str, Any]=32			,							UpperCamelCase__:				Any=3			,							UpperCamelCase__:				Optional[int]=10			,							UpperCamelCase__:				List[str]=[10, 20, 30, 40]			,							UpperCamelCase__:				Tuple=[1, 1, 2, 1]			,							UpperCamelCase__:				Union[str, Any]=True			,							UpperCamelCase__:				List[str]=True			,							UpperCamelCase__:				str="relu"			,							UpperCamelCase__:				Any=3			,							UpperCamelCase__:				Optional[int]=None			,							):
														lowerCamelCase__					:	List[str]         =       parent
														lowerCamelCase__					:	str         =       batch_size
														lowerCamelCase__					:	str         =       image_size
														lowerCamelCase__					:	List[str]         =       num_channels
														lowerCamelCase__					:	List[str]         =       embeddings_size
														lowerCamelCase__					:	Dict         =       hidden_sizes
														lowerCamelCase__					:	Optional[Any]         =       depths
														lowerCamelCase__					:	Dict         =       is_training
														lowerCamelCase__					:	str         =       use_labels
														lowerCamelCase__					:	Any         =       hidden_act
														lowerCamelCase__					:	str         =       num_labels
														lowerCamelCase__					:	List[str]         =       scope
														lowerCamelCase__					:	Optional[int]         =       len(UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				str     ):
														lowerCamelCase__					:	Dict         =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

														lowerCamelCase__					:	str         =       self.get_config()

														return config, pixel_values, labels




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




							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														lowerCamelCase__					:	Union[str, Any]         =       self.prepare_config_and_inputs()
														lowerCamelCase__  ,		lowerCamelCase__  ,		lowerCamelCase__					:	Optional[int]         =       config_and_inputs
														lowerCamelCase__					:	Union[str, Any]         =       {"""pixel_values""": pixel_values}
														return config, inputs_dict



@require_tf
class _lowercase	(				_lowercase				,      _lowercase				,      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 		lowerCamelCase_				(							self:				Any     ):
														lowerCamelCase__					:	Union[str, Any]         =       TFResNetModelTester(self     )
														lowerCamelCase__					:	Any         =       ConfigTester(self			,							config_class=UpperCamelCase__			,							has_text_modality=UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				Optional[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 		lowerCamelCase_				(							self:				int     ):
														return




							@unittest.skip(reason="""ResNet does not use inputs_embeds"""     )
							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														pass




							@unittest.skip(reason="""ResNet does not support input and output embeddings"""     )
							def 		lowerCamelCase_				(							self:				Union[str, Any]     ):
														pass




							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														lowerCamelCase__  ,		lowerCamelCase__					:	List[str]         =       self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					lowerCamelCase__					:	Optional[Any]         =       model_class(UpperCamelCase__     )
																					lowerCamelCase__					:	List[str]         =       inspect.signature(model.call     )
																					# signature.parameters is an OrderedDict => so arg_names order is deterministic
																					lowerCamelCase__					:	Union[str, Any]         =       [*signature.parameters.keys()]

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




							def 		lowerCamelCase_				(							self:				int     ):
														lowerCamelCase__					:	Any         =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				Union[str, Any]     ):
														def check_hidden_states_output(UpperCamelCase__:				Optional[Any]			,							UpperCamelCase__:				Optional[int]			,							UpperCamelCase__:				int     ):
																					lowerCamelCase__					:	List[str]         =       model_class(UpperCamelCase__     )
																					lowerCamelCase__					:	Tuple         =       model(**self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__     )     )

																					lowerCamelCase__					:	Tuple         =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																					lowerCamelCase__					:	Optional[int]         =       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]			,							)

														lowerCamelCase__  ,		lowerCamelCase__					:	Optional[Any]         =       self.model_tester.prepare_config_and_inputs_for_common()
														lowerCamelCase__					:	Tuple         =       ["""basic""", """bottleneck"""]
														for model_class in self.all_model_classes:
																					for layer_type in layers_type:
																												lowerCamelCase__					:	Tuple         =       layer_type
																												lowerCamelCase__					:	Optional[Any]         =       True
																												check_hidden_states_output(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__     )

																												# check that output_hidden_states also work using config
																												del inputs_dict["output_hidden_states"]
																												lowerCamelCase__					:	Union[str, Any]         =       True

																												check_hidden_states_output(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				List[Any]     ):
														lowerCamelCase__					:	str         =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__     )




							@slow
							def 		lowerCamelCase_				(							self:				List[Any]     ):
														for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					lowerCamelCase__					:	List[str]         =       TFResNetModel.from_pretrained(UpperCamelCase__     )
																					self.assertIsNotNone(UpperCamelCase__     )





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



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




							@cached_property
							def 		lowerCamelCase_				(							self:				int     ):
														return (
														    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )
														    if is_vision_available()
														    else None
														)




							@slow
							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														lowerCamelCase__					:	List[str]         =       TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )

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

														# forward pass
														lowerCamelCase__					:	Optional[int]         =       model(**UpperCamelCase__     )

														# verify the logits
														lowerCamelCase__					:	List[Any]         =       tf.TensorShape((1, 1_000)     )
														self.assertEqual(outputs.logits.shape			,							UpperCamelCase__     )

														lowerCamelCase__					:	Tuple         =       tf.constant([-11.1_069, -9.7_877, -8.3_777]     )

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





import argparse
import collections
import os
import re

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_table.py
_UpperCAmelCase	:     Optional[int]   ="""src/transformers"""
_UpperCAmelCase	:     str   ="""docs/source/en"""
_UpperCAmelCase	:     Optional[int]   ="""."""



def 	lowerCAmelCase       (						lowerCAmelCase_       ,      lowerCAmelCase_       ,      lowerCAmelCase_       )->       List[str]:
				with open(lowerCAmelCase_       ,      '''r'''       ,      encoding='''utf-8'''       ,      newline='''\n'''       ) as f:
								lowerCAmelCase_       :					int			 = f.readlines()
				# Find the start prompt.
				lowerCAmelCase_       :					List[Any]			 = 0
				while not lines[start_index].startswith(lowerCAmelCase_       ):
								start_index += 1
				start_index += 1

				lowerCAmelCase_       :					List[str]			 = start_index
				while not lines[end_index].startswith(lowerCAmelCase_       ):
								end_index += 1
				end_index -= 1

				while len(lines[start_index]       ) <= 1:
								start_index += 1
				while len(lines[end_index]       ) <= 1:
								end_index -= 1
				end_index += 1
				return "".join(lines[start_index:end_index]       ), start_index, end_index, lines


# Add here suffixes that are used to identify models, separated by |
_UpperCAmelCase	:     Optional[Any]   ="""Model|Encoder|Decoder|ForConditionalGeneration"""
# Regexes that match TF/Flax/PT model names.
_UpperCAmelCase	:     Optional[int]   =re.compile(R"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")
_UpperCAmelCase	:     Dict   =re.compile(R"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
_UpperCAmelCase	:     Optional[Any]   =re.compile(R"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""")


# This is to make sure the transformers module imported is the one in the repo.
_UpperCAmelCase	:     Optional[int]   =direct_transformers_import(TRANSFORMERS_PATH)



def 	lowerCAmelCase       (						lowerCAmelCase_       )->       Optional[int]:
				lowerCAmelCase_       :					str			 = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)'''       ,      lowerCAmelCase_       )
				return [m.group(0       ) for m in matches]



def 	lowerCAmelCase       (						lowerCAmelCase_       ,      lowerCAmelCase_       )->       Optional[int]:
				lowerCAmelCase_       :					Tuple			 = 2 if text == '''✅''' or text == '''❌''' else len(lowerCAmelCase_       )
				lowerCAmelCase_       :					int			 = (width - text_length) // 2
				lowerCAmelCase_       :					Union[str, Any]			 = width - text_length - left_indent
				return " " * left_indent + text + " " * right_indent



def 	lowerCAmelCase       (						)->       str:
				lowerCAmelCase_       :					Any			 = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
				lowerCAmelCase_       :					Dict			 = {
				    name: config_maping_names[code]
				    for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
				    if code in config_maping_names
				}
				lowerCAmelCase_       :					List[Any]			 = {name: config.replace('''Config'''       ,      ''''''       ) for name, config in model_name_to_config.items()}

				# Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax.
				lowerCAmelCase_       :					Tuple			 = collections.defaultdict(lowerCAmelCase_       )
				lowerCAmelCase_       :					List[str]			 = collections.defaultdict(lowerCAmelCase_       )
				lowerCAmelCase_       :					Optional[Any]			 = collections.defaultdict(lowerCAmelCase_       )
				lowerCAmelCase_       :					Optional[int]			 = collections.defaultdict(lowerCAmelCase_       )
				lowerCAmelCase_       :					List[str]			 = collections.defaultdict(lowerCAmelCase_       )

				# Let's lookup through all transformers object (once).
				for attr_name in dir(lowerCAmelCase_       ):
								lowerCAmelCase_       :					Optional[int]			 = None
								if attr_name.endswith('''Tokenizer'''       ):
												lowerCAmelCase_       :					Union[str, Any]			 = slow_tokenizers
												lowerCAmelCase_       :					List[str]			 = attr_name[:-9]
								elif attr_name.endswith('''TokenizerFast'''       ):
												lowerCAmelCase_       :					int			 = fast_tokenizers
												lowerCAmelCase_       :					Union[str, Any]			 = attr_name[:-13]
								elif _re_tf_models.match(lowerCAmelCase_       ) is not None:
												lowerCAmelCase_       :					Tuple			 = tf_models
												lowerCAmelCase_       :					str			 = _re_tf_models.match(lowerCAmelCase_       ).groups()[0]
								elif _re_flax_models.match(lowerCAmelCase_       ) is not None:
												lowerCAmelCase_       :					Tuple			 = flax_models
												lowerCAmelCase_       :					Union[str, Any]			 = _re_flax_models.match(lowerCAmelCase_       ).groups()[0]
								elif _re_pt_models.match(lowerCAmelCase_       ) is not None:
												lowerCAmelCase_       :					Any			 = pt_models
												lowerCAmelCase_       :					List[Any]			 = _re_pt_models.match(lowerCAmelCase_       ).groups()[0]

								if lookup_dict is not None:
												while len(lowerCAmelCase_       ) > 0:
																if attr_name in model_name_to_prefix.values():
																				lowerCAmelCase_       :					Union[str, Any]			 = True
																				break
																# Try again after removing the last word in the name
																lowerCAmelCase_       :					Any			 = ''''''.join(camel_case_split(lowerCAmelCase_       )[:-1]       )

    # Let's build that table!
				lowerCAmelCase_       :					int			 = list(model_name_to_config.keys()       )
				model_names.sort(key=str.lower       )
				lowerCAmelCase_       :					Tuple			 = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support''']
				# We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side).
				lowerCAmelCase_       :					Union[str, Any]			 = [len(lowerCAmelCase_       ) + 2 for c in columns]
				lowerCAmelCase_       :					Optional[Any]			 = max([len(lowerCAmelCase_       ) for name in model_names]       ) + 2

				# Build the table per se
				lowerCAmelCase_       :					Dict			 = '''|''' + '''|'''.join([_center_text(lowerCAmelCase_       ,      lowerCAmelCase_       ) for c, w in zip(lowerCAmelCase_       ,      lowerCAmelCase_       )]       ) + '''|\n'''
				# Use ":-----:" format to center-aligned table cell texts
				table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths]       ) + "|\n"

				lowerCAmelCase_       :					List[str]			 = {True: '''✅''', False: '''❌'''}
				for name in model_names:
								lowerCAmelCase_       :					List[Any]			 = model_name_to_prefix[name]
								lowerCAmelCase_       :					Union[str, Any]			 = [
								    name,
								    check[slow_tokenizers[prefix]],
								    check[fast_tokenizers[prefix]],
								    check[pt_models[prefix]],
								    check[tf_models[prefix]],
								    check[flax_models[prefix]],
								]
								table += "|" + "|".join([_center_text(lowerCAmelCase_       ,      lowerCAmelCase_       ) for l, w in zip(lowerCAmelCase_       ,      lowerCAmelCase_       )]       ) + "|\n"
				return table



def 	lowerCAmelCase       (						lowerCAmelCase_=False       )->       Tuple:
				lowerCAmelCase_ ,     lowerCAmelCase_ ,     lowerCAmelCase_ ,     lowerCAmelCase_       :					str			 = _find_text_in_file(
				    filename=os.path.join(lowerCAmelCase_       ,      '''index.md'''       )       ,      start_prompt='''<!--This table is updated automatically from the auto modules'''       ,      end_prompt='''<!-- End table-->'''       ,      )
				lowerCAmelCase_       :					Tuple			 = get_model_table_from_auto_modules()

				if current_table != new_table:
								if overwrite:
												with open(os.path.join(lowerCAmelCase_       ,      '''index.md'''       )       ,      '''w'''       ,      encoding='''utf-8'''       ,      newline='''\n'''       ) as f:
																f.writelines(lines[:start_index] + [new_table] + lines[end_index:]       )
								else:
												raise ValueError(
												    '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.'''       )


if __name__ == "__main__":
						_UpperCAmelCase	:     List[Any]   =argparse.ArgumentParser()
						parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
						_UpperCAmelCase	:     Tuple   =parser.parse_args()

						check_model_table(args.fix_and_overwrite)