





from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
				from PIL import Image

				from transformers import ConvNextImageProcessor
class 							snake_case_		:







		def __init__(		self      ,  __lowercase      ,  __lowercase=1_3      ,  __lowercase=3_2      ,  __lowercase=3      ,  __lowercase=4      ,  __lowercase=[1_0, 2_0, 3_0, 4_0]      ,  __lowercase=[2, 2, 3, 2]      ,  __lowercase=True      ,  __lowercase=True      ,  __lowercase=3_7      ,  __lowercase="gelu"      ,  __lowercase=1_0      ,  __lowercase=0.0_2      ,  __lowercase=3      ,  __lowercase=None      ,  )					-> Optional[int]:
				lowerCamelCase :			Optional[Any]    		=parent
				lowerCamelCase :			str    		=batch_size
				lowerCamelCase :			str    		=image_size
				lowerCamelCase :			str    		=num_channels
				lowerCamelCase :			Union[str, Any]    		=num_stages
				lowerCamelCase :			str    		=hidden_sizes
				lowerCamelCase :			Optional[int]    		=depths
				lowerCamelCase :			Optional[int]    		=is_training
				lowerCamelCase :			Tuple    		=use_labels
				lowerCamelCase :			str    		=intermediate_size
				lowerCamelCase :			Any    		=hidden_act
				lowerCamelCase :			Tuple    		=type_sequence_label_size
				lowerCamelCase :			Optional[Any]    		=initializer_range
				lowerCamelCase :			Optional[Any]    		=scope







		def       __lowercase (		self )					-> Optional[Any]:
				lowerCamelCase :			Optional[Any]    		=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

				lowerCamelCase :			int    		=None
				if self.use_labels:
						lowerCamelCase :			List[Any]    		=ids_tensor([self.batch_size]      ,  self.type_sequence_label_size )

				lowerCamelCase :			int    		=self.get_config()

				return config, pixel_values, labels







		def       __lowercase (		self )					-> int:
				return ConvNextConfig(
				    num_channels=self.num_channels      ,  hidden_sizes=self.hidden_sizes      ,  depths=self.depths      ,  num_stages=self.num_stages      ,  hidden_act=self.hidden_act      ,  is_decoder=__lowercase      ,  initializer_range=self.initializer_range      ,  )







		def       __lowercase (		self      ,  __lowercase      ,  __lowercase      ,  __lowercase )					-> Dict:
				lowerCamelCase :			Optional[int]    		=TFConvNextModel(config=__lowercase )
				lowerCamelCase :			Union[str, Any]    		=model(__lowercase      ,  training=__lowercase )
				# 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 // 3_2, self.image_size // 3_2)      ,  )







		def       __lowercase (		self      ,  __lowercase      ,  __lowercase      ,  __lowercase )					-> Union[str, Any]:
				lowerCamelCase :			Union[str, Any]    		=self.type_sequence_label_size
				lowerCamelCase :			Tuple    		=TFConvNextForImageClassification(__lowercase )
				lowerCamelCase :			str    		=model(__lowercase      ,  labels=__lowercase      ,  training=__lowercase )
				self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, self.type_sequence_label_size) )







		def       __lowercase (		self )					-> List[Any]:
				lowerCamelCase :			List[Any]    		=self.prepare_config_and_inputs()
				lowerCamelCase		, lowerCamelCase		, lowerCamelCase :			Tuple    		=config_and_inputs
				lowerCamelCase :			Optional[Any]    		={'''pixel_values''': pixel_values}
				return config, inputs_dict

@require_tf
class 							snake_case_		(      _A    ,       _A    ,       unittest.TestCase):
		lowerCamelCase     :str							=  (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
		lowerCamelCase     :Tuple							=  (
		    {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
		    if is_tf_available()
		    else {}
		)

		lowerCamelCase     :Optional[int]							=  False
		lowerCamelCase     :Tuple							=  False
		lowerCamelCase     :str							=  False
		lowerCamelCase     :Tuple							=  False
		lowerCamelCase     :List[str]							=  False







		def       __lowercase (		self )					-> int:
				lowerCamelCase :			Union[str, Any]    		=TFConvNextModelTester(self )
				lowerCamelCase :			Optional[Any]    		=ConfigTester(
				    self      ,  config_class=__lowercase      ,  has_text_modality=__lowercase      ,  hidden_size=3_7      ,  )







		@unittest.skip(reason='''ConvNext does not use inputs_embeds''' )
		def       __lowercase (		self )					-> int:
				pass







		@unittest.skipIf(
		    not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0      ,  reason='''TF does not support backprop for grouped convolutions on CPU.'''      ,  )
		@slow
		def       __lowercase (		self )					-> Dict:
				super().test_keras_fit()







		@unittest.skip(reason='''ConvNext does not support input and output embeddings''' )
		def       __lowercase (		self )					-> Dict:
				pass







		def       __lowercase (		self )					-> str:
				lowerCamelCase		, lowerCamelCase :			Union[str, Any]    		=self.model_tester.prepare_config_and_inputs_for_common()

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

						lowerCamelCase :			Any    		=['''pixel_values''']
						self.assertListEqual(arg_names[:1]      ,  __lowercase )







		def       __lowercase (		self )					-> int:
				lowerCamelCase :			Tuple    		=self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*__lowercase )







		@unittest.skipIf(
		    not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0      ,  reason='''TF does not support backprop for grouped convolutions on CPU.'''      ,  )
		def       __lowercase (		self )					-> int:
				super().test_dataset_conversion()







		def       __lowercase (		self )					-> Optional[int]:
				def check_hidden_states_output(__lowercase      ,  __lowercase      ,  __lowercase ):
						lowerCamelCase :			Optional[int]    		=model_class(__lowercase )

						lowerCamelCase :			List[Any]    		=model(**self._prepare_for_class(__lowercase      ,  __lowercase ) )
						lowerCamelCase :			Dict    		=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

						lowerCamelCase :			str    		=self.model_tester.num_stages
						self.assertEqual(len(__lowercase )      ,  expected_num_stages + 1 )

						# ConvNext'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 :			int    		=self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						lowerCamelCase :			int    		=True
						check_hidden_states_output(__lowercase      ,  __lowercase      ,  __lowercase )

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

						check_hidden_states_output(__lowercase      ,  __lowercase      ,  __lowercase )







		def       __lowercase (		self )					-> List[Any]:
				lowerCamelCase		, lowerCamelCase :			List[str]    		=self.model_tester.prepare_config_and_inputs_for_common()

				def check_equivalence(__lowercase      ,  __lowercase      ,  __lowercase      ,  __lowercase={} ):
						lowerCamelCase :			Any    		=model(__lowercase      ,  return_dict=__lowercase      ,  **__lowercase )
						lowerCamelCase :			List[Any]    		=model(__lowercase      ,  return_dict=__lowercase      ,  **__lowercase ).to_tuple()

						def recursive_check(__lowercase      ,  __lowercase ):
								if isinstance(__lowercase      ,  (List, Tuple) ):
										for tuple_iterable_value, dict_iterable_value in zip(__lowercase      ,  __lowercase ):
												recursive_check(__lowercase      ,  __lowercase )
								elif tuple_object is None:
										return
								else:
										self.assertTrue(
										    all(tf.equal(__lowercase      ,  __lowercase ) )      ,  msg=(
										        '''Tuple and dict output are not equal. Difference:'''
										        F" {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}"
										    )      ,  )

								recursive_check(__lowercase      ,  __lowercase )

				for model_class in self.all_model_classes:
						lowerCamelCase :			List[str]    		=model_class(__lowercase )

						lowerCamelCase :			Optional[int]    		=self._prepare_for_class(__lowercase      ,  __lowercase )
						lowerCamelCase :			str    		=self._prepare_for_class(__lowercase      ,  __lowercase )
						check_equivalence(__lowercase      ,  __lowercase      ,  __lowercase )

						lowerCamelCase :			Dict    		=self._prepare_for_class(__lowercase      ,  __lowercase      ,  return_labels=__lowercase )
						lowerCamelCase :			List[str]    		=self._prepare_for_class(__lowercase      ,  __lowercase      ,  return_labels=__lowercase )
						check_equivalence(__lowercase      ,  __lowercase      ,  __lowercase )

						lowerCamelCase :			Union[str, Any]    		=self._prepare_for_class(__lowercase      ,  __lowercase )
						lowerCamelCase :			Union[str, Any]    		=self._prepare_for_class(__lowercase      ,  __lowercase )
						check_equivalence(__lowercase      ,  __lowercase      ,  __lowercase      ,  {'''output_hidden_states''': True} )

						lowerCamelCase :			Any    		=self._prepare_for_class(__lowercase      ,  __lowercase      ,  return_labels=__lowercase )
						lowerCamelCase :			Union[str, Any]    		=self._prepare_for_class(__lowercase      ,  __lowercase      ,  return_labels=__lowercase )
						check_equivalence(__lowercase      ,  __lowercase      ,  __lowercase      ,  {'''output_hidden_states''': True} )







		def       __lowercase (		self )					-> int:
				lowerCamelCase :			str    		=self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*__lowercase )







		@slow
		def       __lowercase (		self )					-> Any:
				lowerCamelCase :			Optional[Any]    		=TFConvNextModel.from_pretrained('''facebook/convnext-tiny-224''' )
				self.assertIsNotNone(__lowercase )


def        A__						(							) ->  Union[str, Any]:
		lowerCamelCase :			Optional[int]    		=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
		return image



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







		@cached_property
		def       __lowercase (		self )					-> Dict:
				return ConvNextImageProcessor.from_pretrained('''facebook/convnext-tiny-224''' ) if is_vision_available() else None







		@slow
		def       __lowercase (		self )					-> Optional[Any]:
				lowerCamelCase :			Dict    		=TFConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224''' )

				lowerCamelCase :			int    		=self.default_image_processor
				lowerCamelCase :			Dict    		=prepare_img()
				lowerCamelCase :			List[str]    		=image_processor(images=__lowercase      ,  return_tensors='''tf''' )

				# forward pass
				lowerCamelCase :			Any    		=model(**__lowercase )

				# verify the logits
				lowerCamelCase :			Optional[int]    		=tf.TensorShape((1, 1_0_0_0) )
				self.assertEqual(outputs.logits.shape      ,  __lowercase )

				lowerCamelCase :			Tuple    		=tf.constant([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1] )

				tf.debugging.assert_near(outputs.logits[0, :3]      ,  __lowercase      ,  atol=1e-4 )








import argparse
import collections
import importlib.util
import os
import re


# 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
snake_case_				=      '''src/diffusers'''
snake_case_				=      '''docs/source/en'''
snake_case_				=      '''.'''


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

		lowerCamelCase :			Dict    		=start_index
		while not lines[end_index].startswith(SCREAMING_SNAKE_CASE_		):
				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 |
snake_case_				=      '''Model|Encoder|Decoder|ForConditionalGeneration'''
# Regexes that match TF/Flax/PT model names.
snake_case_				=      re.compile(r'''TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''')
snake_case_				=      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.
snake_case_				=      re.compile(r'''(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''')


# This is to make sure the diffusers module imported is the one in the repo.
snake_case_				=      importlib.util.spec_from_file_location(
    '''diffusers''',
    os.path.join(TRANSFORMERS_PATH, '''__init__.py'''),
    submodule_search_locations=[TRANSFORMERS_PATH],
)
snake_case_				=      spec.loader.load_module()


def        A__						(							SCREAMING_SNAKE_CASE_		) ->  Tuple:
		lowerCamelCase :			Optional[Any]    		=re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)'''				,							SCREAMING_SNAKE_CASE_		)
		return [m.group(0		) for m in matches]


def        A__						(							SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_		) ->  Union[str, Any]:
		lowerCamelCase :			Dict    		=2 if text == '''✅''' or text == '''❌''' else len(SCREAMING_SNAKE_CASE_		)
		lowerCamelCase :			Union[str, Any]    		=(width - text_length) // 2
		lowerCamelCase :			List[str]    		=width - text_length - left_indent
		return " " * left_indent + text + " " * right_indent


def        A__						(							) ->  Union[str, Any]:
		lowerCamelCase :			List[str]    		=diffusers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
		lowerCamelCase :			List[Any]    		={
		    name: config_mapping_names[code]
		    for code, name in diffusers_module.MODEL_NAMES_MAPPING.items()
		    if code in config_mapping_names
		}
		lowerCamelCase :			Optional[int]    		={name: config.replace('''ConfigMixin'''				,							''''''		) 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 :			Optional[int]    		=collections.defaultdict(SCREAMING_SNAKE_CASE_		)
		lowerCamelCase :			Optional[int]    		=collections.defaultdict(SCREAMING_SNAKE_CASE_		)
		lowerCamelCase :			str    		=collections.defaultdict(SCREAMING_SNAKE_CASE_		)
		lowerCamelCase :			Any    		=collections.defaultdict(SCREAMING_SNAKE_CASE_		)
		lowerCamelCase :			Optional[int]    		=collections.defaultdict(SCREAMING_SNAKE_CASE_		)

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

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

    # Let's build that table!
		lowerCamelCase :			Optional[int]    		=list(model_name_to_config.keys()		)
		model_names.sort(key=str.lower		)
		lowerCamelCase :			Union[str, Any]    		=['''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 :			Tuple    		=[len(SCREAMING_SNAKE_CASE_		) + 2 for c in columns]
		lowerCamelCase :			Dict    		=max([len(SCREAMING_SNAKE_CASE_		) for name in model_names]		) + 2

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

		lowerCamelCase :			Optional[Any]    		={True: '''✅''', False: '''❌'''}
		for name in model_names:
				lowerCamelCase :			str    		=model_name_to_prefix[name]
				lowerCamelCase :			Dict    		=[
				    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(SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_		) for l, w in zip(SCREAMING_SNAKE_CASE_				,							SCREAMING_SNAKE_CASE_		)]		) + "|\n"
		return table


def        A__						(							SCREAMING_SNAKE_CASE_=False		) ->  int:
		lowerCamelCase		, lowerCamelCase		, lowerCamelCase		, lowerCamelCase :			Tuple    		=_find_text_in_file(
		    filename=os.path.join(SCREAMING_SNAKE_CASE_				,							'''index.mdx'''		)				,							start_prompt='''<!--This table is updated automatically from the auto modules'''				,							end_prompt='''<!-- End table-->'''				,							)
		lowerCamelCase :			List[Any]    		=get_model_table_from_auto_modules()

		if current_table != new_table:
				if overwrite:
						with open(os.path.join(SCREAMING_SNAKE_CASE_				,							'''index.mdx'''		)				,							'''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.mdx` has not been updated. Run `make fix-copies` to fix this.'''		)


if __name__ == "__main__":
				snake_case_				=      argparse.ArgumentParser()
				parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''')
				snake_case_				=      parser.parse_args()

				check_model_table(args.fix_and_overwrite)

