






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






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


       """simple docstring"""






       lowerCamelCase_							:    List[Any]							=     parent
       lowerCamelCase_							:    List[str]							=     batch_size
       lowerCamelCase_							:    List[str]							=     image_size
       lowerCamelCase_							:    Optional[int]							=     num_channels
       lowerCamelCase_							:    Optional[Any]							=     num_stages
       lowerCamelCase_							:    Optional[Any]							=     hidden_sizes
       lowerCamelCase_							:    int							=     depths
       lowerCamelCase_							:    Union[str, Any]							=     is_training
       lowerCamelCase_							:    List[str]							=     use_labels
       lowerCamelCase_							:    Optional[int]							=     intermediate_size
       lowerCamelCase_							:    Tuple							=     hidden_act
       lowerCamelCase_							:    List[str]							=     type_sequence_label_size
       lowerCamelCase_							:    List[str]							=     initializer_range
       lowerCamelCase_							:    Tuple							=     scope






      def      UpperCAmelCase_     (self					:    str		)       ->   Tuple:


       """simple docstring"""






       lowerCamelCase_							:    str							=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

       lowerCamelCase_							:    Dict							=     None
       if self.use_labels:
        lowerCamelCase_							:    List[Any]							=     ids_tensor([self.batch_size]		,		self.type_sequence_label_size		)

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

       return config, pixel_values, labels






      def      UpperCAmelCase_     (self					:    Dict		)       ->   Optional[int]:


       """simple docstring"""






       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=_snake_case		,		initializer_range=self.initializer_range		,		)






      def      UpperCAmelCase_     (self					:    int		,		_snake_case					:    Dict		,		_snake_case					:    Dict		,		_snake_case					:    int		)       ->   Tuple:


       """simple docstring"""






       lowerCamelCase_							:    Optional[int]							=     TFConvNextModel(config=_snake_case		)
       lowerCamelCase_							:    int							=     model(_snake_case		,		training=_snake_case		)
       # 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 // 32, self.image_size // 32)		,		)






      def      UpperCAmelCase_     (self					:    Dict		,		_snake_case					:    str		,		_snake_case					:    Optional[int]		,		_snake_case					:    List[Any]		)       ->   Dict:


       """simple docstring"""






       lowerCamelCase_							:    Optional[int]							=     self.type_sequence_label_size
       lowerCamelCase_							:    Optional[Any]							=     TFConvNextForImageClassification(_snake_case		)
       lowerCamelCase_							:    List[Any]							=     model(_snake_case		,		labels=_snake_case		,		training=_snake_case		)
       self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.type_sequence_label_size)		)






      def      UpperCAmelCase_     (self					:    List[str]		)       ->   Tuple:


       """simple docstring"""






       lowerCamelCase_							:    List[Any]							=     self.prepare_config_and_inputs()
       lowerCamelCase_		,      lowerCamelCase_		,      lowerCamelCase_							:    Optional[Any]							=     config_and_inputs
       lowerCamelCase_							:    str							=     {'pixel_values': pixel_values}
       return config, inputs_dict




@require_tf
class 	lowerCamelCase__				(							UpperCAmelCase,   UpperCAmelCase,   unittest.TestCase ):
      lowerCamelCase_							:   Optional[int]											=	(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
      lowerCamelCase_							:   List[Any]											=	(
          {'feature-extraction': TFConvNextModel, 'image-classification': TFConvNextForImageClassification}
          if is_tf_available()
          else {}
      )

      lowerCamelCase_							:   str											=	False
      lowerCamelCase_							:   str											=	False
      lowerCamelCase_							:   int											=	False
      lowerCamelCase_							:   str											=	False
      lowerCamelCase_							:   Any											=	False






      def      UpperCAmelCase_     (self					:    Tuple		)       ->   Any:


       """simple docstring"""






       lowerCamelCase_							:    Any							=     TFConvNextModelTester(self		)
       lowerCamelCase_							:    List[str]							=     ConfigTester(
           self		,		config_class=_snake_case		,		has_text_modality=_snake_case		,		hidden_size=37		,		)






      @unittest.skip(reason='ConvNext does not use inputs_embeds'		)
      def      UpperCAmelCase_     (self					:    int		)       ->   List[str]:


       """simple docstring"""






       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      UpperCAmelCase_     (self					:    Any		)       ->   Dict:


       """simple docstring"""






       super().test_keras_fit()






      @unittest.skip(reason='ConvNext does not support input and output embeddings'		)
      def      UpperCAmelCase_     (self					:    List[str]		)       ->   List[Any]:


       """simple docstring"""






       pass






      def      UpperCAmelCase_     (self					:    Tuple		)       ->   Optional[int]:


       """simple docstring"""






       lowerCamelCase_		,      lowerCamelCase_							:    Optional[int]							=     self.model_tester.prepare_config_and_inputs_for_common()

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

        lowerCamelCase_							:    Optional[Any]							=     ['pixel_values']
        self.assertListEqual(arg_names[:1]		,		_snake_case		)






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


       """simple docstring"""






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






      @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      UpperCAmelCase_     (self					:    List[str]		)       ->   Dict:


       """simple docstring"""






       super().test_dataset_conversion()






      def      UpperCAmelCase_     (self					:    Any		)       ->   str:


       """simple docstring"""






       def check_hidden_states_output(_snake_case					:    Optional[int]		,		_snake_case					:    Dict		,		_snake_case					:    Any		):
        lowerCamelCase_							:    Union[str, Any]							=     model_class(_snake_case		)

        lowerCamelCase_							:    Tuple							=     model(**self._prepare_for_class(_snake_case		,		_snake_case		)		)
        lowerCamelCase_							:    List[str]							=     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        lowerCamelCase_							:    int							=     self.model_tester.num_stages
        self.assertEqual(len(_snake_case		)		,		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]		,		)

       lowerCamelCase_		,      lowerCamelCase_							:    Any							=     self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        lowerCamelCase_							:    int							=     True
        check_hidden_states_output(_snake_case		,		_snake_case		,		_snake_case		)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        lowerCamelCase_							:    List[str]							=     True

        check_hidden_states_output(_snake_case		,		_snake_case		,		_snake_case		)






      def      UpperCAmelCase_     (self					:    Optional[int]		)       ->   List[Any]:


       """simple docstring"""






       lowerCamelCase_		,      lowerCamelCase_							:    List[Any]							=     self.model_tester.prepare_config_and_inputs_for_common()

       def check_equivalence(_snake_case					:    Tuple		,		_snake_case					:    List[Any]		,		_snake_case					:    Optional[int]		,		_snake_case					:    Tuple={}		):
        lowerCamelCase_							:    Tuple							=     model(_snake_case		,		return_dict=_snake_case		,		**_snake_case		)
        lowerCamelCase_							:    Any							=     model(_snake_case		,		return_dict=_snake_case		,		**_snake_case		).to_tuple()

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

         recursive_check(_snake_case		,		_snake_case		)

       for model_class in self.all_model_classes:
        lowerCamelCase_							:    Optional[int]							=     model_class(_snake_case		)

        lowerCamelCase_							:    str							=     self._prepare_for_class(_snake_case		,		_snake_case		)
        lowerCamelCase_							:    List[Any]							=     self._prepare_for_class(_snake_case		,		_snake_case		)
        check_equivalence(_snake_case		,		_snake_case		,		_snake_case		)

        lowerCamelCase_							:    str							=     self._prepare_for_class(_snake_case		,		_snake_case		,		return_labels=_snake_case		)
        lowerCamelCase_							:    Dict							=     self._prepare_for_class(_snake_case		,		_snake_case		,		return_labels=_snake_case		)
        check_equivalence(_snake_case		,		_snake_case		,		_snake_case		)

        lowerCamelCase_							:    Any							=     self._prepare_for_class(_snake_case		,		_snake_case		)
        lowerCamelCase_							:    Optional[int]							=     self._prepare_for_class(_snake_case		,		_snake_case		)
        check_equivalence(_snake_case		,		_snake_case		,		_snake_case		,		{'output_hidden_states': True}		)

        lowerCamelCase_							:    Tuple							=     self._prepare_for_class(_snake_case		,		_snake_case		,		return_labels=_snake_case		)
        lowerCamelCase_							:    Union[str, Any]							=     self._prepare_for_class(_snake_case		,		_snake_case		,		return_labels=_snake_case		)
        check_equivalence(_snake_case		,		_snake_case		,		_snake_case		,		{'output_hidden_states': True}		)






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


       """simple docstring"""






       lowerCamelCase_							:    Optional[Any]							=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_snake_case		)






      @slow
      def      UpperCAmelCase_     (self					:    List[Any]		)       ->   List[str]:


       """simple docstring"""






       lowerCamelCase_							:    int							=     TFConvNextModel.from_pretrained('facebook/convnext-tiny-224'		)
       self.assertIsNotNone(_snake_case		)




def       _a   (							)  ->      Union[str, Any]:
 lowerCamelCase_							:    Optional[int]							=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
 return image





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






      @cached_property
      def      UpperCAmelCase_     (self					:    List[str]		)       ->   Dict:


       """simple docstring"""






       return ConvNextImageProcessor.from_pretrained('facebook/convnext-tiny-224'		) if is_vision_available() else None






      @slow
      def      UpperCAmelCase_     (self					:    Tuple		)       ->   List[str]:


       """simple docstring"""






       lowerCamelCase_							:    int							=     TFConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'		)

       lowerCamelCase_							:    List[str]							=     self.default_image_processor
       lowerCamelCase_							:    Any							=     prepare_img()
       lowerCamelCase_							:    Any							=     image_processor(images=_snake_case		,		return_tensors='tf'		)

       # forward pass
       lowerCamelCase_							:    List[Any]							=     model(**_snake_case		)

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

       lowerCamelCase_							:    Optional[Any]							=     tf.constant([-0.0260, -0.4739, 0.1911]		)

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








UpperCamelCase											=      [
    [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
    [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0],
    [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
]




def       _a   (							lowerCamelCase__ ,			lowerCamelCase__ ,			lowerCamelCase__ ,			lowerCamelCase__				)  ->      bool:
 return 0 <= row < rows and 0 <= col < cols




def       _a   (							lowerCamelCase__ ,			lowerCamelCase__ ,			lowerCamelCase__ ,			lowerCamelCase__				)  ->      int:
 lowerCamelCase_							:    Tuple							=     len(lowerCamelCase__				)
 lowerCamelCase_							:    Tuple							=     len(mat[0]				)
 if is_safe(lowerCamelCase__ ,			lowerCamelCase__ ,			lowerCamelCase__ ,			lowerCamelCase__				) and (row, col) not in seen and mat[row][col] == 1:
  seen.add((row, col)				)
  return (
      1
      + depth_first_search(row + 1 ,			lowerCamelCase__ ,			lowerCamelCase__ ,			lowerCamelCase__				)
      + depth_first_search(row - 1 ,			lowerCamelCase__ ,			lowerCamelCase__ ,			lowerCamelCase__				)
      + depth_first_search(lowerCamelCase__ ,			col + 1 ,			lowerCamelCase__ ,			lowerCamelCase__				)
      + depth_first_search(lowerCamelCase__ ,			col - 1 ,			lowerCamelCase__ ,			lowerCamelCase__				)
  )
 else:
  return 0




def       _a   (							lowerCamelCase__				)  ->      int:
 lowerCamelCase_							:    set							=     set()

 lowerCamelCase_							:    int							=     0
 for row, line in enumerate(lowerCamelCase__				):
  for col, item in enumerate(lowerCamelCase__				):
   if item == 1 and (row, col) not in seen:
    # Maximizing the area
    lowerCamelCase_							:    str							=     max(lowerCamelCase__ ,			depth_first_search(lowerCamelCase__ ,			lowerCamelCase__ ,			lowerCamelCase__ ,			lowerCamelCase__				)				)
 return max_area


if __name__ == "__main__":
       import doctest

       print(find_max_area(matrix))  # Output -> 6
       doctest.testmod()
