


'''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    UpperCAmelCase_  :





    """simple docstring"""






    def __init__(							self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_=3			,     SCREAMING_SNAKE_CASE_=32			,     SCREAMING_SNAKE_CASE_=3			,     SCREAMING_SNAKE_CASE_=10			,     SCREAMING_SNAKE_CASE_=[10, 20, 30, 40]			,     SCREAMING_SNAKE_CASE_=[1, 1, 2, 1]			,     SCREAMING_SNAKE_CASE_=True			,     SCREAMING_SNAKE_CASE_=True			,     SCREAMING_SNAKE_CASE_="relu"			,     SCREAMING_SNAKE_CASE_=3			,     SCREAMING_SNAKE_CASE_=None			,     )				->     Any:
         __lowerCamelCase   :	List[Any]								=		parent
         __lowerCamelCase   :	Optional[int]								=		batch_size
         __lowerCamelCase   :	int								=		image_size
         __lowerCamelCase   :	List[Any]								=		num_channels
         __lowerCamelCase   :	Union[str, Any]								=		embeddings_size
         __lowerCamelCase   :	Optional[int]								=		hidden_sizes
         __lowerCamelCase   :	Tuple								=		depths
         __lowerCamelCase   :	Dict								=		is_training
         __lowerCamelCase   :	str								=		use_labels
         __lowerCamelCase   :	Union[str, Any]								=		hidden_act
         __lowerCamelCase   :	Any								=		num_labels
         __lowerCamelCase   :	Optional[int]								=		scope
         __lowerCamelCase   :	Union[str, Any]								=		len(SCREAMING_SNAKE_CASE_	)







    def       lowercase_				(							self	)				->     Optional[int]:
         __lowerCamelCase   :	Any								=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

         __lowerCamelCase   :	List[str]								=		None
         if self.use_labels:
              __lowerCamelCase   :	Any								=		ids_tensor([self.batch_size]			,     self.num_labels	)

         __lowerCamelCase   :	Optional[int]								=		self.get_config()

         return config, pixel_values, labels







    def       lowercase_				(							self	)				->     List[str]:
         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       lowercase_				(							self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)				->     Optional[int]:
         __lowerCamelCase   :	Tuple								=		TFResNetModel(config=SCREAMING_SNAKE_CASE_	)
         __lowerCamelCase   :	Tuple								=		model(SCREAMING_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       lowercase_				(							self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)				->     int:
         __lowerCamelCase   :	Any								=		self.num_labels
         __lowerCamelCase   :	str								=		TFResNetForImageClassification(SCREAMING_SNAKE_CASE_	)
         __lowerCamelCase   :	int								=		model(SCREAMING_SNAKE_CASE_			,     labels=SCREAMING_SNAKE_CASE_	)
         self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.num_labels)	)







    def       lowercase_				(							self	)				->     Tuple:
         __lowerCamelCase   :	Dict								=		self.prepare_config_and_inputs()
         __lowerCamelCase				,       __lowerCamelCase				,       __lowerCamelCase   :	Tuple								=		config_and_inputs
         __lowerCamelCase   :	List[str]								=		{'pixel_values': pixel_values}
         return config, inputs_dict







@require_tf
class    UpperCAmelCase_  (_UpperCAmelCase					,		_UpperCAmelCase					,		unittest.TestCase  ):





    """simple docstring"""






    lowerCamelCase  :					Dict							     =			(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
    lowerCamelCase  :					List[Any]							     =			(
        {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
        if is_tf_available()
        else {}
    )

    lowerCamelCase  :					Optional[int]							     =			False
    lowerCamelCase  :					Tuple							     =			False
    lowerCamelCase  :					str							     =			False
    lowerCamelCase  :					Optional[int]							     =			False
    lowerCamelCase  :					Union[str, Any]							     =			False







    def       lowercase_				(							self	)				->     str:
         __lowerCamelCase   :	int								=		TFResNetModelTester(self	)
         __lowerCamelCase   :	List[Any]								=		ConfigTester(self			,     config_class=SCREAMING_SNAKE_CASE_			,     has_text_modality=SCREAMING_SNAKE_CASE_	)







    def       lowercase_				(							self	)				->     Dict:
         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       lowercase_				(							self	)				->     List[str]:
         return







    @unittest.skip(reason='ResNet does not use inputs_embeds'	)
    def       lowercase_				(							self	)				->     List[Any]:
         pass







    @unittest.skip(reason='ResNet does not support input and output embeddings'	)
    def       lowercase_				(							self	)				->     Any:
         pass







    def       lowercase_				(							self	)				->     Optional[int]:
         __lowerCamelCase				,       __lowerCamelCase   :	List[str]								=		self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              __lowerCamelCase   :	Optional[int]								=		model_class(SCREAMING_SNAKE_CASE_	)
              __lowerCamelCase   :	Dict								=		inspect.signature(model.call	)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              __lowerCamelCase   :	Tuple								=		[*signature.parameters.keys()]

              __lowerCamelCase   :	List[str]								=		['pixel_values']
              self.assertListEqual(arg_names[:1]			,     SCREAMING_SNAKE_CASE_	)







    def       lowercase_				(							self	)				->     Dict:
         __lowerCamelCase   :	int								=		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_	)







    def       lowercase_				(							self	)				->     List[Any]:
         def check_hidden_states_output(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	):
              __lowerCamelCase   :	List[str]								=		model_class(SCREAMING_SNAKE_CASE_	)
              __lowerCamelCase   :	Tuple								=		model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)	)

              __lowerCamelCase   :	Optional[Any]								=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              __lowerCamelCase   :	Union[str, Any]								=		self.model_tester.num_stages
              self.assertEqual(len(SCREAMING_SNAKE_CASE_	)			,     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]			,     )

         __lowerCamelCase				,       __lowerCamelCase   :	Optional[Any]								=		self.model_tester.prepare_config_and_inputs_for_common()
         __lowerCamelCase   :	int								=		['basic', 'bottleneck']
         for model_class in self.all_model_classes:
              for layer_type in layers_type:
                   __lowerCamelCase   :	List[Any]								=		layer_type
                   __lowerCamelCase   :	List[Any]								=		True
                   check_hidden_states_output(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)

                   # check that output_hidden_states also work using config
                   del inputs_dict["output_hidden_states"]
                   __lowerCamelCase   :	Tuple								=		True

                   check_hidden_states_output(SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_	)







    def       lowercase_				(							self	)				->     Tuple:
         __lowerCamelCase   :	List[str]								=		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_	)







    @slow
    def       lowercase_				(							self	)				->     List[Any]:
         for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __lowerCamelCase   :	Optional[Any]								=		TFResNetModel.from_pretrained(SCREAMING_SNAKE_CASE_	)
              self.assertIsNotNone(SCREAMING_SNAKE_CASE_	)







def 			UpperCAmelCase__					(	)     ->		str:
     __lowerCamelCase   :	List[str]								=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
     return image





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





    """simple docstring"""






    @cached_property
    def       lowercase_				(							self	)				->     List[str]:
         return (
             AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)
             if is_vision_available()
             else None
         )







    @slow
    def       lowercase_				(							self	)				->     List[Any]:
         __lowerCamelCase   :	Dict								=		TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)

         __lowerCamelCase   :	List[Any]								=		self.default_image_processor
         __lowerCamelCase   :	List[str]								=		prepare_img()
         __lowerCamelCase   :	Tuple								=		image_processor(images=SCREAMING_SNAKE_CASE_			,     return_tensors='tf'	)

         # forward pass
         __lowerCamelCase   :	Dict								=		model(**SCREAMING_SNAKE_CASE_	)

         # verify the logits
         __lowerCamelCase   :	int								=		tf.TensorShape((1, 10_00)	)
         self.assertEqual(outputs.logits.shape			,     SCREAMING_SNAKE_CASE_	)

         __lowerCamelCase   :	Any								=		tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]	)

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










'''simple docstring'''



A__		:					Optional[int]												=  """ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"""



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				bytes							)     ->		bytes:
     # Make sure the supplied data is a bytes-like object
     if not isinstance(UpperCAmelCase_      ,    UpperCAmelCase_							):
          __lowerCamelCase   :	Dict								=		F'a bytes-like object is required, not \'{data.__class__.__name__}\''
          raise TypeError(UpperCAmelCase_							)

     __lowerCamelCase   :	Optional[int]								=		''.join(bin(UpperCAmelCase_							)[2:].zfill(8							) for byte in data							)

     __lowerCamelCase   :	Any								=		len(UpperCAmelCase_							) % 6 != 0

     if padding_needed:
          # The padding that will be added later
          __lowerCamelCase   :	int								=		B'=' * ((6 - len(UpperCAmelCase_							) % 6) // 2)

          # Append binary_stream with arbitrary binary digits (0's by default) to make its
          # length a multiple of 6.
          binary_stream += "0" * (6 - len(UpperCAmelCase_							) % 6)
     else:
          __lowerCamelCase   :	str								=		B''

     # Encode every 6 binary digits to their corresponding Base64 character
     return (
         "".join(
             B64_CHARSET[int(binary_stream[index : index + 6]      ,    2							)]
             for index in range(0      ,    len(UpperCAmelCase_							)      ,    6							)							).encode()
         + padding
     )



def 			UpperCAmelCase__					(	UpperCAmelCase_    :				str							)     ->		bytes:
     # Make sure encoded_data is either a string or a bytes-like object
     if not isinstance(UpperCAmelCase_      ,    UpperCAmelCase_							) and not isinstance(UpperCAmelCase_      ,    UpperCAmelCase_							):
          __lowerCamelCase   :	Dict								=		(
              'argument should be a bytes-like object or ASCII string, '
              F'not \'{encoded_data.__class__.__name__}\''
          )
          raise TypeError(UpperCAmelCase_							)

     # In case encoded_data is a bytes-like object, make sure it contains only
     # ASCII characters so we convert it to a string object
     if isinstance(UpperCAmelCase_      ,    UpperCAmelCase_							):
          try:
               __lowerCamelCase   :	int								=		encoded_data.decode('utf-8'							)
          except UnicodeDecodeError:
               raise ValueError('base64 encoded data should only contain ASCII characters'							)

     __lowerCamelCase   :	Union[str, Any]								=		encoded_data.count('='							)

     # Check if the encoded string contains non base64 characters
     if padding:
          assert all(
              char in B64_CHARSET for char in encoded_data[:-padding]							), "Invalid base64 character(s) found."
     else:
          assert all(
              char in B64_CHARSET for char in encoded_data							), "Invalid base64 character(s) found."

     # Check the padding
     assert len(UpperCAmelCase_							) % 4 == 0 and padding < 3, "Incorrect padding"

     if padding:
          # Remove padding if there is one
          __lowerCamelCase   :	Any								=		encoded_data[:-padding]

          __lowerCamelCase   :	Optional[Any]								=		''.join(
              bin(B64_CHARSET.index(UpperCAmelCase_							)							)[2:].zfill(6							) for char in encoded_data							)[: -padding * 2]
     else:
          __lowerCamelCase   :	Any								=		''.join(
              bin(B64_CHARSET.index(UpperCAmelCase_							)							)[2:].zfill(6							) for char in encoded_data							)

     __lowerCamelCase   :	str								=		[
         int(binary_stream[index : index + 8]      ,    2							)
         for index in range(0      ,    len(UpperCAmelCase_							)      ,    8							)
     ]

     return bytes(UpperCAmelCase_							)


if __name__ == "__main__":
      import doctest

      doctest.testmod()






