
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(__lowerCAmelCase    ,		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(lowerCamelCase		,	lowerCamelCase )

          snake_case__						=				TFVisionTextDualEncoderModel(lowerCamelCase )

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

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

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

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

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

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

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

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

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

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

          snake_case__						=				output.vision_model_output.attentions
          self.assertEqual(len(lowerCamelCase )		,	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(lowerCamelCase )		,	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(lowerCamelCase		,	lowerCamelCase		,	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(**lowerCamelCase )
      def A_			(			self ):
          snake_case__						=				self.prepare_config_and_inputs()
          self.check_model_from_pretrained_configs(**lowerCamelCase )
      def A_			(			self ):
          snake_case__						=				self.prepare_config_and_inputs()
          self.check_vision_text_dual_encoder_from_pretrained(**lowerCamelCase )
      def A_			(			self ):
          snake_case__						=				self.prepare_config_and_inputs()
          self.check_save_load(**lowerCamelCase )
      def A_			(			self ):
          snake_case__						=				self.prepare_config_and_inputs()
          self.check_vision_text_output_attention(**lowerCamelCase )



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

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

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

              snake_case__						=				model_a(**lowerCamelCase )
              snake_case__						=				after_outputs[0].numpy()
              snake_case__						=				np.amax(np.abs(out_a - out_a ) )
              self.assertLessEqual(lowerCamelCase		,	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(lowerCamelCase		,	name="vision_model" )
          snake_case__						=				TFBertModel(lowerCamelCase		,	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__						,					snake_case__						,					snake_case__						=				vision_config_and_inputs

          (
              (
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              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 ):
          # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's
          # just reinitialize it.
          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__						,					snake_case__						=				self.get_vision_text_model(lowerCamelCase		,	lowerCamelCase )
          snake_case__						=				TFVisionTextDualEncoderModel(vision_model=lowerCamelCase		,	text_model=lowerCamelCase )

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

          snake_case__						=				output.vision_model_output.attentions
          self.assertEqual(len(lowerCamelCase )		,	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(lowerCamelCase )		,	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(lowerCamelCase		,	name="vision_model" )
          snake_case__						=				TFRobertaModel(lowerCamelCase		,	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__						,					snake_case__						,					snake_case__						=				vision_config_and_inputs

          (
              (
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              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(lowerCamelCase		,	name="vision_model" )
          snake_case__						=				TFBertModel(lowerCamelCase		,	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__						,					snake_case__						=				vision_config_and_inputs

          (
              (
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              snake_case__
          )						,					(
              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=lowerCamelCase )
          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=lowerCamelCase		,	padding=lowerCamelCase		,	return_tensors="np" )

          snake_case__						=				model(**lowerCamelCase )

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





import importlib.util
import os
import platform
from argparse import ArgumentParser

import huggingface_hub

from .. import __version__ as version
from ..utils import (
    is_accelerate_available,
    is_flax_available,
    is_safetensors_available,
    is_tf_available,
    is_torch_available,
)
from . import BaseTransformersCLICommand





def 	SCREAMING_SNAKE_CASE__    (      __lowerCAmelCase							):
    return EnvironmentCommand()





def 	SCREAMING_SNAKE_CASE__    (      __lowerCAmelCase							):
    return EnvironmentCommand(args.accelerate_config_file							)





class 					_SCREAMING_SNAKE_CASE  (      __UpperCamelCase ):
      @staticmethod
      def A_			(			lowerCamelCase ):
          snake_case__						=				parser.add_parser("env" )
          download_parser.set_defaults(func=lowerCamelCase )
          download_parser.add_argument(
              "--accelerate-config_file"		,	default=lowerCamelCase		,	help="The accelerate config file to use for the default values in the launching script."		,	)
          download_parser.set_defaults(func=lowerCamelCase )
      def __init__(			self		,	lowerCamelCase		,	*lowerCamelCase ):
          snake_case__						=				accelerate_config_file
      def A_			(			self ):
          snake_case__						=				"not installed"
          if is_safetensors_available():
              import safetensors

              snake_case__						=				safetensors.__version__
          elif importlib.util.find_spec("safetensors" ) is not None:
              import safetensors

              snake_case__						=				F"""{safetensors.__version__} but is ignored because of PyTorch version too old."""

          snake_case__						=				"not installed"
          snake_case__						=				snake_case__						=				"not found"
          if is_accelerate_available():
              import accelerate
              from accelerate.commands.config import default_config_file, load_config_from_file

              snake_case__						=				accelerate.__version__
              # Get the default from the config file.
              if self._accelerate_config_file is not None or os.path.isfile(lowerCamelCase ):
                  snake_case__						=				load_config_from_file(self._accelerate_config_file ).to_dict()

              snake_case__						=				(
                  "\n".join([F"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] )
                  if isinstance(lowerCamelCase		,	lowerCamelCase )
                  else F"""\t{accelerate_config}"""
              )

          snake_case__						=				"not installed"
          snake_case__						=				"NA"
          if is_torch_available():
              import torch

              snake_case__						=				torch.__version__
              snake_case__						=				torch.cuda.is_available()

          snake_case__						=				"not installed"
          snake_case__						=				"NA"
          if is_tf_available():
              import tensorflow as tf

              snake_case__						=				tf.__version__
              try:
                  # deprecated in v2.1
                  snake_case__						=				tf.test.is_gpu_available()
              except AttributeError:
                  # returns list of devices, convert to bool
                  snake_case__						=				bool(tf.config.list_physical_devices("GPU" ) )

          snake_case__						=				"not installed"
          snake_case__						=				"not installed"
          snake_case__						=				"not installed"
          snake_case__						=				"NA"
          if is_flax_available():
              import flax
              import jax
              import jaxlib

              snake_case__						=				flax.__version__
              snake_case__						=				jax.__version__
              snake_case__						=				jaxlib.__version__
              snake_case__						=				jax.lib.xla_bridge.get_backend().platform

          snake_case__						=				{
              "`transformers` version": version,
              "Platform": platform.platform(),
              "Python version": platform.python_version(),
              "Huggingface_hub version": huggingface_hub.__version__,
              "Safetensors version": F"""{safetensors_version}""",
              "Accelerate version": F"""{accelerate_version}""",
              "Accelerate config": F"""{accelerate_config_str}""",
              "PyTorch version (GPU?)": F"""{pt_version} ({pt_cuda_available})""",
              "Tensorflow version (GPU?)": F"""{tf_version} ({tf_cuda_available})""",
              "Flax version (CPU?/GPU?/TPU?)": F"""{flax_version} ({jax_backend})""",
              "Jax version": F"""{jax_version}""",
              "JaxLib version": F"""{jaxlib_version}""",
              "Using GPU in script?": "<fill in>",
              "Using distributed or parallel set-up in script?": "<fill in>",
          }

          print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n" )
          print(self.format_dict(lowerCamelCase ) )

          return info



      @staticmethod
      def A_			(			lowerCamelCase ):
          return "\n".join([F"""- {prop}: {val}""" for prop, val in d.items()] ) + "\n"



