



'''simple docstring'''

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 					__lowerCamelCase					(				lowerCAmelCase_  )      ->				Optional[int]:
		if isinstance(lowerCAmelCase_						,      collections.abc.Iterable  ):
				return x
		return (x, x)

@require_tf
class      __magic_name__						:







							def 							__lowercase      (							self :	Any     ,_UpperCAmelCase :	List[Any]     ,_UpperCAmelCase :	Optional[Any]		):
									pass







							def 							__lowercase      (							self :	Any		):
									pass







							def 							__lowercase      (							self :	int		):
									pass







							def 							__lowercase      (							self :	List[Any]     ,_UpperCAmelCase :	Optional[Any]     ,_UpperCAmelCase :	Union[str, Any]     ,_UpperCAmelCase :	Dict     ,_UpperCAmelCase :	List[Any]     ,_UpperCAmelCase :	List[Any]=None     ,**_UpperCAmelCase :	List[str]		):
									_a					:				Any				=							VisionTextDualEncoderConfig.from_vision_text_configs(_UpperCAmelCase     ,_UpperCAmelCase		)

									_a					:				Dict				=							TFVisionTextDualEncoderModel(_UpperCAmelCase		)

									_a					:				Union[str, Any]				=							model(input_ids=_UpperCAmelCase     ,pixel_values=_UpperCAmelCase     ,attention_mask=_UpperCAmelCase		)

									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 							__lowercase      (							self :	Tuple     ,_UpperCAmelCase :	Union[str, Any]     ,_UpperCAmelCase :	Any     ,_UpperCAmelCase :	Tuple     ,_UpperCAmelCase :	int     ,_UpperCAmelCase :	Any=None     ,**_UpperCAmelCase :	int		):
									_a	, _a					:				List[str]				=							self.get_vision_text_model(_UpperCAmelCase     ,_UpperCAmelCase		)
									_a					:				Any				=							TFVisionTextDualEncoderModel(vision_model=_UpperCAmelCase     ,text_model=_UpperCAmelCase		)

									_a					:				Dict				=							model(input_ids=_UpperCAmelCase     ,pixel_values=_UpperCAmelCase     ,attention_mask=_UpperCAmelCase		)

									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 							__lowercase      (							self :	Tuple     ,_UpperCAmelCase :	Union[str, Any]     ,_UpperCAmelCase :	Any     ,_UpperCAmelCase :	Any     ,_UpperCAmelCase :	Union[str, Any]     ,_UpperCAmelCase :	Tuple=None     ,**_UpperCAmelCase :	str		):
									_a	, _a					:				Any				=							self.get_vision_text_model(_UpperCAmelCase     ,_UpperCAmelCase		)
									_a					:				Optional[Any]				=							{'vision_model': vision_model, 'text_model': text_model}
									_a					:				Tuple				=							TFVisionTextDualEncoderModel.from_vision_text_pretrained(**_UpperCAmelCase		)

									_a					:				List[str]				=							model(input_ids=_UpperCAmelCase     ,pixel_values=_UpperCAmelCase     ,attention_mask=_UpperCAmelCase		)

									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 							__lowercase      (							self :	List[Any]     ,_UpperCAmelCase :	Optional[Any]     ,_UpperCAmelCase :	Optional[int]     ,_UpperCAmelCase :	Dict     ,_UpperCAmelCase :	Dict     ,_UpperCAmelCase :	Dict=None     ,**_UpperCAmelCase :	Union[str, Any]		):
									_a	, _a					:				List[Any]				=							self.get_vision_text_model(_UpperCAmelCase     ,_UpperCAmelCase		)
									_a					:				Tuple				=							TFVisionTextDualEncoderModel(vision_model=_UpperCAmelCase     ,text_model=_UpperCAmelCase		)

									_a					:				int				=							model(input_ids=_UpperCAmelCase     ,pixel_values=_UpperCAmelCase     ,attention_mask=_UpperCAmelCase		)
									_a					:				Tuple				=							output[0].numpy()

									with tempfile.TemporaryDirectory() as tmpdirname:
											model.save_pretrained(_UpperCAmelCase		)
											_a					:				Dict				=							TFVisionTextDualEncoderModel.from_pretrained(_UpperCAmelCase		)

											_a					:				str				=							model(input_ids=_UpperCAmelCase     ,pixel_values=_UpperCAmelCase     ,attention_mask=_UpperCAmelCase		)
											_a					:				Tuple				=							after_output[0].numpy()
											_a					:				Optional[int]				=							np.amax(np.abs(out_a - out_a		)		)
											self.assertLessEqual(_UpperCAmelCase     ,1E-5		)







							def 							__lowercase      (							self :	Union[str, Any]     ,_UpperCAmelCase :	Optional[int]     ,_UpperCAmelCase :	Union[str, Any]     ,_UpperCAmelCase :	Union[str, Any]     ,_UpperCAmelCase :	str     ,_UpperCAmelCase :	List[str]=None     ,**_UpperCAmelCase :	List[str]		):
									_a	, _a					:				Any				=							self.get_vision_text_model(_UpperCAmelCase     ,_UpperCAmelCase		)
									_a					:				Dict				=							TFVisionTextDualEncoderModel(vision_model=_UpperCAmelCase     ,text_model=_UpperCAmelCase		)

									_a					:				Tuple				=							model(
									    input_ids=_UpperCAmelCase     ,pixel_values=_UpperCAmelCase     ,attention_mask=_UpperCAmelCase     ,output_attentions=_UpperCAmelCase		)

									_a					:				Any				=							output.vision_model_output.attentions
									self.assertEqual(len(_UpperCAmelCase		)     ,vision_config.num_hidden_layers		)

									# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
									_a					:				Optional[Any]				=							to_atuple(vision_model.config.image_size		)
									_a					:				str				=							to_atuple(vision_model.config.patch_size		)
									_a					:				Union[str, Any]				=							(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
									_a					:				List[str]				=							num_patches + 1
									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(_UpperCAmelCase		)     ,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 							__lowercase      (							self :	str     ,_UpperCAmelCase :	np.ndarray     ,_UpperCAmelCase :	np.ndarray     ,_UpperCAmelCase :	float		):
									_a					:				Any				=							np.abs((a - b)		).max()
									self.assertLessEqual(_UpperCAmelCase     ,_UpperCAmelCase     ,F"""Difference between torch and flax is {diff} (>= {tol})."""		)







							def 							__lowercase      (							self :	List[Any]		):
									_a					:				int				=							self.prepare_config_and_inputs()
									self.check_vision_text_dual_encoder_model(**_UpperCAmelCase		)







							def 							__lowercase      (							self :	Any		):
									_a					:				Union[str, Any]				=							self.prepare_config_and_inputs()
									self.check_model_from_pretrained_configs(**_UpperCAmelCase		)







							def 							__lowercase      (							self :	Any		):
									_a					:				Dict				=							self.prepare_config_and_inputs()
									self.check_vision_text_dual_encoder_from_pretrained(**_UpperCAmelCase		)







							def 							__lowercase      (							self :	Union[str, Any]		):
									_a					:				Optional[int]				=							self.prepare_config_and_inputs()
									self.check_save_load(**_UpperCAmelCase		)







							def 							__lowercase      (							self :	str		):
									_a					:				int				=							self.prepare_config_and_inputs()
									self.check_vision_text_output_attention(**_UpperCAmelCase		)







							@slow
							def 							__lowercase      (							self :	int		):
									_a	, _a					:				Dict				=							self.get_pretrained_model_and_inputs()

									_a					:				Tuple				=							model_a(**_UpperCAmelCase		)
									_a					:				Optional[int]				=							outputs[0].numpy()

									with tempfile.TemporaryDirectory() as tmp_dirname:
											model_a.save_pretrained(_UpperCAmelCase		)
											_a					:				Tuple				=							TFVisionTextDualEncoderModel.from_pretrained(_UpperCAmelCase		)

											_a					:				str				=							model_a(**_UpperCAmelCase		)
											_a					:				Tuple				=							after_outputs[0].numpy()
											_a					:				Optional[Any]				=							np.amax(np.abs(out_a - out_a		)		)
											self.assertLessEqual(_UpperCAmelCase     ,1E-5		)

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







							def 							__lowercase      (							self :	str		):
									_a					:				Optional[Any]				=							TFVisionTextDualEncoderModel.from_vision_text_pretrained(
									    'hf-internal-testing/tiny-random-vit'     ,'hf-internal-testing/tiny-random-bert'		)
									_a					:				List[str]				=							13
									_a					:				int				=							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					:				List[str]				=							random_attention_mask([batch_size, 4]		)
									_a					:				List[Any]				=							{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

									return model, inputs







							def 							__lowercase      (							self :	List[Any]     ,_UpperCAmelCase :	List[str]     ,_UpperCAmelCase :	Optional[int]		):
									_a					:				List[Any]				=							TFViTModel(_UpperCAmelCase     ,name='vision_model'		)
									_a					:				List[str]				=							TFBertModel(_UpperCAmelCase     ,name='text_model'		)
									return vision_model, text_model







							def 							__lowercase      (							self :	Optional[Any]		):
									_a					:				Optional[int]				=							TFViTModelTester(self		)
									_a					:				List[str]				=							TFBertModelTester(self		)
									_a					:				Any				=							vit_model_tester.prepare_config_and_inputs()
									_a					:				Union[str, Any]				=							bert_model_tester.prepare_config_and_inputs()

									_a	, _a	, _a					:				Dict				=							vision_config_and_inputs

									(
									    (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, 
									)					:				Union[str, Any]				=							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      __magic_name__						(   _UpperCamelCase      ,						unittest.TestCase       ):







							def 							__lowercase      (							self :	str		):
									# 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[Any]				=							TFVisionTextDualEncoderModel.from_vision_text_pretrained(
									    'Rocketknight1/tiny-random-deit-tf'     ,'hf-internal-testing/tiny-random-roberta'		)
									_a					:				Union[str, Any]				=							13
									_a					:				Optional[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					:				Tuple				=							{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

									return model, inputs







							def 							__lowercase      (							self :	List[Any]     ,_UpperCAmelCase :	List[Any]     ,_UpperCAmelCase :	Dict     ,_UpperCAmelCase :	str     ,_UpperCAmelCase :	Any     ,_UpperCAmelCase :	str=None     ,**_UpperCAmelCase :	List[str]		):
									_a	, _a					:				Tuple				=							self.get_vision_text_model(_UpperCAmelCase     ,_UpperCAmelCase		)
									_a					:				Any				=							TFVisionTextDualEncoderModel(vision_model=_UpperCAmelCase     ,text_model=_UpperCAmelCase		)

									_a					:				int				=							model(
									    input_ids=_UpperCAmelCase     ,pixel_values=_UpperCAmelCase     ,attention_mask=_UpperCAmelCase     ,output_attentions=_UpperCAmelCase		)

									_a					:				Any				=							output.vision_model_output.attentions
									self.assertEqual(len(_UpperCAmelCase		)     ,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					:				Tuple				=							to_atuple(vision_model.config.image_size		)
									_a					:				Dict				=							to_atuple(vision_model.config.patch_size		)
									_a					:				List[str]				=							(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
									_a					:				int				=							num_patches + 2
									self.assertEqual(vision_attentions[0].shape[-3:]     ,(vision_config.num_attention_heads, seq_len, seq_len)		)

									_a					:				Union[str, Any]				=							output.text_model_output.attentions
									self.assertEqual(len(_UpperCAmelCase		)     ,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 							__lowercase      (							self :	List[str]     ,_UpperCAmelCase :	Optional[Any]     ,_UpperCAmelCase :	Union[str, Any]		):
									_a					:				Union[str, Any]				=							TFDeiTModel(_UpperCAmelCase     ,name='vision_model'		)
									_a					:				Dict				=							TFRobertaModel(_UpperCAmelCase     ,name='text_model'		)
									return vision_model, text_model







							def 							__lowercase      (							self :	int		):
									_a					:				int				=							TFDeiTModelTester(self		)
									_a					:				List[str]				=							TFRobertaModelTester(self		)
									_a					:				List[Any]				=							vit_model_tester.prepare_config_and_inputs()
									_a					:				Optional[int]				=							bert_model_tester.prepare_config_and_inputs()

									_a	, _a	, _a					:				Dict				=							vision_config_and_inputs

									(
									    (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, 
									)					:				Union[str, Any]				=							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      __magic_name__						(   _UpperCamelCase      ,						unittest.TestCase       ):







							def 							__lowercase      (							self :	int		):
									_a					:				Any				=							TFVisionTextDualEncoderModel.from_vision_text_pretrained(
									    'Rocketknight1/tiny-random-clip-tf'     ,'hf-internal-testing/tiny-random-bert'		)
									_a					:				Dict				=							13
									_a					:				Any				=							floats_tensor(
									    [
									        batch_size,
									        model.vision_model.config.num_channels,
									        model.vision_model.config.image_size,
									        model.vision_model.config.image_size,
									    ]		)
									_a					:				str				=							ids_tensor([batch_size, 4]     ,model.text_model.config.vocab_size		)
									_a					:				Optional[int]				=							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 							__lowercase      (							self :	str     ,_UpperCAmelCase :	Optional[Any]     ,_UpperCAmelCase :	Tuple		):
									_a					:				Optional[int]				=							TFCLIPVisionModel(_UpperCAmelCase     ,name='vision_model'		)
									_a					:				int				=							TFBertModel(_UpperCAmelCase     ,name='text_model'		)
									return vision_model, text_model







							def 							__lowercase      (							self :	List[str]		):
									_a					:				Optional[int]				=							TFCLIPVisionModelTester(self		)
									_a					:				List[Any]				=							TFBertModelTester(self		)
									_a					:				int				=							clip_model_tester.prepare_config_and_inputs()
									_a					:				Dict				=							bert_model_tester.prepare_config_and_inputs()

									_a	, _a					:				Optional[Any]				=							vision_config_and_inputs

									(
									    (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, (
									    _a
									)	, (
									    _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_vision
@require_tf
class      __magic_name__						(   unittest.TestCase       ):







							@slow
							def 							__lowercase      (							self :	List[str]		):
									_a					:				Optional[int]				=							TFVisionTextDualEncoderModel.from_pretrained(
									    'clip-italian/clip-italian'     ,logit_scale_init_value=1.0     ,from_pt=_UpperCAmelCase		)
									_a					:				Optional[Any]				=							VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'		)

									_a					:				int				=							Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
									_a					:				Dict				=							processor(
									    text=['una foto di un gatto', 'una foto di un cane']     ,images=_UpperCAmelCase     ,padding=_UpperCAmelCase     ,return_tensors='np'		)

									_a					:				List[Any]				=							model(**_UpperCAmelCase		)

									# 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					:				List[str]				=							np.array([[1.2_28_47_27, 0.3_10_41_22]]		)

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









'''simple docstring'''

from __future__ import annotations

import collections
import pprint
from pathlib import Path



def 					__lowerCamelCase					(				lowerCAmelCase_  )      ->				str:
		return "".join(sorted(lowerCAmelCase_  )  )



def 					__lowerCamelCase					(				lowerCAmelCase_  )      ->				list[str]:
		return word_by_signature[signature(lowerCAmelCase_  )]


__lowerCAmelCase						      =       Path(__file__).parent.joinpath('''words.txt''').read_text(encoding='''utf-8''')
__lowerCAmelCase						      =       sorted({word.strip().lower() for word in data.splitlines()})

__lowerCAmelCase						      =       collections.defaultdict(list)
for word in word_list:
							word_by_signature[signature(word)].append(word)

if __name__ == "__main__":
							__lowerCAmelCase						      =       {word: anagram(word) for word in word_list if len(anagram(word)) > 1}

							with open('''anagrams.txt''', '''w''') as file:
														file.write('''all_anagrams = \n ''')
														file.write(pprint.pformat(all_anagrams))




