

from __future__ import annotations

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import is_tf_available, is_vision_available

from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_tf_bert import TFBertModelTester
from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester
from ..deit.test_modeling_tf_deit import TFDeiTModelTester
from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester
from ..vit.test_modeling_tf_vit import TFViTModelTester


if is_tf_available():
	from transformers import (
	    TFBertModel,
	    TFCLIPVisionModel,
	    TFDeiTModel,
	    TFRobertaModel,
	    TFVisionTextDualEncoderModel,
	    TFViTModel,
	    VisionTextDualEncoderConfig,
	)

if is_vision_available():
	from PIL import Image

	from transformers import VisionTextDualEncoderProcessor

def 		UpperCamelCase      (lowercase_:				Any      )  ->   int:




	if isinstance(_lowerCAmelCase					,   collections.abc.Iterable      ):
		return x
	return (x, x)



@require_tf
class 					_a		:


					'''simple docstring'''






					def 						__A    (				self					, A__					, A__    ):
						pass






					def 						__A    (				self    ):
						pass






					def 						__A    (				self    ):
						pass






					def 						__A    (				self					, A__					, A__					, A__					, A__					, A__=None					, **A__    ):
						A__							:					Dict       =	VisionTextDualEncoderConfig.from_vision_text_configs(__A					, __A    )

						A__							:					Optional[int]       =	TFVisionTextDualEncoderModel(__A    )

						A__							:					Union[str, Any]       =	model(input_ids=__A					, pixel_values=__A					, attention_mask=__A    )

						self.assertEqual(output["""text_embeds"""].shape					, (input_ids.shape[0], config.projection_dim)    )
						self.assertEqual(output["""image_embeds"""].shape					, (pixel_values.shape[0], config.projection_dim)    )






					def 						__A    (				self					, A__					, A__					, A__					, A__					, A__=None					, **A__    ):
						A__							:					Optional[int]       =	self.get_vision_text_model(__A					, __A    )
						A__							:					Optional[int]       =	TFVisionTextDualEncoderModel(vision_model=__A					, text_model=__A    )

						A__							:					Any       =	model(input_ids=__A					, pixel_values=__A					, attention_mask=__A    )

						self.assertEqual(output["""text_embeds"""].shape					, (input_ids.shape[0], model.config.projection_dim)    )
						self.assertEqual(output["""image_embeds"""].shape					, (pixel_values.shape[0], model.config.projection_dim)    )






					def 						__A    (				self					, A__					, A__					, A__					, A__					, A__=None					, **A__    ):
						A__							:					Union[str, Any]       =	self.get_vision_text_model(__A					, __A    )
						A__							:					Dict       =	{"vision_model": vision_model, "text_model": text_model}
						A__							:					List[Any]       =	TFVisionTextDualEncoderModel.from_vision_text_pretrained(**__A    )

						A__							:					List[str]       =	model(input_ids=__A					, pixel_values=__A					, attention_mask=__A    )

						self.assertEqual(output["""text_embeds"""].shape					, (input_ids.shape[0], model.config.projection_dim)    )
						self.assertEqual(output["""image_embeds"""].shape					, (pixel_values.shape[0], model.config.projection_dim)    )






					def 						__A    (				self					, A__					, A__					, A__					, A__					, A__=None					, **A__    ):
						A__							:					List[str]       =	self.get_vision_text_model(__A					, __A    )
						A__							:					List[Any]       =	TFVisionTextDualEncoderModel(vision_model=__A					, text_model=__A    )

						A__							:					Optional[int]       =	model(input_ids=__A					, pixel_values=__A					, attention_mask=__A    )
						A__							:					List[str]       =	output[0].numpy()

						with tempfile.TemporaryDirectory() as tmpdirname:
							model.save_pretrained(__A    )
							A__							:					Union[str, Any]       =	TFVisionTextDualEncoderModel.from_pretrained(__A    )

							A__							:					Any       =	model(input_ids=__A					, pixel_values=__A					, attention_mask=__A    )
							A__							:					Optional[int]       =	after_output[0].numpy()
							A__							:					Optional[Any]       =	np.amax(np.abs(out_a - out_a    )    )
							self.assertLessEqual(__A					, 1e-5    )






					def 						__A    (				self					, A__					, A__					, A__					, A__					, A__=None					, **A__    ):
						A__							:					int       =	self.get_vision_text_model(__A					, __A    )
						A__							:					Any       =	TFVisionTextDualEncoderModel(vision_model=__A					, text_model=__A    )

						A__							:					str       =	model(
						    input_ids=__A					, pixel_values=__A					, attention_mask=__A					, output_attentions=__A    )

						A__							:					Any       =	output.vision_model_output.attentions
						self.assertEqual(len(__A    )					, vision_config.num_hidden_layers    )

						# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
						A__							:					Any       =	to_atuple(vision_model.config.image_size    )
						A__							:					Any       =	to_atuple(vision_model.config.patch_size    )
						A__							:					Optional[Any]       =	(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
						A__							:					Dict       =	num_patches + 1
						self.assertEqual(vision_attentions[0].shape[-3:]					, (vision_config.num_attention_heads, seq_len, seq_len)    )

						A__							:					List[Any]       =	output.text_model_output.attentions
						self.assertEqual(len(__A    )					, text_config.num_hidden_layers    )

						self.assertEqual(
						    text_attentions[0].shape[-3:]					, (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])					, )






					def 						__A    (				self					, A__					, A__					, A__    ):
						A__							:					List[Any]       =	np.abs((a - b)    ).max()
						self.assertLessEqual(__A					, __A					, F"""Difference between torch and flax is {diff} (>= {tol})."""    )






					def 						__A    (				self    ):
						A__							:					Any       =	self.prepare_config_and_inputs()
						self.check_vision_text_dual_encoder_model(**__A    )






					def 						__A    (				self    ):
						A__							:					str       =	self.prepare_config_and_inputs()
						self.check_model_from_pretrained_configs(**__A    )






					def 						__A    (				self    ):
						A__							:					Optional[int]       =	self.prepare_config_and_inputs()
						self.check_vision_text_dual_encoder_from_pretrained(**__A    )






					def 						__A    (				self    ):
						A__							:					Optional[Any]       =	self.prepare_config_and_inputs()
						self.check_save_load(**__A    )






					def 						__A    (				self    ):
						A__							:					Union[str, Any]       =	self.prepare_config_and_inputs()
						self.check_vision_text_output_attention(**__A    )






					@slow
					def 						__A    (				self    ):
						A__							:					Any       =	self.get_pretrained_model_and_inputs()

						A__							:					Tuple       =	model_a(**__A    )
						A__							:					int       =	outputs[0].numpy()

						with tempfile.TemporaryDirectory() as tmp_dirname:
							model_a.save_pretrained(__A    )
							A__							:					int       =	TFVisionTextDualEncoderModel.from_pretrained(__A    )

							A__							:					List[str]       =	model_a(**__A    )
							A__							:					Any       =	after_outputs[0].numpy()
							A__							:					str       =	np.amax(np.abs(out_a - out_a    )    )
							self.assertLessEqual(__A					, 1e-5    )



@require_tf
class 					_a		(__magic_name__	,     unittest.TestCase       ):


					'''simple docstring'''






					def 						__A    (				self    ):
						A__							:					Any       =	TFVisionTextDualEncoderModel.from_vision_text_pretrained(
						    """hf-internal-testing/tiny-random-vit"""					, """hf-internal-testing/tiny-random-bert"""    )
						A__							:					List[str]       =	13
						A__							:					List[str]       =	floats_tensor(
						    [
						        batch_size,
						        model.vision_model.config.num_channels,
						        model.vision_model.config.image_size,
						        model.vision_model.config.image_size,
						    ]    )
						A__							:					Optional[Any]       =	ids_tensor([batch_size, 4]					, model.text_model.config.vocab_size    )
						A__							:					Tuple       =	random_attention_mask([batch_size, 4]    )
						A__							:					Optional[Any]       =	{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

						return model, inputs






					def 						__A    (				self					, A__					, A__    ):
						A__							:					List[Any]       =	TFViTModel(__A					, name="""vision_model"""    )
						A__							:					str       =	TFBertModel(__A					, name="""text_model"""    )
						return vision_model, text_model






					def 						__A    (				self    ):
						A__							:					Dict       =	TFViTModelTester(self    )
						A__							:					int       =	TFBertModelTester(self    )
						A__							:					Tuple       =	vit_model_tester.prepare_config_and_inputs()
						A__							:					Optional[Any]       =	bert_model_tester.prepare_config_and_inputs()

						A__							:					str       =	vision_config_and_inputs

						(
						    A__		
						)							:					Optional[int]       =	text_config_and_inputs

						return {
						    "text_config": text_config,
						    "vision_config": vision_config,
						    "pixel_values": pixel_values,
						    "attention_mask": input_mask,
						    "input_ids": input_ids,
						    "text_token_type_ids": token_type_ids,
						    "text_sequence_labels": sequence_labels,
						    "text_token_labels": token_labels,
						    "text_choice_labels": choice_labels,
						}



@require_tf
class 					_a		(__magic_name__	,     unittest.TestCase       ):


					'''simple docstring'''






					def 						__A    (				self    ):
						# DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's
						# just reinitialize it.
						A__							:					List[str]       =	TFVisionTextDualEncoderModel.from_vision_text_pretrained(
						    """Rocketknight1/tiny-random-deit-tf"""					, """hf-internal-testing/tiny-random-roberta"""    )
						A__							:					int       =	13
						A__							:					Tuple       =	floats_tensor(
						    [
						        batch_size,
						        model.vision_model.config.num_channels,
						        model.vision_model.config.image_size,
						        model.vision_model.config.image_size,
						    ]    )
						A__							:					Optional[int]       =	ids_tensor([batch_size, 4]					, model.text_model.config.vocab_size    )
						A__							:					Optional[int]       =	random_attention_mask([batch_size, 4]    )
						A__							:					str       =	{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

						return model, inputs






					def 						__A    (				self					, A__					, A__					, A__					, A__					, A__=None					, **A__    ):
						A__							:					Dict       =	self.get_vision_text_model(__A					, __A    )
						A__							:					int       =	TFVisionTextDualEncoderModel(vision_model=__A					, text_model=__A    )

						A__							:					List[Any]       =	model(
						    input_ids=__A					, pixel_values=__A					, attention_mask=__A					, output_attentions=__A    )

						A__							:					int       =	output.vision_model_output.attentions
						self.assertEqual(len(__A    )					, vision_config.num_hidden_layers    )

						# in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
						A__							:					Union[str, Any]       =	to_atuple(vision_model.config.image_size    )
						A__							:					Tuple       =	to_atuple(vision_model.config.patch_size    )
						A__							:					Optional[Any]       =	(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
						A__							:					Dict       =	num_patches + 2
						self.assertEqual(vision_attentions[0].shape[-3:]					, (vision_config.num_attention_heads, seq_len, seq_len)    )

						A__							:					Any       =	output.text_model_output.attentions
						self.assertEqual(len(__A    )					, text_config.num_hidden_layers    )

						self.assertEqual(
						    text_attentions[0].shape[-3:]					, (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])					, )






					def 						__A    (				self					, A__					, A__    ):
						A__							:					Union[str, Any]       =	TFDeiTModel(__A					, name="""vision_model"""    )
						A__							:					str       =	TFRobertaModel(__A					, name="""text_model"""    )
						return vision_model, text_model






					def 						__A    (				self    ):
						A__							:					Tuple       =	TFDeiTModelTester(self    )
						A__							:					Union[str, Any]       =	TFRobertaModelTester(self    )
						A__							:					str       =	vit_model_tester.prepare_config_and_inputs()
						A__							:					Any       =	bert_model_tester.prepare_config_and_inputs()

						A__							:					List[Any]       =	vision_config_and_inputs

						(
						    A__		
						)							:					Dict       =	text_config_and_inputs

						return {
						    "text_config": text_config,
						    "vision_config": vision_config,
						    "pixel_values": pixel_values,
						    "attention_mask": input_mask,
						    "input_ids": input_ids,
						    "text_token_type_ids": token_type_ids,
						    "text_sequence_labels": sequence_labels,
						    "text_token_labels": token_labels,
						    "text_choice_labels": choice_labels,
						}



@require_tf
class 					_a		(__magic_name__	,     unittest.TestCase       ):


					'''simple docstring'''






					def 						__A    (				self    ):
						A__							:					Any       =	TFVisionTextDualEncoderModel.from_vision_text_pretrained(
						    """Rocketknight1/tiny-random-clip-tf"""					, """hf-internal-testing/tiny-random-bert"""    )
						A__							:					List[Any]       =	13
						A__							:					List[Any]       =	floats_tensor(
						    [
						        batch_size,
						        model.vision_model.config.num_channels,
						        model.vision_model.config.image_size,
						        model.vision_model.config.image_size,
						    ]    )
						A__							:					List[str]       =	ids_tensor([batch_size, 4]					, model.text_model.config.vocab_size    )
						A__							:					List[Any]       =	random_attention_mask([batch_size, 4]    )
						A__							:					str       =	{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

						return model, inputs






					def 						__A    (				self					, A__					, A__    ):
						A__							:					Tuple       =	TFCLIPVisionModel(__A					, name="""vision_model"""    )
						A__							:					int       =	TFBertModel(__A					, name="""text_model"""    )
						return vision_model, text_model






					def 						__A    (				self    ):
						A__							:					Union[str, Any]       =	TFCLIPVisionModelTester(self    )
						A__							:					Dict       =	TFBertModelTester(self    )
						A__							:					List[str]       =	clip_model_tester.prepare_config_and_inputs()
						A__							:					List[Any]       =	bert_model_tester.prepare_config_and_inputs()

						A__							:					Optional[Any]       =	vision_config_and_inputs

						(
						    A__		
						)							:					int       =	text_config_and_inputs

						return {
						    "text_config": text_config,
						    "vision_config": vision_config,
						    "pixel_values": pixel_values,
						    "attention_mask": input_mask,
						    "input_ids": input_ids,
						    "text_token_type_ids": token_type_ids,
						    "text_sequence_labels": sequence_labels,
						    "text_token_labels": token_labels,
						    "text_choice_labels": choice_labels,
						}



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


					'''simple docstring'''






					@slow
					def 						__A    (				self    ):
						A__							:					Dict       =	TFVisionTextDualEncoderModel.from_pretrained(
						    """clip-italian/clip-italian"""					, logit_scale_init_value=1.0					, from_pt=__A    )
						A__							:					List[Any]       =	VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian"""    )

						A__							:					Any       =	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
						A__							:					str       =	processor(
						    text=["""una foto di un gatto""", """una foto di un cane"""]					, images=__A					, padding=__A					, return_tensors="""np"""    )

						A__							:					int       =	model(**__A    )

						# verify the logits
						self.assertEqual(outputs.logits_per_image.shape					, (inputs.pixel_values.shape[0], inputs.input_ids.shape[0])    )
						self.assertEqual(
						    outputs.logits_per_text.shape					, (inputs.input_ids.shape[0], inputs.pixel_values.shape[0])					, )

						A__							:					Dict       =	np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]]    )

						self.assertTrue(np.allclose(outputs.logits_per_image.numpy()					, __A					, atol=1e-3    )    )


class 					_a		:


					'''simple docstring'''






					def __init__(				self    ):
						A__							:					str       =	""""""
						A__							:					Any       =	""""""
						A__							:					List[Any]       =	[]






					def 						__A    (				self					, A__					, A__    ):
						if m == -1:
							return n + 1
						elif n == -1:
							return m + 1
						elif self.dp[m][n] > -1:
							return self.dp[m][n]
						else:
							if self.worda[m] == self.worda[n]:
								A__							:					Optional[Any]       =	self.__min_dist_top_down_dp(m - 1					, n - 1    )
							else:
								A__							:					Union[str, Any]       =	self.__min_dist_top_down_dp(A__					, n - 1    )
								A__							:					Union[str, Any]       =	self.__min_dist_top_down_dp(m - 1					, A__    )
								A__							:					Union[str, Any]       =	self.__min_dist_top_down_dp(m - 1					, n - 1    )
								A__							:					List[Any]       =	1 + min(A__					, A__					, A__    )

							return self.dp[m][n]






					def 						__A    (				self					, A__					, A__    ):
						A__							:					Tuple       =	worda
						A__							:					Dict       =	worda
						A__							:					Optional[Any]       =	[[-1 for _ in range(len(A__    )    )] for _ in range(len(A__    )    )]

						return self.__min_dist_top_down_dp(len(A__    ) - 1					, len(A__    ) - 1    )






					def 						__A    (				self					, A__					, A__    ):
						A__							:					Optional[Any]       =	worda
						A__							:					Dict       =	worda
						A__							:					Union[str, Any]       =	len(A__    )
						A__							:					List[str]       =	len(A__    )
						A__							:					int       =	[[0 for _ in range(n + 1    )] for _ in range(m + 1    )]

						for i in range(m + 1    ):
							for j in range(n + 1    ):
								if i == 0:  # first string is empty
									A__							:					Tuple       =	j
								elif j == 0:  # second string is empty
									A__							:					Dict       =	i
								elif worda[i - 1] == worda[j - 1]:  # last characters are equal
									A__							:					str       =	self.dp[i - 1][j - 1]
								else:
									A__							:					Union[str, Any]       =	self.dp[i][j - 1]
									A__							:					str       =	self.dp[i - 1][j]
									A__							:					Union[str, Any]       =	self.dp[i - 1][j - 1]
									A__							:					Tuple       =	1 + min(A__					, A__					, A__    )
						return self.dp[m][n]


if __name__ == "__main__":
	A_ :				Union[str, Any]						 =    EditDistance()

	print('****************** Testing Edit Distance DP Algorithm ******************')
	print()

	A_ :				int						 =    input('Enter the first string: ').strip()
	A_ :				List[str]						 =    input('Enter the second string: ').strip()

	print()
	print(f'''The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}''')
	print(f'''The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}''')
	print()
	print('*************** End of Testing Edit Distance DP Algorithm ***************')



