"""simple docstring"""






import inspect
import unittest

from transformers import ConvNextConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
						from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor
class 				snake_case       :




					"""simple docstring"""

					def __init__(				self   :	List[Any]    ,lowerCamelCase__   :	Optional[int]    ,lowerCamelCase__   :	Union[str, Any]=13    ,lowerCamelCase__   :	Dict=32    ,lowerCamelCase__   :	str=3    ,lowerCamelCase__   :	Union[str, Any]=4    ,lowerCamelCase__   :	Optional[int]=[10, 20, 30, 40]    ,lowerCamelCase__   :	Dict=[2, 2, 3, 2]    ,lowerCamelCase__   :	List[str]=True    ,lowerCamelCase__   :	Any=True    ,lowerCamelCase__   :	List[Any]=37    ,lowerCamelCase__   :	Optional[Any]="gelu"    ,lowerCamelCase__   :	List[str]=10    ,lowerCamelCase__   :	Union[str, Any]=0.0_2    ,lowerCamelCase__   :	int=["stage2", "stage3", "stage4"]    ,lowerCamelCase__   :	Optional[int]=[2, 3, 4]    ,lowerCamelCase__   :	List[Any]=None    ,):
									UpperCAmelCase__             =							parent
									UpperCAmelCase__             =							batch_size
									UpperCAmelCase__             =							image_size
									UpperCAmelCase__             =							num_channels
									UpperCAmelCase__             =							num_stages
									UpperCAmelCase__             =							hidden_sizes
									UpperCAmelCase__             =							depths
									UpperCAmelCase__             =							is_training
									UpperCAmelCase__             =							use_labels
									UpperCAmelCase__             =							intermediate_size
									UpperCAmelCase__             =							hidden_act
									UpperCAmelCase__             =							num_labels
									UpperCAmelCase__             =							initializer_range
									UpperCAmelCase__             =							out_features
									UpperCAmelCase__             =							out_indices
									UpperCAmelCase__             =							scope







					def 		__lowerCAmelCase						(				self   :	Optional[int]			):
									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 		__lowerCAmelCase						(				self   :	str			):
									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=lowerCamelCase__    ,initializer_range=self.initializer_range    ,out_features=self.out_features    ,out_indices=self.out_indices    ,num_labels=self.num_labels    ,)







					def 		__lowerCAmelCase						(				self   :	Dict    ,lowerCamelCase__   :	List[Any]    ,lowerCamelCase__   :	List[str]    ,lowerCamelCase__   :	int			):
									UpperCAmelCase__             =							ConvNextModel(config=lowerCamelCase__			)
									model.to(lowerCamelCase__			)
									model.eval()
									UpperCAmelCase__             =							model(lowerCamelCase__			)
									# 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   :	Dict    ,lowerCamelCase__   :	List[str]    ,lowerCamelCase__   :	int    ,lowerCamelCase__   :	List[str]			):
									UpperCAmelCase__             =							ConvNextForImageClassification(lowerCamelCase__			)
									model.to(lowerCamelCase__			)
									model.eval()
									UpperCAmelCase__             =							model(lowerCamelCase__    ,labels=lowerCamelCase__			)
									self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.num_labels)			)







					def 		__lowerCAmelCase						(				self   :	List[str]    ,lowerCamelCase__   :	int    ,lowerCamelCase__   :	Union[str, Any]    ,lowerCamelCase__   :	int			):
									UpperCAmelCase__             =							ConvNextBackbone(config=lowerCamelCase__			)
									model.to(lowerCamelCase__			)
									model.eval()
									UpperCAmelCase__             =							model(lowerCamelCase__			)

									# verify hidden states
									self.parent.assertEqual(len(result.feature_maps			)    ,len(config.out_features			)			)
									self.parent.assertListEqual(list(result.feature_maps[0].shape			)    ,[self.batch_size, self.hidden_sizes[1], 4, 4]			)

									# verify channels
									self.parent.assertEqual(len(model.channels			)    ,len(config.out_features			)			)
									self.parent.assertListEqual(model.channels    ,config.hidden_sizes[1:]			)

									# verify backbone works with out_features=None
									UpperCAmelCase__             =							None
									UpperCAmelCase__             =							ConvNextBackbone(config=lowerCamelCase__			)
									model.to(lowerCamelCase__			)
									model.eval()
									UpperCAmelCase__             =							model(lowerCamelCase__			)

									# verify feature maps
									self.parent.assertEqual(len(result.feature_maps			)    ,1			)
									self.parent.assertListEqual(list(result.feature_maps[0].shape			)    ,[self.batch_size, self.hidden_sizes[-1], 1, 1]			)

									# verify channels
									self.parent.assertEqual(len(model.channels			)    ,1			)
									self.parent.assertListEqual(model.channels    ,[config.hidden_sizes[-1]]			)







					def 		__lowerCAmelCase						(				self   :	Optional[int]			):
									UpperCAmelCase__             =							self.prepare_config_and_inputs()
									UpperCAmelCase__      ,	UpperCAmelCase__      ,	UpperCAmelCase__             =							config_and_inputs
									UpperCAmelCase__             =							{'pixel_values': pixel_values}
									return config, inputs_dict






@require_torch
class 				snake_case       ( __UpperCAmelCase      ,    __UpperCAmelCase      ,    unittest.TestCase				):




					"""simple docstring"""

					snake_case__				    = (
					    (
					        ConvNextModel,
					        ConvNextForImageClassification,
					        ConvNextBackbone,
					    )
					    if is_torch_available()
					    else ()
					)
					snake_case__				    = (
					    {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
					    if is_torch_available()
					    else {}
					)

					snake_case__				    = True
					snake_case__				    = False
					snake_case__				    = False
					snake_case__				    = False
					snake_case__				    = False







					def 		__lowerCAmelCase						(				self   :	str			):
									UpperCAmelCase__             =							ConvNextModelTester(self			)
									UpperCAmelCase__             =							ConfigTester(self    ,config_class=lowerCamelCase__    ,has_text_modality=lowerCamelCase__    ,hidden_size=37			)







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







					@unittest.skip(reason='ConvNext does not use inputs_embeds'			)
					def 		__lowerCAmelCase						(				self   :	Optional[int]			):
									pass







					@unittest.skip(reason='ConvNext does not support input and output embeddings'			)
					def 		__lowerCAmelCase						(				self   :	List[str]			):
									pass







					@unittest.skip(reason='ConvNext does not use feedforward chunking'			)
					def 		__lowerCAmelCase						(				self   :	Optional[int]			):
									pass







					def 		__lowerCAmelCase						(				self   :	List[Any]			):
									UpperCAmelCase__      ,	UpperCAmelCase__             =							self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
													UpperCAmelCase__             =							model_class(lowerCamelCase__			)
													UpperCAmelCase__             =							inspect.signature(model.forward			)
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													UpperCAmelCase__             =							[*signature.parameters.keys()]

													UpperCAmelCase__             =							['pixel_values']
													self.assertListEqual(arg_names[:1]    ,lowerCamelCase__			)







					def 		__lowerCAmelCase						(				self   :	List[str]			):
									UpperCAmelCase__             =							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCamelCase__			)







					def 		__lowerCAmelCase						(				self   :	Dict			):
									UpperCAmelCase__             =							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_backbone(*lowerCamelCase__			)







					def 		__lowerCAmelCase						(				self   :	int			):
									def check_hidden_states_output(lowerCamelCase__   :	Tuple    ,lowerCamelCase__   :	Tuple    ,lowerCamelCase__   :	Any			):
													UpperCAmelCase__             =							model_class(lowerCamelCase__			)
													model.to(lowerCamelCase__			)
													model.eval()

													with torch.no_grad():
																	UpperCAmelCase__             =							model(**self._prepare_for_class(lowerCamelCase__    ,lowerCamelCase__			)			)

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

													UpperCAmelCase__             =							self.model_tester.num_stages
													self.assertEqual(len(lowerCamelCase__			)    ,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]    ,)

									UpperCAmelCase__      ,	UpperCAmelCase__             =							self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
													UpperCAmelCase__             =							True
													check_hidden_states_output(lowerCamelCase__    ,lowerCamelCase__    ,lowerCamelCase__			)

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

													check_hidden_states_output(lowerCamelCase__    ,lowerCamelCase__    ,lowerCamelCase__			)







					def 		__lowerCAmelCase						(				self   :	List[str]			):
									UpperCAmelCase__             =							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__			)







					@slow
					def 		__lowerCAmelCase						(				self   :	Optional[int]			):
									for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													UpperCAmelCase__             =							ConvNextModel.from_pretrained(lowerCamelCase__			)
													self.assertIsNotNone(lowerCamelCase__			)






def   a_						(					):
				UpperCAmelCase__             =							Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
				return image
@require_torch
@require_vision
class 				snake_case       ( unittest.TestCase				):




					"""simple docstring"""

					@cached_property
					def 		__lowerCAmelCase						(				self   :	Tuple			):
									return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224'			) if is_vision_available() else None







					@slow
					def 		__lowerCAmelCase						(				self   :	List[str]			):
									UpperCAmelCase__             =							ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'			).to(lowerCamelCase__			)

									UpperCAmelCase__             =							self.default_image_processor
									UpperCAmelCase__             =							prepare_img()
									UpperCAmelCase__             =							image_processor(images=lowerCamelCase__    ,return_tensors='pt'			).to(lowerCamelCase__			)

									# forward pass
									with torch.no_grad():
													UpperCAmelCase__             =							model(**lowerCamelCase__			)

									# verify the logits
									UpperCAmelCase__             =							torch.Size((1, 1_000)			)
									self.assertEqual(outputs.logits.shape    ,lowerCamelCase__			)

									UpperCAmelCase__             =							torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]			).to(lowerCamelCase__			)

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






@require_torch
class 				snake_case       ( unittest.TestCase      ,    __UpperCAmelCase				):




					"""simple docstring"""

					snake_case__				    = (ConvNextBackbone,) if is_torch_available() else ()
					snake_case__				    = ConvNextConfig

					snake_case__				    = False







					def 		__lowerCAmelCase						(				self   :	Any			):
									UpperCAmelCase__             =							ConvNextModelTester(self			)




"""simple docstring"""






import functools



def   a_						(					lowerCamelCase					,			lowerCamelCase       ):
				UpperCAmelCase__             =							len(lowerCamelCase       )
				UpperCAmelCase__             =							len(lowerCamelCase       )

				@functools.cache
				def min_distance(lowerCamelCase					,			lowerCamelCase       ) -> int:
								# if first word index is overflow - delete all from the second word
								if indexa >= len_worda:
												return len_worda - indexa
								# if second word index is overflow - delete all from the first word
								if indexa >= len_worda:
												return len_worda - indexa
								UpperCAmelCase__             =							int(worda[indexa] != worda[indexa]       )  # current letters not identical
								return min(
								    1 + min_distance(indexa + 1					,			lowerCamelCase       )					,			1 + min_distance(lowerCamelCase					,			indexa + 1       )					,			diff + min_distance(indexa + 1					,			indexa + 1       )					,			)

				return min_distance(0					,			0       )


if __name__ == "__main__":
						import doctest

						doctest.testmod()



