

from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
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 TFCvtForImageClassification, TFCvtModel
       from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor


class       SCREAMING_SNAKE_CASE__					(__snake_case     ):





    def       snake_case_				(      self):
         lowercase__    :   Optional[Any]      =       self.config_class(**self.inputs_dict)
         self.parent.assertTrue(hasattr(a						,   'embed_dim'))
         self.parent.assertTrue(hasattr(a						,   'num_heads'))



class       SCREAMING_SNAKE_CASE__					:





    def __init__(      self						,   a						,   a=13						,   a=64						,   a=3						,   a=[16, 48, 96]						,   a=[1, 3, 6]						,   a=[1, 2, 10]						,   a=[7, 3, 3]						,   a=[4, 2, 2]						,   a=[2, 1, 1]						,   a=[2, 2, 2]						,   a=[False, False, True]						,   a=[0.0, 0.0, 0.0]						,   a=0.02						,   a=1e-12						,   a=True						,   a=True						,   a=2						,   ):
         lowercase__    :   Dict      =       parent
         lowercase__    :   Optional[int]      =       batch_size
         lowercase__    :   Optional[Any]      =       image_size
         lowercase__    :   Optional[int]      =       patch_sizes
         lowercase__    :   Union[str, Any]      =       patch_stride
         lowercase__    :   int      =       patch_padding
         lowercase__    :   List[Any]      =       is_training
         lowercase__    :   Tuple      =       use_labels
         lowercase__    :   Optional[Any]      =       num_labels
         lowercase__    :   Union[str, Any]      =       num_channels
         lowercase__    :   Any      =       embed_dim
         lowercase__    :   str      =       num_heads
         lowercase__    :   int      =       stride_kv
         lowercase__    :   Optional[Any]      =       depth
         lowercase__    :   List[Any]      =       cls_token
         lowercase__    :   Dict      =       attention_drop_rate
         lowercase__    :   Optional[int]      =       initializer_range
         lowercase__    :   Dict      =       layer_norm_eps





    def       snake_case_				(      self):
         lowercase__    :   List[str]      =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

         lowercase__    :   Optional[Any]      =       None
         if self.use_labels:
              # create a random int32 tensor of given shape
              lowercase__    :   Optional[Any]      =       ids_tensor([self.batch_size]						,   self.num_labels)

         lowercase__    :   int      =       self.get_config()
         return config, pixel_values, labels





    def       snake_case_				(      self):
         return CvtConfig(
             image_size=self.image_size						,   num_labels=self.num_labels						,   num_channels=self.num_channels						,   embed_dim=self.embed_dim						,   num_heads=self.num_heads						,   patch_sizes=self.patch_sizes						,   patch_padding=self.patch_padding						,   patch_stride=self.patch_stride						,   stride_kv=self.stride_kv						,   depth=self.depth						,   cls_token=self.cls_token						,   attention_drop_rate=self.attention_drop_rate						,   initializer_range=self.initializer_range						,   )





    def       snake_case_				(      self						,   a						,   a						,   a):
         lowercase__    :   Any      =       TFCvtModel(config=a)
         lowercase__    :   Any      =       model(a						,   training=a)
         lowercase__    :   int      =       (self.image_size, self.image_size)
         lowercase__      , lowercase__    :   Any      =       image_size[0], image_size[1]
         for i in range(len(self.depth)):
              lowercase__    :   Optional[int]      =       floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
              lowercase__    :   Optional[Any]      =       floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
         self.parent.assertEqual(result.last_hidden_state.shape						,   (self.batch_size, self.embed_dim[-1], height, width))





    def       snake_case_				(      self						,   a						,   a						,   a):
         lowercase__    :   int      =       self.num_labels
         lowercase__    :   Dict      =       TFCvtForImageClassification(a)
         lowercase__    :   int      =       model(a						,   labels=a						,   training=a)
         self.parent.assertEqual(result.logits.shape						,   (self.batch_size, self.num_labels))





    def       snake_case_				(      self):
         lowercase__    :   int      =       self.prepare_config_and_inputs()
         lowercase__      , lowercase__      , lowercase__    :   int      =       config_and_inputs
         lowercase__    :   Optional[Any]      =       {'pixel_values': pixel_values}
         return config, inputs_dict



@require_tf
class       SCREAMING_SNAKE_CASE__					(__snake_case		,       __snake_case		,       unittest.TestCase     ):
    __lowerCamelCase						:       List[Any]														=     (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
    __lowerCamelCase						:       List[Any]														=     (
        {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
        if is_tf_available()
        else {}
    )
    __lowerCamelCase						:       Union[str, Any]														=     False
    __lowerCamelCase						:       Optional[Any]														=     False
    __lowerCamelCase						:       Any														=     False
    __lowerCamelCase						:       str														=     False
    __lowerCamelCase						:       Union[str, Any]														=     False





    def       snake_case_				(      self):
         lowercase__    :   int      =       TFCvtModelTester(self)
         lowercase__    :   int      =       TFCvtConfigTester(self						,   config_class=a						,   has_text_modality=a						,   hidden_size=37)





    def       snake_case_				(      self):
         self.config_tester.create_and_test_config_common_properties()
         self.config_tester.create_and_test_config_to_json_string()
         self.config_tester.create_and_test_config_to_json_file()
         self.config_tester.create_and_test_config_from_and_save_pretrained()
         self.config_tester.create_and_test_config_with_num_labels()
         self.config_tester.check_config_can_be_init_without_params()
         self.config_tester.check_config_arguments_init()





    @unittest.skip(reason='Cvt does not output attentions')
    def       snake_case_				(      self):
         pass





    @unittest.skip(reason='Cvt does not use inputs_embeds')
    def       snake_case_				(      self):
         pass





    @unittest.skip(reason='Cvt does not support input and output embeddings')
    def       snake_case_				(      self):
         pass





    @unittest.skipIf(
        not is_tf_available() or len(tf.config.list_physical_devices('GPU')) == 0						,   reason='TF does not support backprop for grouped convolutions on CPU.'						,   )
    def       snake_case_				(      self):
         super().test_dataset_conversion()





    @unittest.skipIf(
        not is_tf_available() or len(tf.config.list_physical_devices('GPU')) == 0						,   reason='TF does not support backprop for grouped convolutions on CPU.'						,   )
    @slow
    def       snake_case_				(      self):
         super().test_keras_fit()





    @unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8')
    def       snake_case_				(      self):
         lowercase__    :   List[str]      =       tf.keras.mixed_precision.Policy('mixed_float16')
         tf.keras.mixed_precision.set_global_policy(a)
         super().test_keras_fit()
         tf.keras.mixed_precision.set_global_policy('float32')





    def       snake_case_				(      self):
         lowercase__      , lowercase__    :   int      =       self.model_tester.prepare_config_and_inputs_for_common()

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

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





    def       snake_case_				(      self):
         def check_hidden_states_output(a						,   a						,   a):
              lowercase__    :   str      =       model_class(a)

              lowercase__    :   List[Any]      =       model(**self._prepare_for_class(a						,   a))
              lowercase__    :   List[Any]      =       outputs.hidden_states

              lowercase__    :   Optional[int]      =       len(self.model_tester.depth)
              self.assertEqual(len(a)						,   a)

              # verify the first hidden states (first block)
              self.assertListEqual(
                  list(hidden_states[0].shape[-3:])						,   [
                      self.model_tester.embed_dim[0],
                      self.model_tester.image_size // 4,
                      self.model_tester.image_size // 4,
                  ]						,   )

         lowercase__      , lowercase__    :   int      =       self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              lowercase__    :   int      =       True
              check_hidden_states_output(a						,   a						,   a)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              lowercase__    :   Optional[Any]      =       True

              check_hidden_states_output(a						,   a						,   a)





    def       snake_case_				(      self):
         lowercase__    :   Optional[int]      =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*a)





    def       snake_case_				(      self):
         lowercase__    :   Optional[Any]      =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*a)





    @slow
    def       snake_case_				(      self):
         for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              lowercase__    :   int      =       TFCvtModel.from_pretrained(a)
              self.assertIsNotNone(a)



def 	snake_case__			(    ):



     '''simple docstring'''





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


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





    @cached_property
    def       snake_case_				(      self):
         return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])





    @slow
    def       snake_case_				(      self):
         lowercase__    :   Dict      =       TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])

         lowercase__    :   Union[str, Any]      =       self.default_image_processor
         lowercase__    :   Union[str, Any]      =       prepare_img()
         lowercase__    :   List[Any]      =       image_processor(images=a						,   return_tensors='tf')

         # forward pass
         lowercase__    :   Any      =       model(**a)

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

         lowercase__    :   List[str]      =       tf.constant([0.9_285, 0.9_015, -0.3_150])
         self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()						,   a						,   atol=1e-4))




import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
       from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
       from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Dict			):



     '''simple docstring'''





     return 1.0 / (1.0 + np.exp(-_outputs			))

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    str			):



     '''simple docstring'''





     lowercase__    :   int      =       np.max(_outputs	,     axis=-1	,     keepdims=SCREAMING_SNAKE_CASE_			)
     lowercase__    :   int      =       np.exp(_outputs - maxes			)
     return shifted_exp / shifted_exp.sum(axis=-1	,     keepdims=SCREAMING_SNAKE_CASE_			)


class       SCREAMING_SNAKE_CASE__					(__snake_case     ):
    __lowerCamelCase						:       Optional[int]														=     """sigmoid"""
    __lowerCamelCase						:       List[Any]														=     """softmax"""
    __lowerCamelCase						:       Optional[Any]														=     """none"""



@add_end_docstrings(
    __snake_case		,       r"""
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `\"default\"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `\"sigmoid\"`: Applies the sigmoid function on the output.
            - `\"softmax\"`: Applies the softmax function on the output.
            - `\"none\"`: Does not apply any function on the output.
    """		,       )
class       SCREAMING_SNAKE_CASE__					(__snake_case     ):
    __lowerCamelCase						:       Dict														=     False
    __lowerCamelCase						:       List[str]														=     ClassificationFunction.NONE





    def __init__(      self						,   **a):
         super().__init__(**a)

         self.check_model_type(
             TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
             if self.framework == 'tf'
             else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING)





    def       snake_case_				(      self						,   a=None						,   a=None						,   a=""						,   **a):
         # Using "" as default argument because we're going to use `top_k=None` in user code to declare
         # "No top_k"
         lowercase__    :   List[str]      =       tokenizer_kwargs

         lowercase__    :   Dict      =       {}
         if hasattr(self.model.config						,   'return_all_scores') and return_all_scores is None:
              lowercase__    :   Union[str, Any]      =       self.model.config.return_all_scores

         if isinstance(a						,   a) or top_k is None:
              lowercase__    :   Tuple      =       top_k
              lowercase__    :   Any      =       False
         elif return_all_scores is not None:
              warnings.warn(
                  '`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'
                  ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'						,   a						,   )
              if return_all_scores:
                   lowercase__    :   Union[str, Any]      =       None
              else:
                   lowercase__    :   Union[str, Any]      =       1

         if isinstance(a						,   a):
              lowercase__    :   Tuple      =       ClassificationFunction[function_to_apply.upper()]

         if function_to_apply is not None:
              lowercase__    :   List[str]      =       function_to_apply
         return preprocess_params, {}, postprocess_params





    def __call__(      self						,   *a						,   **a):
         lowercase__    :   int      =       super().__call__(*a						,   **a)
         # TODO try and retrieve it in a nicer way from _sanitize_parameters.
         lowercase__    :   Any      =       'top_k' not in kwargs
         if isinstance(args[0]						,   a) and _legacy:
              # This pipeline is odd, and return a list when single item is run
              return [result]
         else:
              return result





    def       snake_case_				(      self						,   a						,   **a):
         lowercase__    :   List[str]      =       self.framework
         if isinstance(a						,   a):
              return self.tokenizer(**a						,   return_tensors=a						,   **a)
         elif isinstance(a						,   a) and len(a) == 1 and isinstance(inputs[0]						,   a) and len(inputs[0]) == 2:
              # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
              return self.tokenizer(
                  text=inputs[0][0]						,   text_pair=inputs[0][1]						,   return_tensors=a						,   **a)
         elif isinstance(a						,   a):
              # This is likely an invalid usage of the pipeline attempting to pass text pairs.
              raise ValueError(
                  'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'
                  ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.')
         return self.tokenizer(a						,   return_tensors=a						,   **a)





    def       snake_case_				(      self						,   a):
         return self.model(**a)





    def       snake_case_				(      self						,   a						,   a=None						,   a=1						,   a=True):
         # `_legacy` is used to determine if we're running the naked pipeline and in backward
         # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
         # the more natural result containing the list.
         # Default value before `set_parameters`
         if function_to_apply is None:
              if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
                   lowercase__    :   Union[str, Any]      =       ClassificationFunction.SIGMOID
              elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
                   lowercase__    :   Union[str, Any]      =       ClassificationFunction.SOFTMAX
              elif hasattr(self.model.config						,   'function_to_apply') and function_to_apply is None:
                   lowercase__    :   List[str]      =       self.model.config.function_to_apply
              else:
                   lowercase__    :   Union[str, Any]      =       ClassificationFunction.NONE

         lowercase__    :   str      =       model_outputs['logits'][0]
         lowercase__    :   Dict      =       outputs.numpy()

         if function_to_apply == ClassificationFunction.SIGMOID:
              lowercase__    :   int      =       sigmoid(a)
         elif function_to_apply == ClassificationFunction.SOFTMAX:
              lowercase__    :   List[Any]      =       softmax(a)
         elif function_to_apply == ClassificationFunction.NONE:
              lowercase__    :   Any      =       outputs
         else:
              raise ValueError(f"""Unrecognized `function_to_apply` argument: {function_to_apply}""")

         if top_k == 1 and _legacy:
              return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

         lowercase__    :   Any      =       [
             {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(a)
         ]
         if not _legacy:
              dict_scores.sort(key=lambda a: x["score"]						,   reverse=a)
              if top_k is not None:
                   lowercase__    :   Optional[Any]      =       dict_scores[:top_k]
         return dict_scores

