





from __future__ import annotations

import inspect
import unittest

import numpy as np

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import (
      TFDeiTForImageClassification,
      TFDeiTForImageClassificationWithTeacher,
      TFDeiTForMaskedImageModeling,
      TFDeiTModel,
  )
  from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import DeiTImageProcessor






class 					lowercase__ :

   '''simple docstring'''


   def __init__(					self,	__magic_name__,	__magic_name__=13,	__magic_name__=30,	__magic_name__=2,	__magic_name__=3,	__magic_name__=True,	__magic_name__=True,	__magic_name__=32,	__magic_name__=2,	__magic_name__=4,	__magic_name__=37,	__magic_name__="gelu",	__magic_name__=0.1,	__magic_name__=0.1,	__magic_name__=10,	__magic_name__=0.02,	__magic_name__=3,	__magic_name__=None,	__magic_name__=2,	)				->   Tuple:






       """simple docstring"""
       UpperCamelCase__							:       Tuple      =   parent
       UpperCamelCase__							:       Union[str, Any]      =   batch_size
       UpperCamelCase__							:       List[str]      =   image_size
       UpperCamelCase__							:       int      =   patch_size
       UpperCamelCase__							:       Tuple      =   num_channels
       UpperCamelCase__							:       Dict      =   is_training
       UpperCamelCase__							:       Optional[Any]      =   use_labels
       UpperCamelCase__							:       str      =   hidden_size
       UpperCamelCase__							:       Any      =   num_hidden_layers
       UpperCamelCase__							:       Union[str, Any]      =   num_attention_heads
       UpperCamelCase__							:       Optional[int]      =   intermediate_size
       UpperCamelCase__							:       int      =   hidden_act
       UpperCamelCase__							:       Optional[int]      =   hidden_dropout_prob
       UpperCamelCase__							:       Optional[Any]      =   attention_probs_dropout_prob
       UpperCamelCase__							:       List[str]      =   type_sequence_label_size
       UpperCamelCase__							:       List[str]      =   initializer_range
       UpperCamelCase__							:       str      =   scope
       UpperCamelCase__							:       Dict      =   encoder_stride

       # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
       UpperCamelCase__							:       Optional[Any]      =   (image_size // patch_size) ** 2
       UpperCamelCase__							:       Optional[int]      =   num_patches + 2




   def    UpperCamelCase__						(					self							)				->   str:






       """simple docstring"""
       UpperCamelCase__							:       List[str]      =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

       UpperCamelCase__							:       Optional[int]      =   None
       if self.use_labels:
           UpperCamelCase__							:       str      =   ids_tensor([self.batch_size],	self.type_sequence_label_size							)

       UpperCamelCase__							:       Tuple      =   self.get_config()

       return config, pixel_values, labels




   def    UpperCamelCase__						(					self							)				->   int:






       """simple docstring"""
       return DeiTConfig(
           image_size=self.image_size,	patch_size=self.patch_size,	num_channels=self.num_channels,	hidden_size=self.hidden_size,	num_hidden_layers=self.num_hidden_layers,	num_attention_heads=self.num_attention_heads,	intermediate_size=self.intermediate_size,	hidden_act=self.hidden_act,	hidden_dropout_prob=self.hidden_dropout_prob,	attention_probs_dropout_prob=self.attention_probs_dropout_prob,	is_decoder=__magic_name__,	initializer_range=self.initializer_range,	encoder_stride=self.encoder_stride,	)




   def    UpperCamelCase__						(					self,	__magic_name__,	__magic_name__,	__magic_name__							)				->   Tuple:






       """simple docstring"""
       UpperCamelCase__							:       Any      =   TFDeiTModel(config=__magic_name__							)
       UpperCamelCase__							:       Any      =   model(__magic_name__							)
       self.parent.assertEqual(result.last_hidden_state.shape,	(self.batch_size, self.seq_length, self.hidden_size)							)




   def    UpperCamelCase__						(					self,	__magic_name__,	__magic_name__,	__magic_name__							)				->   Tuple:






       """simple docstring"""
       UpperCamelCase__							:       int      =   TFDeiTForMaskedImageModeling(config=__magic_name__							)
       UpperCamelCase__							:       List[str]      =   model(__magic_name__							)
       self.parent.assertEqual(
           result.reconstruction.shape,	(self.batch_size, self.num_channels, self.image_size, self.image_size)							)

       # test greyscale images
       UpperCamelCase__							:       Tuple      =   1
       UpperCamelCase__							:       int      =   TFDeiTForMaskedImageModeling(__magic_name__							)

       UpperCamelCase__							:       List[str]      =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
       UpperCamelCase__							:       Union[str, Any]      =   model(__magic_name__							)
       self.parent.assertEqual(result.reconstruction.shape,	(self.batch_size, 1, self.image_size, self.image_size)							)




   def    UpperCamelCase__						(					self,	__magic_name__,	__magic_name__,	__magic_name__							)				->   Optional[int]:






       """simple docstring"""
       UpperCamelCase__							:       Union[str, Any]      =   self.type_sequence_label_size
       UpperCamelCase__							:       str      =   TFDeiTForImageClassification(__magic_name__							)
       UpperCamelCase__							:       Union[str, Any]      =   model(__magic_name__,	labels=__magic_name__							)
       self.parent.assertEqual(result.logits.shape,	(self.batch_size, self.type_sequence_label_size)							)

       # test greyscale images
       UpperCamelCase__							:       str      =   1
       UpperCamelCase__							:       Optional[Any]      =   TFDeiTForImageClassification(__magic_name__							)

       UpperCamelCase__							:       Dict      =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
       UpperCamelCase__							:       int      =   model(__magic_name__,	labels=__magic_name__							)
       self.parent.assertEqual(result.logits.shape,	(self.batch_size, self.type_sequence_label_size)							)




   def    UpperCamelCase__						(					self							)				->   str:






       """simple docstring"""
       UpperCamelCase__							:       Union[str, Any]      =   self.prepare_config_and_inputs()
       UpperCamelCase__     ,UpperCamelCase__     ,UpperCamelCase__							:       Any      =   config_and_inputs
       UpperCamelCase__							:       Dict      =   {'''pixel_values''': pixel_values}
       return config, inputs_dict






@require_tf
class 					lowercase__ (			__lowerCamelCase    ,       __lowerCamelCase    ,       unittest.TestCase       ):

   '''simple docstring'''


   a		:							str     	=	(
       (
           TFDeiTModel,
           TFDeiTForImageClassification,
           TFDeiTForImageClassificationWithTeacher,
           TFDeiTForMaskedImageModeling,
       )
       if is_tf_available()
       else ()
   )
   a		:							Tuple     	=	(
       {
           """feature-extraction""": TFDeiTModel,
           """image-classification""": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
       }
       if is_tf_available()
       else {}
   )

   a		:							Union[str, Any]     	=	False
   a		:							List[str]     	=	False
   a		:							List[str]     	=	False
   a		:							List[Any]     	=	False




   def    UpperCamelCase__						(					self							)				->   int:






       """simple docstring"""
       UpperCamelCase__							:       int      =   TFDeiTModelTester(self							)
       UpperCamelCase__							:       Union[str, Any]      =   ConfigTester(self,	config_class=__magic_name__,	has_text_modality=__magic_name__,	hidden_size=37							)




   def    UpperCamelCase__						(					self							)				->   Dict:






       """simple docstring"""
       self.config_tester.run_common_tests()




   @unittest.skip(reason='''DeiT does not use inputs_embeds'''							)
   def    UpperCamelCase__						(					self							)				->   Optional[Any]:






       """simple docstring"""
       pass




   def    UpperCamelCase__						(					self							)				->   Tuple:






       """simple docstring"""
       UpperCamelCase__     ,UpperCamelCase__							:       Optional[Any]      =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           UpperCamelCase__							:       str      =   model_class(__magic_name__							)
           self.assertIsInstance(model.get_input_embeddings(),	(tf.keras.layers.Layer)							)
           UpperCamelCase__							:       Union[str, Any]      =   model.get_output_embeddings()
           self.assertTrue(x is None or isinstance(__magic_name__,	tf.keras.layers.Dense							)							)




   def    UpperCamelCase__						(					self							)				->   Tuple:






       """simple docstring"""
       UpperCamelCase__     ,UpperCamelCase__							:       Union[str, Any]      =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           UpperCamelCase__							:       Any      =   model_class(__magic_name__							)
           UpperCamelCase__							:       Optional[int]      =   inspect.signature(model.call							)
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           UpperCamelCase__							:       Any      =   [*signature.parameters.keys()]

           UpperCamelCase__							:       List[Any]      =   ['''pixel_values''']
           self.assertListEqual(arg_names[:1],	__magic_name__							)




   def    UpperCamelCase__						(					self							)				->   Tuple:






       """simple docstring"""
       UpperCamelCase__							:       List[str]      =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__magic_name__							)




   def    UpperCamelCase__						(					self							)				->   Union[str, Any]:






       """simple docstring"""
       UpperCamelCase__							:       Tuple      =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*__magic_name__							)




   def    UpperCamelCase__						(					self							)				->   int:






       """simple docstring"""
       UpperCamelCase__							:       Tuple      =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__magic_name__							)




   def    UpperCamelCase__						(					self,	__magic_name__,	__magic_name__,	__magic_name__=False							)				->   int:






       """simple docstring"""
       UpperCamelCase__							:       Optional[Any]      =   super()._prepare_for_class(__magic_name__,	__magic_name__,	return_labels=__magic_name__							)

       if return_labels:
           if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call							).parameters:
               del inputs_dict["labels"]

       return inputs_dict




   @slow
   def    UpperCamelCase__						(					self							)				->   Tuple:






       """simple docstring"""

       for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase__							:       Any      =   TFDeiTModel.from_pretrained(__magic_name__							)
           self.assertIsNotNone(__magic_name__							)




def 	lowerCAmelCase_					(						)   ->			List[Any]:
    UpperCamelCase__							:       Any      =   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
    return image






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

   '''simple docstring'''


   @cached_property
   def    UpperCamelCase__						(					self							)				->   int:






       """simple docstring"""
       return (
           DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224'''							)
           if is_vision_available()
           else None
       )




   @slow
   def    UpperCamelCase__						(					self							)				->   Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:       int      =   TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224'''							)

       UpperCamelCase__							:       Tuple      =   self.default_image_processor
       UpperCamelCase__							:       Union[str, Any]      =   prepare_img()
       UpperCamelCase__							:       Optional[Any]      =   image_processor(images=__magic_name__,	return_tensors='''tf'''							)

       # forward pass
       UpperCamelCase__							:       List[str]      =   model(**__magic_name__							)

       # verify the logits
       UpperCamelCase__							:       Optional[Any]      =   tf.TensorShape((1, 1000)							)
       self.assertEqual(outputs.logits.shape,	__magic_name__							)

       UpperCamelCase__							:       Optional[Any]      =   tf.constant([-1.0266, 0.1912, -1.2861]							)

       self.assertTrue(np.allclose(outputs.logits[0, :3],	__magic_name__,	atol=1E-4							)							)








import argparse

from transformers import (
    TapasConfig,
    TapasForMaskedLM,
    TapasForQuestionAnswering,
    TapasForSequenceClassification,
    TapasModel,
    TapasTokenizer,
    load_tf_weights_in_tapas,
)
from transformers.utils import logging


logging.set_verbosity_info()




def 	lowerCAmelCase_					(						__UpperCAmelCase:    Optional[Any]	,     __UpperCAmelCase:    List[str]	,     __UpperCAmelCase:    Dict	,     __UpperCAmelCase:    Tuple	,     __UpperCAmelCase:    str   )   ->			Optional[int]:
    # Initialise PyTorch model.
    # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of
    # TapasConfig to False.

    # initialize configuration from json file
    UpperCamelCase__							:       Any      =   TapasConfig.from_json_file(__UpperCAmelCase   )
    # set absolute/relative position embeddings parameter
    UpperCamelCase__							:       Optional[Any]      =   reset_position_index_per_cell

    # set remaining parameters of TapasConfig as well as the model based on the task
    if task == "SQA":
        UpperCamelCase__							:       List[Any]      =   TapasForQuestionAnswering(config=__UpperCAmelCase   )
    elif task == "WTQ":
        # run_task_main.py hparams
        UpperCamelCase__							:       Any      =   4
        UpperCamelCase__							:       List[str]      =   True
        # hparam_utils.py hparams
        UpperCamelCase__							:       int      =   0.664694
        UpperCamelCase__							:       Union[str, Any]      =   0.207951
        UpperCamelCase__							:       Any      =   0.121194
        UpperCamelCase__							:       int      =   True
        UpperCamelCase__							:       Any      =   True
        UpperCamelCase__							:       str      =   False
        UpperCamelCase__							:       int      =   0.0352513

        UpperCamelCase__							:       Dict      =   TapasForQuestionAnswering(config=__UpperCAmelCase   )
    elif task == "WIKISQL_SUPERVISED":
        # run_task_main.py hparams
        UpperCamelCase__							:       Any      =   4
        UpperCamelCase__							:       List[str]      =   False
        # hparam_utils.py hparams
        UpperCamelCase__							:       int      =   36.4519
        UpperCamelCase__							:       int      =   0.903421
        UpperCamelCase__							:       List[str]      =   222.088
        UpperCamelCase__							:       Dict      =   True
        UpperCamelCase__							:       List[str]      =   True
        UpperCamelCase__							:       Any      =   True
        UpperCamelCase__							:       int      =   0.763141

        UpperCamelCase__							:       Union[str, Any]      =   TapasForQuestionAnswering(config=__UpperCAmelCase   )
    elif task == "TABFACT":
        UpperCamelCase__							:       List[Any]      =   TapasForSequenceClassification(config=__UpperCAmelCase   )
    elif task == "MLM":
        UpperCamelCase__							:       Optional[Any]      =   TapasForMaskedLM(config=__UpperCAmelCase   )
    elif task == "INTERMEDIATE_PRETRAINING":
        UpperCamelCase__							:       str      =   TapasModel(config=__UpperCAmelCase   )
    else:
        raise ValueError(f"Task {task} not supported."   )

    print(f"Building PyTorch model from configuration: {config}"   )
    # Load weights from tf checkpoint
    load_tf_weights_in_tapas(__UpperCAmelCase	,     __UpperCAmelCase	,     __UpperCAmelCase   )

    # Save pytorch-model (weights and configuration)
    print(f"Save PyTorch model to {pytorch_dump_path}"   )
    model.save_pretrained(__UpperCAmelCase   )

    # Save tokenizer files
    print(f"Save tokenizer files to {pytorch_dump_path}"   )
    UpperCamelCase__							:       str      =   TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt'''	,     model_max_length=512   )
    tokenizer.save_pretrained(__UpperCAmelCase   )

    print('''Used relative position embeddings:'''	,     model.config.reset_position_index_per_cell   )


if __name__ == "__main__":
  UpperCAmelCase_  							=				argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.'
  )
  parser.add_argument(
      '--reset_position_index_per_cell',
      default=False,
      action='store_true',
      help='Whether to use relative position embeddings or not. Defaults to True.',
  )
  parser.add_argument(
      '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.'
  )
  parser.add_argument(
      '--tapas_config_file',
      default=None,
      type=str,
      required=True,
      help=(
          'The config json file corresponding to the pre-trained TAPAS model. \n'
          'This specifies the model architecture.'
      ),
  )
  parser.add_argument(
      '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
  )
  UpperCAmelCase_  							=				parser.parse_args()
  convert_tf_checkpoint_to_pytorch(
      args.task,
      args.reset_position_index_per_cell,
      args.tf_checkpoint_path,
      args.tapas_config_file,
      args.pytorch_dump_path,
  )

