

'''simple docstring'''







from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
      from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor


class 					A__      :



    def __init__(					self		,				UpperCamelCase__		,				UpperCamelCase__=3		,				UpperCamelCase__=32		,				UpperCamelCase__=3		,				UpperCamelCase__=10		,				UpperCamelCase__=[10, 20, 30, 40]		,				UpperCamelCase__=[1, 1, 2, 1]		,				UpperCamelCase__=True		,				UpperCamelCase__=True		,				UpperCamelCase__="relu"		,				UpperCamelCase__=3		,				UpperCamelCase__=None		,				)						->      Union[str, Any]:





           '''simple docstring'''
           A_						=      parent
           A_						=      batch_size
           A_						=      image_size
           A_						=      num_channels
           A_						=      embeddings_size
           A_						=      hidden_sizes
           A_						=      depths
           A_						=      is_training
           A_						=      use_labels
           A_						=      hidden_act
           A_						=      num_labels
           A_						=      scope
           A_						=      len(UpperCamelCase__       )



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





           '''simple docstring'''
           A_						=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

           A_						=      None
           if self.use_labels:
                  A_						=      ids_tensor([self.batch_size]		,				self.num_labels       )

           A_						=      self.get_config()

           return config, pixel_values, labels



    def 					snake_case_			(					self       )						->      int:





           '''simple docstring'''
           return ResNetConfig(
               num_channels=self.num_channels		,				embeddings_size=self.embeddings_size		,				hidden_sizes=self.hidden_sizes		,				depths=self.depths		,				hidden_act=self.hidden_act		,				num_labels=self.num_labels		,				image_size=self.image_size		,				)



    def 					snake_case_			(					self		,				UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__       )						->      int:





           '''simple docstring'''
           A_						=      TFResNetModel(config=UpperCamelCase__       )
           A_						=      model(UpperCamelCase__       )
           # 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 					snake_case_			(					self		,				UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__       )						->      Union[str, Any]:





           '''simple docstring'''
           A_						=      self.num_labels
           A_						=      TFResNetForImageClassification(UpperCamelCase__       )
           A_						=      model(UpperCamelCase__		,				labels=UpperCamelCase__       )
           self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_labels)       )







    def 					snake_case_			(					self       )						->      Tuple:





           '''simple docstring'''
           A_						=      self.prepare_config_and_inputs()
           A_					,			A_					,			A_						=      config_and_inputs
           A_						=      {"""pixel_values""": pixel_values}
           return config, inputs_dict


@require_tf
class 					A__      (      _snake_case						,						_snake_case						,						unittest.TestCase			):
    lowercase						=		(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
    lowercase						=		(
        {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
        if is_tf_available()
        else {}
    )

    lowercase						=		False
    lowercase						=		False
    lowercase						=		False
    lowercase						=		False
    lowercase						=		False



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





           '''simple docstring'''
           A_						=      TFResNetModelTester(self       )
           A_						=      ConfigTester(self		,				config_class=UpperCamelCase__		,				has_text_modality=UpperCamelCase__       )



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





           '''simple docstring'''
           self.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()



    def 					snake_case_			(					self       )						->      Any:





           '''simple docstring'''
           return



    @unittest.skip(reason="""ResNet does not use inputs_embeds"""       )
    def 					snake_case_			(					self       )						->      int:





           '''simple docstring'''
           pass



    @unittest.skip(reason="""ResNet does not support input and output embeddings"""       )
    def 					snake_case_			(					self       )						->      List[Any]:





           '''simple docstring'''
           pass



    def 					snake_case_			(					self       )						->      Any:





           '''simple docstring'''
           A_					,			A_						=      self.model_tester.prepare_config_and_inputs_for_common()

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

                  A_						=      ["""pixel_values"""]
                  self.assertListEqual(arg_names[:1]		,				UpperCamelCase__       )



    def 					snake_case_			(					self       )						->      str:





           '''simple docstring'''
           A_						=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCamelCase__       )



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





           '''simple docstring'''
           def check_hidden_states_output(UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__       ):
                  A_						=      model_class(UpperCamelCase__       )
                  A_						=      model(**self._prepare_for_class(UpperCamelCase__		,				UpperCamelCase__       )       )

                  A_						=      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                  A_						=      self.model_tester.num_stages
                  self.assertEqual(len(UpperCamelCase__       )		,				expected_num_stages + 1       )

                  # ResNet'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]		,				)

           A_					,			A_						=      self.model_tester.prepare_config_and_inputs_for_common()
           A_						=      ["""basic""", """bottleneck"""]
           for model_class in self.all_model_classes:
                  for layer_type in layers_type:
                         A_						=      layer_type
                         A_						=      True
                         check_hidden_states_output(UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__       )

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

                         check_hidden_states_output(UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__       )



    def 					snake_case_			(					self       )						->      Any:





           '''simple docstring'''
           A_						=      self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__       )







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





           '''simple docstring'''
           for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  A_						=      TFResNetModel.from_pretrained(UpperCamelCase__       )
                  self.assertIsNotNone(UpperCamelCase__       )

def       UpperCAmelCase__    (      )			->			str:
       A_						=      Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""				)
       return image







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



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





           '''simple docstring'''
           return (
               AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )
               if is_vision_available()
               else None
           )







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





           '''simple docstring'''
           A_						=      TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

           A_						=      self.default_image_processor
           A_						=      prepare_img()
           A_						=      image_processor(images=UpperCamelCase__		,				return_tensors="""tf"""       )

           # forward pass
           A_						=      model(**UpperCamelCase__       )

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

           A_						=      tf.constant([-11.1069, -9.7877, -8.3777]       )

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



'''simple docstring'''







import numpy as np
from cva import COLOR_BGR2GRAY, cvtColor, imread
from numpy import array, uinta
from PIL import Image

from digital_image_processing import change_contrast as cc
from digital_image_processing import convert_to_negative as cn
from digital_image_processing import sepia as sp
from digital_image_processing.dithering import burkes as bs
from digital_image_processing.edge_detection import canny
from digital_image_processing.filters import convolve as conv
from digital_image_processing.filters import gaussian_filter as gg
from digital_image_processing.filters import local_binary_pattern as lbp
from digital_image_processing.filters import median_filter as med
from digital_image_processing.filters import sobel_filter as sob
from digital_image_processing.resize import resize as rs

__lowerCamelCase		       =    imread(r'''digital_image_processing/image_data/lena_small.jpg''')
__lowerCamelCase		       =    cvtColor(img, COLOR_BGR2GRAY)
def       UpperCAmelCase__    (      )			->			Dict:
       A_						=      cn.convert_to_negative(UpperCAmelCase__				)
       # assert negative_img array for at least one True
       assert negative_img.any()
def       UpperCAmelCase__    (      )			->			List[Any]:
       with Image.open("""digital_image_processing/image_data/lena_small.jpg"""				) as img:
              # Work around assertion for response
              assert str(cc.change_contrast(UpperCAmelCase__,       1_10				)				).startswith(
                  """<PIL.Image.Image image mode=RGB size=100x100 at"""				)
def       UpperCAmelCase__    (      )			->			str:
       A_						=      canny.gen_gaussian_kernel(9,       sigma=1.4				)
       # Assert ambiguous array
       assert resp.all()
def       UpperCAmelCase__    (      )			->			Union[str, Any]:
       A_						=      imread("""digital_image_processing/image_data/lena_small.jpg""",       0				)
       # assert ambiguous array for all == True
       assert canny_img.all()
       A_						=      canny.canny(UpperCAmelCase__				)
       # assert canny array for at least one True
       assert canny_array.any()
def       UpperCAmelCase__    (      )			->			Dict:
       assert gg.gaussian_filter(UpperCAmelCase__,       5,       sigma=0.9				).all()
def       UpperCAmelCase__    (      )			->			int:
       # laplace diagonals
       A_						=      array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]]				)
       A_						=      conv.img_convolve(UpperCAmelCase__,       UpperCAmelCase__				).astype(UpperCAmelCase__				)
       assert res.any()
def       UpperCAmelCase__    (      )			->			List[Any]:
       assert med.median_filter(UpperCAmelCase__,       3				).any()
def       UpperCAmelCase__    (      )			->			List[Any]:
       A_					,			A_						=      sob.sobel_filter(UpperCAmelCase__				)
       assert grad.any() and theta.any()
def       UpperCAmelCase__    (      )			->			List[str]:
       A_						=      sp.make_sepia(UpperCAmelCase__,       20				)
       assert sepia.all()
def       UpperCAmelCase__    (      UpperCAmelCase__ = "digital_image_processing/image_data/lena_small.jpg"				)			->			List[Any]:
       A_						=      bs.Burkes(imread(UpperCAmelCase__,       1				),       1_20				)
       burkes.process()
       assert burkes.output_img.any()
def       UpperCAmelCase__    (      UpperCAmelCase__ = "digital_image_processing/image_data/lena_small.jpg",       )			->			Optional[int]:
       A_						=      rs.NearestNeighbour(imread(UpperCAmelCase__,       1				),       4_00,       2_00				)
       nn.process()
       assert nn.output.any()







def       UpperCAmelCase__    (      )			->			Optional[int]:
       A_						=      """digital_image_processing/image_data/lena.jpg"""

       # Reading the image and converting it to grayscale.
       A_						=      imread(UpperCAmelCase__,       0				)

       # Test for get_neighbors_pixel function() return not None
       A_						=      0
       A_						=      0
       A_						=      image[x_coordinate][y_coordinate]

       A_						=      lbp.get_neighbors_pixel(
           UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__				)

       assert neighbors_pixels is not None

       # Test for local_binary_pattern function()
       # Create a numpy array as the same height and width of read image
       A_						=      np.zeros((image.shape[0], image.shape[1])				)

       # Iterating through the image and calculating the local binary pattern value
       # for each pixel.
       for i in range(0,       image.shape[0]				):
              for j in range(0,       image.shape[1]				):
                     A_						=      lbp.local_binary_value(UpperCAmelCase__,       UpperCAmelCase__,       UpperCAmelCase__				)

       assert lbp_image.any()
