





from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
    from PIL import Image

    from transformers import ConvNextImageProcessor

class 					snake_case					:




 """simple docstring"""



 def __init__(	self	:							Dict							,     __A	:							str							,     __A	:							Tuple=1_3							,     __A	:							List[str]=3_2							,     __A	:							Optional[int]=3							,     __A	:							Any=4							,     __A	:							Tuple=[1_0, 2_0, 3_0, 4_0]							,     __A	:							Optional[Any]=[2, 2, 3, 2]							,     __A	:							List[Any]=True							,     __A	:							int=True							,     __A	:							Dict=3_7							,     __A	:							Optional[int]="gelu"							,     __A	:							Dict=1_0							,     __A	:							List[Any]=0.02							,     __A	:							str=3							,     __A	:							str=None							,     ):
        __UpperCamelCase	=  parent
        __UpperCamelCase	=  batch_size
        __UpperCamelCase	=  image_size
        __UpperCamelCase	=  num_channels
        __UpperCamelCase	=  num_stages
        __UpperCamelCase	=  hidden_sizes
        __UpperCamelCase	=  depths
        __UpperCamelCase	=  is_training
        __UpperCamelCase	=  use_labels
        __UpperCamelCase	=  intermediate_size
        __UpperCamelCase	=  hidden_act
        __UpperCamelCase	=  type_sequence_label_size
        __UpperCamelCase	=  initializer_range
        __UpperCamelCase	=  scope






 def 	_lowerCamelCase (	self	:							Optional[Any]     ):
        __UpperCamelCase	=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

        __UpperCamelCase	=  self.get_config()

        return config, pixel_values, labels






 def 	_lowerCamelCase (	self	:							Union[str, Any]     ):
        return ConvNextConfig(
            num_channels=self.num_channels							,     hidden_sizes=self.hidden_sizes							,     depths=self.depths							,     num_stages=self.num_stages							,     hidden_act=self.hidden_act							,     is_decoder=__A							,     initializer_range=self.initializer_range							,     )






 def 	_lowerCamelCase (	self	:							Union[str, Any]							,     __A	:							int							,     __A	:							Dict							,     __A	:							List[Any]     ):
        __UpperCamelCase	=  TFConvNextModel(config=__A     )
        __UpperCamelCase	=  model(__A							,     training=__A     )
        # expected last hidden states: B, C, H // 32, W // 32
        self.parent.assertEqual(
            result.last_hidden_state.shape							,     (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)							,     )






 def 	_lowerCamelCase (	self	:							Union[str, Any]							,     __A	:							int							,     __A	:							str							,     __A	:							Tuple     ):
        __UpperCamelCase	=  self.type_sequence_label_size
        __UpperCamelCase	=  TFConvNextForImageClassification(__A     )
        __UpperCamelCase	=  model(__A							,     labels=__A							,     training=__A     )
        self.parent.assertEqual(result.logits.shape							,     (self.batch_size, self.type_sequence_label_size)     )






 def 	_lowerCamelCase (	self	:							Any     ):
        __UpperCamelCase	=  self.prepare_config_and_inputs()
        __UpperCamelCase	,						__UpperCamelCase	,						__UpperCamelCase	=  config_and_inputs
        __UpperCamelCase	=  {'pixel_values': pixel_values}
        return config, inputs_dict






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




 """simple docstring"""



 SCREAMING_SNAKE_CASE_     : Union[str, Any]      		=(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
 SCREAMING_SNAKE_CASE_     : List[str]      		=(
     {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
     if is_tf_available()
     else {}
 )

 SCREAMING_SNAKE_CASE_     : Optional[int]      		=False
 SCREAMING_SNAKE_CASE_     : Tuple      		=False
 SCREAMING_SNAKE_CASE_     : List[Any]      		=False
 SCREAMING_SNAKE_CASE_     : Optional[Any]      		=False
 SCREAMING_SNAKE_CASE_     : List[Any]      		=False






 def 	_lowerCamelCase (	self	:							Dict     ):
        __UpperCamelCase	=  TFConvNextModelTester(self     )
        __UpperCamelCase	=  ConfigTester(
            self							,     config_class=__A							,     has_text_modality=__A							,     hidden_size=3_7							,     )






 @unittest.skip(reason='ConvNext does not use inputs_embeds'     )
 def 	_lowerCamelCase (	self	:							str     ):
        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.'							,     )
 @slow
 def 	_lowerCamelCase (	self	:							Tuple     ):
        super().test_keras_fit()






 @unittest.skip(reason='ConvNext does not support input and output embeddings'     )
 def 	_lowerCamelCase (	self	:							Union[str, Any]     ):
        pass






 def 	_lowerCamelCase (	self	:							int     ):
        __UpperCamelCase	,						__UpperCamelCase	=  self.model_tester.prepare_config_and_inputs_for_common()

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

               __UpperCamelCase	=  ['pixel_values']
               self.assertListEqual(arg_names[:1]							,     __A     )






 def 	_lowerCamelCase (	self	:							List[str]     ):
        __UpperCamelCase	=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__A     )






 @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 	_lowerCamelCase (	self	:							str     ):
        super().test_dataset_conversion()






 def 	_lowerCamelCase (	self	:							Optional[Any]     ):
        def check_hidden_states_output(__A	:							Tuple							,     __A	:							Union[str, Any]							,     __A	:							str     ):
               __UpperCamelCase	=  model_class(__A     )

               __UpperCamelCase	=  model(**self._prepare_for_class(__A							,     __A     )     )
               __UpperCamelCase	=  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

               __UpperCamelCase	=  self.model_tester.num_stages
               self.assertEqual(len(__A     )							,     expected_num_stages + 1     )

               # ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
               self.assertListEqual(
                   list(hidden_states[0].shape[-2:]     )							,     [self.model_tester.image_size // 4, self.model_tester.image_size // 4]							,     )

        __UpperCamelCase	,						__UpperCamelCase	=  self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               __UpperCamelCase	=  True
               check_hidden_states_output(__A							,     __A							,     __A     )

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               __UpperCamelCase	=  True

               check_hidden_states_output(__A							,     __A							,     __A     )






 def 	_lowerCamelCase (	self	:							List[Any]     ):
        __UpperCamelCase	,						__UpperCamelCase	=  self.model_tester.prepare_config_and_inputs_for_common()

        def check_equivalence(__A	:							str							,     __A	:							Union[str, Any]							,     __A	:							int							,     __A	:							Tuple={}     ):
               __UpperCamelCase	=  model(__A							,     return_dict=__A							,     **__A     )
               __UpperCamelCase	=  model(__A							,     return_dict=__A							,     **__A     ).to_tuple()

               def recursive_check(__A	:							List[str]							,     __A	:							Optional[int]     ):
                      if isinstance(__A							,     (List, Tuple)     ):
                             for tuple_iterable_value, dict_iterable_value in zip(__A							,     __A     ):
                                    recursive_check(__A							,     __A     )
                      elif tuple_object is None:
                             return
                      else:
                             self.assertTrue(
                                 all(tf.equal(__A							,     __A     )     )							,     msg=(
                                     'Tuple and dict output are not equal. Difference:'
                                     f''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object     )     )}'''
                                 )							,     )

                      recursive_check(__A							,     __A     )

        for model_class in self.all_model_classes:
               __UpperCamelCase	=  model_class(__A     )

               __UpperCamelCase	=  self._prepare_for_class(__A							,     __A     )
               __UpperCamelCase	=  self._prepare_for_class(__A							,     __A     )
               check_equivalence(__A							,     __A							,     __A     )

               __UpperCamelCase	=  self._prepare_for_class(__A							,     __A							,     return_labels=__A     )
               __UpperCamelCase	=  self._prepare_for_class(__A							,     __A							,     return_labels=__A     )
               check_equivalence(__A							,     __A							,     __A     )

               __UpperCamelCase	=  self._prepare_for_class(__A							,     __A     )
               __UpperCamelCase	=  self._prepare_for_class(__A							,     __A     )
               check_equivalence(__A							,     __A							,     __A							,     {'output_hidden_states': True}     )

               __UpperCamelCase	=  self._prepare_for_class(__A							,     __A							,     return_labels=__A     )
               __UpperCamelCase	=  self._prepare_for_class(__A							,     __A							,     return_labels=__A     )
               check_equivalence(__A							,     __A							,     __A							,     {'output_hidden_states': True}     )






 def 	_lowerCamelCase (	self	:							List[Any]     ):
        __UpperCamelCase	=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__A     )






 @slow
 def 	_lowerCamelCase (	self	:							Tuple     ):
        __UpperCamelCase	=  TFConvNextModel.from_pretrained('facebook/convnext-tiny-224'     )
        self.assertIsNotNone(__A     )






def     lowercase__       (       )			->				int:



       """simple docstring"""






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


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




 """simple docstring"""



 @cached_property
 def 	_lowerCamelCase (	self	:							Dict     ):
        return ConvNextImageProcessor.from_pretrained('facebook/convnext-tiny-224'     ) if is_vision_available() else None






 @slow
 def 	_lowerCamelCase (	self	:							str     ):
        __UpperCamelCase	=  TFConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'     )

        __UpperCamelCase	=  self.default_image_processor
        __UpperCamelCase	=  prepare_img()
        __UpperCamelCase	=  image_processor(images=__A							,     return_tensors='tf'     )

        # forward pass
        __UpperCamelCase	=  model(**__A     )

        # verify the logits
        __UpperCamelCase	=  tf.TensorShape((1, 1_0_0_0)     )
        self.assertEqual(outputs.logits.shape							,     __A     )

        __UpperCamelCase	=  tf.constant([-0.0260, -0.4739, 0.1911]     )

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







'''simple docstring'''
def     lowercase__       (       __lowercase						:  list    ,  __lowercase						:  int    ,  __lowercase						:  int    ,  __lowercase						:  int					)			->				int:



       """simple docstring"""






       __UpperCamelCase	=  int((lower_bound + upper_bound) // 2					)
       if array[r] == value:
              return r
       if lower_bound >= upper_bound:
              return -1
       if array[r] < value:
              return binary_search(__lowercase    ,  r + 1    ,  __lowercase    ,  __lowercase					)
       else:
              return binary_search(__lowercase    ,  __lowercase    ,  r - 1    ,  __lowercase					)
def     lowercase__       (       __lowercase						:  int    ,  __lowercase						:  list					)			->				list:



       """simple docstring"""






       __UpperCamelCase	=  0
       if matrix[index][0] == value:
              return [index, 0]
       while index < len(__lowercase					) and matrix[index][0] < value:
              __UpperCamelCase	=  binary_search(matrix[index]    ,  0    ,  len(matrix[index]					) - 1    ,  __lowercase					)
              if r != -1:
                     return [index, r]
              index += 1
       return [-1, -1]


if __name__ == "__main__":
    import doctest

    doctest.testmod()
