


'''simple docstring'''

from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
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 TFViTForImageClassification, TFViTModel


if is_vision_available():
 from PIL import Image

 from transformers import ViTImageProcessor
class   __lowerCAmelCase						:





      '''simple docstring'''






      def __init__(self    :    Optional[Any]   ,						UpperCamelCase    :    Any   ,						UpperCamelCase    :    Tuple=13   ,						UpperCamelCase    :    Dict=30   ,						UpperCamelCase    :    int=2   ,						UpperCamelCase    :    Any=3   ,						UpperCamelCase    :    List[Any]=True   ,						UpperCamelCase    :    Dict=True   ,						UpperCamelCase    :    Optional[int]=32   ,						UpperCamelCase    :    Optional[int]=2   ,						UpperCamelCase    :    str=4   ,						UpperCamelCase    :    Any=37   ,						UpperCamelCase    :    Any="gelu"   ,						UpperCamelCase    :    List[Any]=0.1   ,						UpperCamelCase    :    List[Any]=0.1   ,						UpperCamelCase    :    str=10   ,						UpperCamelCase    :    Any=0.02   ,						UpperCamelCase    :    str=3   ,						UpperCamelCase    :    Optional[int]=None   ,						):

             '''simple docstring'''







             lowercase__      			= parent
             lowercase__      			= batch_size
             lowercase__      			= image_size
             lowercase__      			= patch_size
             lowercase__      			= num_channels
             lowercase__      			= is_training
             lowercase__      			= use_labels
             lowercase__      			= hidden_size
             lowercase__      			= num_hidden_layers
             lowercase__      			= num_attention_heads
             lowercase__      			= intermediate_size
             lowercase__      			= hidden_act
             lowercase__      			= hidden_dropout_prob
             lowercase__      			= attention_probs_dropout_prob
             lowercase__      			= type_sequence_label_size
             lowercase__      			= initializer_range
             lowercase__      			= scope

             # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
             lowercase__      			= (image_size // patch_size) ** 2
             lowercase__      			= num_patches + 1



      def       UpperCamelCase__		(self    :    Any ):

             '''simple docstring'''







             lowercase__      			= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

             lowercase__      			= None
             if self.use_labels:
                    lowercase__      			= ids_tensor([self.batch_size]   ,						self.type_sequence_label_size )

             lowercase__      			= self.get_config()

             return config, pixel_values, labels



      def       UpperCamelCase__		(self    :    Tuple ):

             '''simple docstring'''







             return ViTConfig(
                 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=UpperCamelCase   ,						initializer_range=self.initializer_range   ,						)



      def       UpperCamelCase__		(self    :    Optional[Any]   ,						UpperCamelCase    :    List[Any]   ,						UpperCamelCase    :    Optional[Any]   ,						UpperCamelCase    :    Optional[Any] ):

             '''simple docstring'''







             lowercase__      			= TFViTModel(config=UpperCamelCase )
             lowercase__      			= model(UpperCamelCase   ,						training=UpperCamelCase )
             self.parent.assertEqual(result.last_hidden_state.shape   ,						(self.batch_size, self.seq_length, self.hidden_size) )

             # Test with an image with different size than the one specified in config.
             lowercase__      			= self.image_size // 2
             lowercase__      			= pixel_values[:, :, :image_size, :image_size]
             lowercase__      			= model(UpperCamelCase   ,						interpolate_pos_encoding=UpperCamelCase   ,						training=UpperCamelCase )
             lowercase__      			= (image_size // self.patch_size) ** 2 + 1
             self.parent.assertEqual(result.last_hidden_state.shape   ,						(self.batch_size, seq_length, self.hidden_size) )



      def       UpperCamelCase__		(self    :    Dict   ,						UpperCamelCase    :    List[Any]   ,						UpperCamelCase    :    List[str]   ,						UpperCamelCase    :    Union[str, Any] ):

             '''simple docstring'''







             lowercase__      			= self.type_sequence_label_size
             lowercase__      			= TFViTForImageClassification(UpperCamelCase )
             lowercase__      			= model(UpperCamelCase   ,						labels=UpperCamelCase   ,						training=UpperCamelCase )
             self.parent.assertEqual(result.logits.shape   ,						(self.batch_size, self.type_sequence_label_size) )

             # Test with an image with different size than the one specified in config.
             lowercase__      			= self.image_size // 2
             lowercase__      			= pixel_values[:, :, :image_size, :image_size]
             lowercase__      			= model(UpperCamelCase   ,						interpolate_pos_encoding=UpperCamelCase   ,						training=UpperCamelCase )
             self.parent.assertEqual(result.logits.shape   ,						(self.batch_size, self.type_sequence_label_size) )

             # test greyscale images
             lowercase__      			= 1
             lowercase__      			= TFViTForImageClassification(UpperCamelCase )
             lowercase__      			= floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
             lowercase__      			= model(UpperCamelCase )
             self.parent.assertEqual(result.logits.shape   ,						(self.batch_size, self.type_sequence_label_size) )






      def       UpperCamelCase__		(self    :    Dict ):

             '''simple docstring'''







             lowercase__      			= self.prepare_config_and_inputs()
             lowercase__			,lowercase__			,lowercase__      			= config_and_inputs
             lowercase__      			= {'''pixel_values''': pixel_values}
             return config, inputs_dict






@require_tf
class   __lowerCAmelCase						(lowercase_  ,     lowercase_  ,     unittest.TestCase     ):





      '''simple docstring'''






      lowerCAmelCase__					:     Optional[Any]  					=							(TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
      lowerCAmelCase__					:     Tuple  					=							(
          {"""feature-extraction""": TFViTModel, """image-classification""": TFViTForImageClassification}
          if is_tf_available()
          else {}
      )

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



      def       UpperCamelCase__		(self    :    Dict ):

             '''simple docstring'''







             lowercase__      			= TFViTModelTester(self )
             lowercase__      			= ConfigTester(self   ,						config_class=UpperCamelCase   ,						has_text_modality=UpperCamelCase   ,						hidden_size=37 )



      def       UpperCamelCase__		(self    :    Tuple ):

             '''simple docstring'''







             self.config_tester.run_common_tests()



      @unittest.skip(reason='''ViT does not use inputs_embeds''' )
      def       UpperCamelCase__		(self    :    str ):

             '''simple docstring'''







             pass



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

             '''simple docstring'''







             pass



      def       UpperCamelCase__		(self    :    List[Any] ):

             '''simple docstring'''







             lowercase__			,lowercase__      			= self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    lowercase__      			= model_class(UpperCamelCase )
                    self.assertIsInstance(model.get_input_embeddings()   ,						(tf.keras.layers.Layer) )
                    lowercase__      			= model.get_output_embeddings()
                    self.assertTrue(x is None or isinstance(UpperCamelCase   ,						tf.keras.layers.Layer ) )



      def       UpperCamelCase__		(self    :    List[str] ):

             '''simple docstring'''







             lowercase__			,lowercase__      			= self.model_tester.prepare_config_and_inputs_for_common()

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

                    lowercase__      			= ['''pixel_values''']
                    self.assertListEqual(arg_names[:1]   ,						UpperCamelCase )



      def       UpperCamelCase__		(self    :    List[Any] ):

             '''simple docstring'''







             lowercase__      			= self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*UpperCamelCase )



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

             '''simple docstring'''







             lowercase__      			= self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*UpperCamelCase )






      @slow
      def       UpperCamelCase__		(self    :    List[str] ):

             '''simple docstring'''







             lowercase__      			= TFViTModel.from_pretrained('''google/vit-base-patch16-224''' )
             self.assertIsNotNone(UpperCamelCase )






def _SCREAMING_SNAKE_CASE      ()       ->       List[Any]:






       """simple docstring"""







       lowercase__      			= Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''       )
       return image

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





      '''simple docstring'''






      @cached_property
      def       UpperCamelCase__		(self    :    str ):

             '''simple docstring'''







             return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224''' ) if is_vision_available() else None






      @slow
      def       UpperCamelCase__		(self    :    Union[str, Any] ):

             '''simple docstring'''







             lowercase__      			= TFViTForImageClassification.from_pretrained('''google/vit-base-patch16-224''' )

             lowercase__      			= self.default_image_processor
             lowercase__      			= prepare_img()
             lowercase__      			= image_processor(images=UpperCamelCase   ,						return_tensors='''tf''' )

             # forward pass
             lowercase__      			= model(**UpperCamelCase )

             # verify the logits
             lowercase__      			= tf.TensorShape((1, 1000) )
             self.assertEqual(outputs.logits.shape   ,						UpperCamelCase )

             lowercase__      			= tf.constant([-0.27_44, 0.82_15, -0.08_36] )

             tf.debugging.assert_near(outputs.logits[0, :3]   ,						UpperCamelCase   ,						atol=1E-4 )











from sklearn.metrics import fa_score

import datasets


__lowerCamelCase       :     List[Any]   =     """
The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:
F1 = 2 * (precision * recall) / (precision + recall)
"""


__lowerCamelCase       :     List[Any]   =     """
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.

        - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.
        - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.
        - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.

Examples:

    Example 1-A simple binary example
        >>> f1_metric = datasets.load_metric(\"f1\")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {'f1': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> f1_metric = datasets.load_metric(\"f1\")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results['f1'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> f1_metric = datasets.load_metric(\"f1\")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])
        >>> print(round(results['f1'], 2))
        0.35

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")
        >>> print(round(results['f1'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")
        >>> print(round(results['f1'], 2))
        0.33
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")
        >>> print(round(results['f1'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {'f1': array([0.8, 0. , 0. ])}
"""


__lowerCamelCase       :     str   =     """
@article{scikit-learn,
    title={Scikit-learn: Machine Learning in {P}ython},
    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
           and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
           and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
           Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
    journal={Journal of Machine Learning Research},
    volume={12},
    pages={2825--2830},
    year={2011}
}
"""



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





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       return datasets.MetricInfo(
           description=_DESCRIPTION       ,							citation=_CITATION       ,							inputs_description=_KWARGS_DESCRIPTION       ,							features=datasets.Features(
               {
                   "predictions": datasets.Sequence(datasets.Value("int32"   )   ),
                   "references": datasets.Sequence(datasets.Value("int32"   )   ),
               }
               if self.config_name == "multilabel"
               else {
                   "predictions": datasets.Value("int32"   ),
                   "references": datasets.Value("int32"   ),
               }   )       ,							reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"]       ,							)





      def        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_=None       ,							A_=1       ,							A_="binary"       ,							A_=None   ):
       '''simple docstring'''




       UpperCamelCase	:					List[str]       	=   fa_score(
           A_       ,							A_       ,							labels=A_       ,							pos_label=A_       ,							average=A_       ,							sample_weight=A_   )
       return {"f1": float(A_   ) if score.size == 1 else score}
