





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        _a:







		def __init__(    self ,						__snake_case ,						__snake_case=1_3 ,						__snake_case=3_0 ,						__snake_case=2 ,						__snake_case=3 ,						__snake_case=True ,						__snake_case=True ,						__snake_case=3_2 ,						__snake_case=2 ,						__snake_case=4 ,						__snake_case=3_7 ,						__snake_case="gelu" ,						__snake_case=0.1 ,						__snake_case=0.1 ,						__snake_case=1_0 ,						__snake_case=0.02 ,						__snake_case=3 ,						__snake_case=None ,						__snake_case=2 ,						)      ->      str:


							'''simple docstring'''

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

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







		def        lowercase       (    self				)      ->      Optional[int]:


							'''simple docstring'''

							_snake_case       :					Union[str, Any]				       =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

							_snake_case       :					Optional[Any]				       =   self.get_config()

							return config, pixel_values, labels







		def        lowercase       (    self				)      ->      Optional[Any]:


							'''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=__snake_case ,						initializer_range=self.initializer_range ,						encoder_stride=self.encoder_stride ,						)







		def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case				)      ->      int:


							'''simple docstring'''

							_snake_case       :					Any				       =   TFDeiTModel(config=__snake_case				)
							_snake_case       :					int				       =   model(__snake_case				)
							self.parent.assertEqual(result.last_hidden_state.shape ,						(self.batch_size, self.seq_length, self.hidden_size)				)







		def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case				)      ->      Dict:


							'''simple docstring'''

							_snake_case       :					int				       =   TFDeiTForMaskedImageModeling(config=__snake_case				)
							_snake_case       :					List[Any]				       =   model(__snake_case				)
							self.parent.assertEqual(
							    result.reconstruction.shape ,						(self.batch_size, self.num_channels, self.image_size, self.image_size)				)

							# test greyscale images
							_snake_case       :					List[str]				       =   1
							_snake_case       :					Optional[Any]				       =   TFDeiTForMaskedImageModeling(__snake_case				)

							_snake_case       :					List[str]				       =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]				)
							_snake_case       :					Tuple				       =   model(__snake_case				)
							self.parent.assertEqual(result.reconstruction.shape ,						(self.batch_size, 1, self.image_size, self.image_size)				)







		def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case				)      ->      Any:


							'''simple docstring'''

							_snake_case       :					int				       =   self.type_sequence_label_size
							_snake_case       :					List[Any]				       =   TFDeiTForImageClassification(__snake_case				)
							_snake_case       :					List[str]				       =   model(__snake_case ,						labels=__snake_case				)
							self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.type_sequence_label_size)				)

							# test greyscale images
							_snake_case       :					Tuple				       =   1
							_snake_case       :					Dict				       =   TFDeiTForImageClassification(__snake_case				)

							_snake_case       :					Dict				       =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]				)
							_snake_case       :					List[str]				       =   model(__snake_case ,						labels=__snake_case				)
							self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.type_sequence_label_size)				)







		def        lowercase       (    self				)      ->      List[str]:


							'''simple docstring'''

							_snake_case       :					Tuple				       =   self.prepare_config_and_inputs()
							_snake_case       , _snake_case       , _snake_case       :					Optional[int]				       =   config_and_inputs
							_snake_case       :					List[str]				       =   {"pixel_values": pixel_values}
							return config, inputs_dict






@require_tf
class        _a(    __A	,   __A	,   unittest.TestCase    ):
		lowerCamelCase__     :List[str]   				=		(
		    (
		        TFDeiTModel,
		        TFDeiTForImageClassification,
		        TFDeiTForImageClassificationWithTeacher,
		        TFDeiTForMaskedImageModeling,
		    )
		    if is_tf_available()
		    else ()
		)
		lowerCamelCase__     :Dict   				=		(
		    {
		        'feature-extraction': TFDeiTModel,
		        'image-classification': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
		    }
		    if is_tf_available()
		    else {}
		)

		lowerCamelCase__     :Optional[Any]   				=		False
		lowerCamelCase__     :List[str]   				=		False
		lowerCamelCase__     :Optional[int]   				=		False
		lowerCamelCase__     :List[str]   				=		False







		def        lowercase       (    self				)      ->      Tuple:


							'''simple docstring'''

							_snake_case       :					Any				       =   TFDeiTModelTester(self				)
							_snake_case       :					Union[str, Any]				       =   ConfigTester(self ,						config_class=__snake_case ,						has_text_modality=__snake_case ,						hidden_size=3_7				)







		def        lowercase       (    self				)      ->      Optional[Any]:


							'''simple docstring'''

							self.config_tester.run_common_tests()







		@unittest.skip(reason="DeiT does not use inputs_embeds"				)
		def        lowercase       (    self				)      ->      Dict:


							'''simple docstring'''

							pass







		def        lowercase       (    self				)      ->      Any:


							'''simple docstring'''

							_snake_case       , _snake_case       :					Tuple				       =   self.model_tester.prepare_config_and_inputs_for_common()

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







		def        lowercase       (    self				)      ->      str:


							'''simple docstring'''

							_snake_case       , _snake_case       :					Tuple				       =   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												_snake_case       :					Dict				       =   model_class(__snake_case				)
												_snake_case       :					List[Any]				       =   inspect.signature(model.call				)
												# signature.parameters is an OrderedDict => so arg_names order is deterministic
												_snake_case       :					Dict				       =   [*signature.parameters.keys()]

												_snake_case       :					Optional[int]				       =   ["pixel_values"]
												self.assertListEqual(arg_names[:1] ,						__snake_case				)







		def        lowercase       (    self				)      ->      Dict:


							'''simple docstring'''

							_snake_case       :					Optional[Any]				       =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__snake_case				)







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


							'''simple docstring'''

							_snake_case       :					List[Any]				       =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_image_modeling(*__snake_case				)







		def        lowercase       (    self				)      ->      Optional[Any]:


							'''simple docstring'''

							_snake_case       :					List[Any]				       =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__snake_case				)







		def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case=False				)      ->      List[Any]:


							'''simple docstring'''

							_snake_case       :					List[str]				       =   super()._prepare_for_class(__snake_case ,						__snake_case ,						return_labels=__snake_case				)

							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        lowercase       (    self				)      ->      List[Any]:


							'''simple docstring'''

							for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												_snake_case       :					int				       =   TFDeiTModel.from_pretrained(__snake_case				)
												self.assertIsNotNone(__snake_case				)







def    A				(							):
					_snake_case       :					str				       =   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
					return image






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







		@cached_property
		def        lowercase       (    self				)      ->      Tuple:


							'''simple docstring'''

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







		@slow
		def        lowercase       (    self				)      ->      Tuple:


							'''simple docstring'''

							_snake_case       :					Dict				       =   TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224"				)

							_snake_case       :					Dict				       =   self.default_image_processor
							_snake_case       :					str				       =   prepare_img()
							_snake_case       :					Tuple				       =   image_processor(images=__snake_case ,						return_tensors="tf"				)

							# forward pass
							_snake_case       :					List[str]				       =   model(**__snake_case				)

							# verify the logits
							_snake_case       :					int				       =   tf.TensorShape((1, 1_0_0_0)				)
							self.assertEqual(outputs.logits.shape ,						__snake_case				)

							_snake_case       :					str				       =   tf.constant([-1.02_66, 0.19_12, -1.28_61]				)

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






import datasets

from .evaluate import evaluate


__lowerCAmelCase :Any     =    '\\n@article{hendrycks2021cuad,\n      title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n      author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n      journal={arXiv preprint arXiv:2103.06268},\n      year={2021}\n}\n'

__lowerCAmelCase :Union[str, Any]     =    '\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n'

__lowerCAmelCase :Optional[Any]     =    '\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n    predictions: List of question-answers dictionaries with the following key-values:\n        - \'id\': id of the question-answer pair as given in the references (see below)\n        - \'prediction_text\': list of possible texts for the answer, as a list of strings\n        depending on a threshold on the confidence probability of each prediction.\n    references: List of question-answers dictionaries with the following key-values:\n        - \'id\': id of the question-answer pair (see above),\n        - \'answers\': a Dict in the CUAD dataset format\n            {\n                \'text\': list of possible texts for the answer, as a list of strings\n                \'answer_start\': list of start positions for the answer, as a list of ints\n            }\n            Note that answer_start values are not taken into account to compute the metric.\nReturns:\n    \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n    \'f1\': The F-score of predicted tokens versus the gold answer\n    \'aupr\': Area Under the Precision-Recall curve\n    \'prec_at_80_recall\': Precision at 80% recall\n    \'prec_at_90_recall\': Precision at 90% recall\nExamples:\n    >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n    >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n    >>> cuad_metric = datasets.load_metric("cuad")\n    >>> results = cuad_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}\n'






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,   _KWARGS_DESCRIPTION    )
class        _a(    datasets.Metric    ):







		def        lowercase       (    self				)      ->      Optional[int]:


							'''simple docstring'''

							return datasets.MetricInfo(
							    description=_DESCRIPTION ,						citation=_CITATION ,						inputs_description=_KWARGS_DESCRIPTION ,						features=datasets.Features(
							        {
							            "predictions": {
							                "id": datasets.Value("string"				),
							                "prediction_text": datasets.features.Sequence(datasets.Value("string"				)				),
							            },
							            "references": {
							                "id": datasets.Value("string"				),
							                "answers": datasets.features.Sequence(
							                    {
							                        "text": datasets.Value("string"				),
							                        "answer_start": datasets.Value("int32"				),
							                    }				),
							            },
							        }				) ,						codebase_urls=["https://www.atticusprojectai.org/cuad"] ,						reference_urls=["https://www.atticusprojectai.org/cuad"] ,						)







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


							'''simple docstring'''

							_snake_case       :					str				       =   {prediction["id"]: prediction["prediction_text"] for prediction in predictions}
							_snake_case       :					Union[str, Any]				       =   [
							    {
							        "paragraphs": [
							            {
							                "qas": [
							                    {
							                        "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]],
							                        "id": ref["id"],
							                    }
							                    for ref in references
							                ]
							            }
							        ]
							    }
							]
							_snake_case       :					Union[str, Any]				       =   evaluate(dataset=__snake_case ,						predictions=__snake_case				)
							return score