
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 	SCREAMING_SNAKE_CASE__    (      __lowerCAmelCase							):

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




@require_tf
class 					_SCREAMING_SNAKE_CASE  :
      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase ):
          pass
      def A_			(			self ):
          pass
      def A_			(			self ):
          pass
      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase=None		,	**lowerCamelCase ):
          snake_case__						=				VisionTextDualEncoderConfig.from_vision_text_configs(lowercase__		,	lowercase__ )

          snake_case__						=				TFVisionTextDualEncoderModel(lowercase__ )

          snake_case__						=				model(input_ids=lowercase__		,	pixel_values=lowercase__		,	attention_mask=lowercase__ )

          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		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase=None		,	**lowerCamelCase ):
          snake_case__						=				self.get_vision_text_model(lowercase__		,	lowercase__ )
          snake_case__						=				TFVisionTextDualEncoderModel(vision_model=lowercase__		,	text_model=lowercase__ )

          snake_case__						=				model(input_ids=lowercase__		,	pixel_values=lowercase__		,	attention_mask=lowercase__ )

          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		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase=None		,	**lowerCamelCase ):
          snake_case__						=				self.get_vision_text_model(lowercase__		,	lowercase__ )
          snake_case__						=				{"vision_model": vision_model, "text_model": text_model}
          snake_case__						=				TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase__ )

          snake_case__						=				model(input_ids=lowercase__		,	pixel_values=lowercase__		,	attention_mask=lowercase__ )

          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		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase=None		,	**lowerCamelCase ):
          snake_case__						=				self.get_vision_text_model(lowercase__		,	lowercase__ )
          snake_case__						=				TFVisionTextDualEncoderModel(vision_model=lowercase__		,	text_model=lowercase__ )

          snake_case__						=				model(input_ids=lowercase__		,	pixel_values=lowercase__		,	attention_mask=lowercase__ )
          snake_case__						=				output[0].numpy()

          with tempfile.TemporaryDirectory() as tmpdirname:
              model.save_pretrained(lowercase__ )
              snake_case__						=				TFVisionTextDualEncoderModel.from_pretrained(lowercase__ )

              snake_case__						=				model(input_ids=lowercase__		,	pixel_values=lowercase__		,	attention_mask=lowercase__ )
              snake_case__						=				after_output[0].numpy()
              snake_case__						=				np.amax(np.abs(out_a - out_a ) )
              self.assertLessEqual(lowercase__		,	1e-5 )
      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase=None		,	**lowerCamelCase ):
          snake_case__						=				self.get_vision_text_model(lowercase__		,	lowercase__ )
          snake_case__						=				TFVisionTextDualEncoderModel(vision_model=lowercase__		,	text_model=lowercase__ )

          snake_case__						=				model(
              input_ids=lowercase__		,	pixel_values=lowercase__		,	attention_mask=lowercase__		,	output_attentions=lowercase__ )

          snake_case__						=				output.vision_model_output.attentions
          self.assertEqual(len(lowercase__ )		,	vision_config.num_hidden_layers )

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

          snake_case__						=				output.text_model_output.attentions
          self.assertEqual(len(lowercase__ )		,	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		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase ):
          snake_case__						=				np.abs((a - b) ).max()
          self.assertLessEqual(lowercase__		,	lowercase__		,	F"""Difference between torch and flax is {diff} (>= {tol}).""" )
      def A_			(			self ):
          snake_case__						=				self.prepare_config_and_inputs()
          self.check_vision_text_dual_encoder_model(**lowercase__ )
      def A_			(			self ):
          snake_case__						=				self.prepare_config_and_inputs()
          self.check_model_from_pretrained_configs(**lowercase__ )
      def A_			(			self ):
          snake_case__						=				self.prepare_config_and_inputs()
          self.check_vision_text_dual_encoder_from_pretrained(**lowercase__ )
      def A_			(			self ):
          snake_case__						=				self.prepare_config_and_inputs()
          self.check_save_load(**lowercase__ )
      def A_			(			self ):
          snake_case__						=				self.prepare_config_and_inputs()
          self.check_vision_text_output_attention(**lowercase__ )



      @slow
      def A_			(			self ):
          snake_case__						=				self.get_pretrained_model_and_inputs()

          snake_case__						=				model_a(**lowercase__ )
          snake_case__						=				outputs[0].numpy()

          with tempfile.TemporaryDirectory() as tmp_dirname:
              model_a.save_pretrained(lowercase__ )
              snake_case__						=				TFVisionTextDualEncoderModel.from_pretrained(lowercase__ )

              snake_case__						=				model_a(**lowercase__ )
              snake_case__						=				after_outputs[0].numpy()
              snake_case__						=				np.amax(np.abs(out_a - out_a ) )
              self.assertLessEqual(lowercase__		,	1e-5 )





@require_tf
class 					_SCREAMING_SNAKE_CASE  (      _UpperCAmelCase       ,					unittest.TestCase ):
      def A_			(			self ):
          snake_case__						=				TFVisionTextDualEncoderModel.from_vision_text_pretrained(
              "hf-internal-testing/tiny-random-vit"		,	"hf-internal-testing/tiny-random-bert" )
          snake_case__						=				13
          snake_case__						=				floats_tensor(
              [
                  batch_size,
                  model.vision_model.config.num_channels,
                  model.vision_model.config.image_size,
                  model.vision_model.config.image_size,
              ] )
          snake_case__						=				ids_tensor([batch_size, 4]		,	model.text_model.config.vocab_size )
          snake_case__						=				random_attention_mask([batch_size, 4] )
          snake_case__						=				{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

          return model, inputs
      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase ):
          snake_case__						=				TFViTModel(lowercase__		,	name="vision_model" )
          snake_case__						=				TFBertModel(lowercase__		,	name="text_model" )
          return vision_model, text_model



      def A_			(			self ):
          snake_case__						=				TFViTModelTester(self )
          snake_case__						=				TFBertModelTester(self )
          snake_case__						=				vit_model_tester.prepare_config_and_inputs()
          snake_case__						=				bert_model_tester.prepare_config_and_inputs()

          snake_case__						=				vision_config_and_inputs

          (
              snake_case__		
          )						=				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 					_SCREAMING_SNAKE_CASE  (      _UpperCAmelCase       ,					unittest.TestCase ):
      def A_			(			self ):
          snake_case__						=				TFVisionTextDualEncoderModel.from_vision_text_pretrained(
              "Rocketknight1/tiny-random-deit-tf"		,	"hf-internal-testing/tiny-random-roberta" )
          snake_case__						=				13
          snake_case__						=				floats_tensor(
              [
                  batch_size,
                  model.vision_model.config.num_channels,
                  model.vision_model.config.image_size,
                  model.vision_model.config.image_size,
              ] )
          snake_case__						=				ids_tensor([batch_size, 4]		,	model.text_model.config.vocab_size )
          snake_case__						=				random_attention_mask([batch_size, 4] )
          snake_case__						=				{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

          return model, inputs
      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase=None		,	**lowerCamelCase ):
          snake_case__						=				self.get_vision_text_model(lowercase__		,	lowercase__ )
          snake_case__						=				TFVisionTextDualEncoderModel(vision_model=lowercase__		,	text_model=lowercase__ )

          snake_case__						=				model(
              input_ids=lowercase__		,	pixel_values=lowercase__		,	attention_mask=lowercase__		,	output_attentions=lowercase__ )

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

          snake_case__						=				output.text_model_output.attentions
          self.assertEqual(len(lowercase__ )		,	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		,	lowerCamelCase		,	lowerCamelCase ):
          snake_case__						=				TFDeiTModel(lowercase__		,	name="vision_model" )
          snake_case__						=				TFRobertaModel(lowercase__		,	name="text_model" )
          return vision_model, text_model



      def A_			(			self ):
          snake_case__						=				TFDeiTModelTester(self )
          snake_case__						=				TFRobertaModelTester(self )
          snake_case__						=				vit_model_tester.prepare_config_and_inputs()
          snake_case__						=				bert_model_tester.prepare_config_and_inputs()

          snake_case__						=				vision_config_and_inputs

          (
              snake_case__		
          )						=				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 					_SCREAMING_SNAKE_CASE  (      _UpperCAmelCase       ,					unittest.TestCase ):
      def A_			(			self ):
          snake_case__						=				TFVisionTextDualEncoderModel.from_vision_text_pretrained(
              "Rocketknight1/tiny-random-clip-tf"		,	"hf-internal-testing/tiny-random-bert" )
          snake_case__						=				13
          snake_case__						=				floats_tensor(
              [
                  batch_size,
                  model.vision_model.config.num_channels,
                  model.vision_model.config.image_size,
                  model.vision_model.config.image_size,
              ] )
          snake_case__						=				ids_tensor([batch_size, 4]		,	model.text_model.config.vocab_size )
          snake_case__						=				random_attention_mask([batch_size, 4] )
          snake_case__						=				{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

          return model, inputs
      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase ):
          snake_case__						=				TFCLIPVisionModel(lowercase__		,	name="vision_model" )
          snake_case__						=				TFBertModel(lowercase__		,	name="text_model" )
          return vision_model, text_model



      def A_			(			self ):
          snake_case__						=				TFCLIPVisionModelTester(self )
          snake_case__						=				TFBertModelTester(self )
          snake_case__						=				clip_model_tester.prepare_config_and_inputs()
          snake_case__						=				bert_model_tester.prepare_config_and_inputs()

          snake_case__						=				vision_config_and_inputs

          (
              snake_case__		
          )						=				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 					_SCREAMING_SNAKE_CASE  (      unittest.TestCase ):
      @slow
      def A_			(			self ):
          snake_case__						=				TFVisionTextDualEncoderModel.from_pretrained(
              "clip-italian/clip-italian"		,	logit_scale_init_value=1.0		,	from_pt=lowercase__ )
          snake_case__						=				VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian" )

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

          snake_case__						=				model(**lowercase__ )

          # 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])		,	)

          snake_case__						=				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()		,	lowercase__		,	atol=1e-3 ) )


from __future__ import annotations





def 	SCREAMING_SNAKE_CASE__    (      __lowerCAmelCase    ,		__lowerCAmelCase							):
    snake_case__						,					snake_case__						=				set(__lowerCAmelCase							), [start]

    while stack:
        snake_case__						=				stack.pop()
        explored.add(__lowerCAmelCase							)
        # Differences from BFS:
        # 1) pop last element instead of first one
        # 2) add adjacent elements to stack without exploring them
        for adj in reversed(graph[v]							):
            if adj not in explored:
                stack.append(__lowerCAmelCase							)
    return explored


__magic_name__            =  {
    '''A''': ['''B''', '''C''', '''D'''],
    '''B''': ['''A''', '''D''', '''E'''],
    '''C''': ['''A''', '''F'''],
    '''D''': ['''B''', '''D'''],
    '''E''': ['''B''', '''F'''],
    '''F''': ['''C''', '''E''', '''G'''],
    '''G''': ['''F'''],
}

if __name__ == "__main__":
     import doctest

     doctest.testmod()
     print(depth_first_search(G, '''A'''))



