


'''simple docstring'''


from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFImageClassifierOutputWithNoAttention,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_resnet import ResNetConfig


_UpperCamelCase          =     logging.get_logger(__name__)

# General docstring
_UpperCamelCase          =     """ResNetConfig"""

# Base docstring
_UpperCamelCase          =     """microsoft/resnet-50"""
_UpperCamelCase          =     [1, 2048, 7, 7]

# Image classification docstring
_UpperCamelCase          =     """microsoft/resnet-50"""
_UpperCamelCase          =     """tiger cat"""

_UpperCamelCase          =     [
    """microsoft/resnet-50""",
    # See all resnet models at https://huggingface.co/models?filter=resnet
]







class        __magic_name__  (					tf.keras.layers.Layer   ):

     """simple docstring"""






     def __init__(      self ,    lowerCamelCase ,    lowerCamelCase = 3 ,    lowerCamelCase = 1 ,    lowerCamelCase = "relu" ,    **lowerCamelCase		):


          '''simple docstring'''





          super().__init__(**lowerCamelCase		)
          __A  :					str						     =       kernel_size // 2
          __A  :					Optional[Any]						     =       tf.keras.layers.ConvaD(
              lowerCamelCase ,    kernel_size=lowerCamelCase ,    strides=lowerCamelCase ,    padding="valid" ,    use_bias=lowerCamelCase ,    name="convolution"		)
          # Use same default momentum and epsilon as PyTorch equivalent
          __A  :					int						     =       tf.keras.layers.BatchNormalization(epsilon=1E-5 ,    momentum=0.9 ,    name="normalization"		)
          __A  :					str						     =       ACTaFN[activation] if activation is not None else tf.keras.layers.Activation("linear"		)


     def lowerCAmelCase__     (      self ,    lowerCamelCase		):


          '''simple docstring'''





          __A  :					Optional[int]						     =       (self.pad_value, self.pad_value)
          __A  :					Tuple						     =       tf.pad(lowerCamelCase ,    [(0, 0), height_pad, width_pad, (0, 0)]		)
          __A  :					int						     =       self.conv(lowerCamelCase		)
          return hidden_state


     def lowerCAmelCase__     (      self ,    lowerCamelCase ,    lowerCamelCase = False		):


          '''simple docstring'''





          __A  :					Optional[int]						     =       self.convolution(lowerCamelCase		)
          __A  :					List[Any]						     =       self.normalization(lowerCamelCase ,    training=lowerCamelCase		)
          __A  :					Tuple						     =       self.activation(lowerCamelCase		)
          return hidden_state







class        __magic_name__  (					tf.keras.layers.Layer   ):

     """simple docstring"""






     def __init__(      self ,    lowerCamelCase ,    **lowerCamelCase		):


          '''simple docstring'''





          super().__init__(**lowerCamelCase		)
          __A  :					List[Any]						     =       TFResNetConvLayer(
              config.embedding_size ,    kernel_size=7 ,    stride=2 ,    activation=config.hidden_act ,    name="embedder" ,    )
          __A  :					Tuple						     =       tf.keras.layers.MaxPoolaD(pool_size=3 ,    strides=2 ,    padding="valid" ,    name="pooler"		)
          __A  :					Dict						     =       config.num_channels


     def lowerCAmelCase__     (      self ,    lowerCamelCase ,    lowerCamelCase = False		):


          '''simple docstring'''





          __A     ,__A     ,__A     ,__A  :					List[Any]						     =       shape_list(lowerCamelCase		)
          if tf.executing_eagerly() and num_channels != self.num_channels:
               raise ValueError(
                   "Make sure that the channel dimension of the pixel values match with the one set in the configuration."		)
          __A  :					List[str]						     =       pixel_values
          __A  :					List[str]						     =       self.embedder(lowerCamelCase		)
          __A  :					Any						     =       tf.pad(lowerCamelCase ,    [[0, 0], [1, 1], [1, 1], [0, 0]]		)
          __A  :					Union[str, Any]						     =       self.pooler(lowerCamelCase		)
          return hidden_state







class        __magic_name__  (					tf.keras.layers.Layer   ):

     """simple docstring"""






     def __init__(      self ,    lowerCamelCase ,    lowerCamelCase = 2 ,    **lowerCamelCase		):


          '''simple docstring'''





          super().__init__(**lowerCamelCase		)
          __A  :					Any						     =       tf.keras.layers.ConvaD(
              lowerCamelCase ,    kernel_size=1 ,    strides=lowerCamelCase ,    use_bias=lowerCamelCase ,    name="convolution"		)
          # Use same default momentum and epsilon as PyTorch equivalent
          __A  :					Optional[Any]						     =       tf.keras.layers.BatchNormalization(epsilon=1E-5 ,    momentum=0.9 ,    name="normalization"		)


     def lowerCAmelCase__     (      self ,    lowerCamelCase ,    lowerCamelCase = False		):


          '''simple docstring'''





          __A  :					Optional[Any]						     =       x
          __A  :					Any						     =       self.convolution(lowerCamelCase		)
          __A  :					Tuple						     =       self.normalization(lowerCamelCase ,    training=lowerCamelCase		)
          return hidden_state







class        __magic_name__  (					tf.keras.layers.Layer   ):

     """simple docstring"""






     def __init__(      self ,    lowerCamelCase ,    lowerCamelCase ,    lowerCamelCase = 1 ,    lowerCamelCase = "relu" ,    **lowerCamelCase		):


          '''simple docstring'''





          super().__init__(**lowerCamelCase		)
          __A  :					Optional[int]						     =       in_channels != out_channels or stride != 1
          __A  :					List[Any]						     =       TFResNetConvLayer(lowerCamelCase ,    stride=lowerCamelCase ,    name="layer.0"		)
          __A  :					Tuple						     =       TFResNetConvLayer(lowerCamelCase ,    activation=lowerCamelCase ,    name="layer.1"		)
          __A  :					int						     =       (
              TFResNetShortCut(lowerCamelCase ,    stride=lowerCamelCase ,    name="shortcut"		)
              if should_apply_shortcut
              else tf.keras.layers.Activation("linear" ,    name="shortcut"		)
          )
          __A  :					Optional[int]						     =       ACTaFN[activation]


     def lowerCAmelCase__     (      self ,    lowerCamelCase ,    lowerCamelCase = False		):


          '''simple docstring'''





          __A  :					Optional[int]						     =       hidden_state
          __A  :					Dict						     =       self.conva(lowerCamelCase ,    training=lowerCamelCase		)
          __A  :					Tuple						     =       self.conva(lowerCamelCase ,    training=lowerCamelCase		)
          __A  :					Union[str, Any]						     =       self.shortcut(lowerCamelCase ,    training=lowerCamelCase		)
          hidden_state += residual
          __A  :					List[str]						     =       self.activation(lowerCamelCase		)
          return hidden_state







class        __magic_name__  (					tf.keras.layers.Layer   ):

     """simple docstring"""






     def __init__(      self ,    lowerCamelCase ,    lowerCamelCase ,    lowerCamelCase = 1 ,    lowerCamelCase = "relu" ,    lowerCamelCase = 4 ,    **lowerCamelCase ,    ):


          '''simple docstring'''





          super().__init__(**lowerCamelCase		)
          __A  :					Tuple						     =       in_channels != out_channels or stride != 1
          __A  :					Tuple						     =       out_channels // reduction
          __A  :					int						     =       TFResNetConvLayer(lowerCamelCase ,    kernel_size=1 ,    name="layer.0"		)
          __A  :					List[Any]						     =       TFResNetConvLayer(lowerCamelCase ,    stride=lowerCamelCase ,    name="layer.1"		)
          __A  :					Dict						     =       TFResNetConvLayer(lowerCamelCase ,    kernel_size=1 ,    activation=lowerCamelCase ,    name="layer.2"		)
          __A  :					List[Any]						     =       (
              TFResNetShortCut(lowerCamelCase ,    stride=lowerCamelCase ,    name="shortcut"		)
              if should_apply_shortcut
              else tf.keras.layers.Activation("linear" ,    name="shortcut"		)
          )
          __A  :					Optional[int]						     =       ACTaFN[activation]


     def lowerCAmelCase__     (      self ,    lowerCamelCase ,    lowerCamelCase = False		):


          '''simple docstring'''





          __A  :					int						     =       hidden_state
          __A  :					Dict						     =       self.conva(lowerCamelCase ,    training=lowerCamelCase		)
          __A  :					int						     =       self.conva(lowerCamelCase ,    training=lowerCamelCase		)
          __A  :					int						     =       self.conva(lowerCamelCase ,    training=lowerCamelCase		)
          __A  :					Union[str, Any]						     =       self.shortcut(lowerCamelCase ,    training=lowerCamelCase		)
          hidden_state += residual
          __A  :					Any						     =       self.activation(lowerCamelCase		)
          return hidden_state







class        __magic_name__  (					tf.keras.layers.Layer   ):

     """simple docstring"""






     def __init__(      self ,    lowerCamelCase ,    lowerCamelCase ,    lowerCamelCase ,    lowerCamelCase = 2 ,    lowerCamelCase = 2 ,    **lowerCamelCase		):


          '''simple docstring'''





          super().__init__(**lowerCamelCase		)

          __A  :					str						     =       TFResNetBottleNeckLayer if config.layer_type == "bottleneck" else TFResNetBasicLayer

          __A  :					str						     =       [layer(lowerCamelCase ,    lowerCamelCase ,    stride=lowerCamelCase ,    activation=config.hidden_act ,    name="layers.0"		)]
          layers += [
              layer(lowerCamelCase ,    lowerCamelCase ,    activation=config.hidden_act ,    name=f"layers.{i + 1}"		)
              for i in range(depth - 1		)
          ]
          __A  :					Dict						     =       layers


     def lowerCAmelCase__     (      self ,    lowerCamelCase ,    lowerCamelCase = False		):


          '''simple docstring'''





          for layer in self.stage_layers:
               __A  :					int						     =       layer(lowerCamelCase ,    training=lowerCamelCase		)
          return hidden_state







class        __magic_name__  (					tf.keras.layers.Layer   ):

     """simple docstring"""






     def __init__(      self ,    lowerCamelCase ,    **lowerCamelCase		):


          '''simple docstring'''





          super().__init__(**lowerCamelCase		)
          # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
          __A  :					Optional[int]						     =       [
              TFResNetStage(
                  lowerCamelCase ,    config.embedding_size ,    config.hidden_sizes[0] ,    stride=2 if config.downsample_in_first_stage else 1 ,    depth=config.depths[0] ,    name="stages.0" ,    )
          ]
          for i, (in_channels, out_channels, depth) in enumerate(
              zip(config.hidden_sizes ,    config.hidden_sizes[1:] ,    config.depths[1:]		)		):
               self.stages.append(TFResNetStage(lowerCamelCase ,    lowerCamelCase ,    lowerCamelCase ,    depth=lowerCamelCase ,    name=f"stages.{i + 1}"		)		)


     def lowerCAmelCase__     (      self ,    lowerCamelCase ,    lowerCamelCase = False ,    lowerCamelCase = True ,    lowerCamelCase = False ,    ):


          '''simple docstring'''





          __A  :					Union[str, Any]						     =       () if output_hidden_states else None

          for stage_module in self.stages:
               if output_hidden_states:
                    __A  :					Optional[Any]						     =       hidden_states + (hidden_state,)

               __A  :					Union[str, Any]						     =       stage_module(lowerCamelCase ,    training=lowerCamelCase		)

          if output_hidden_states:
               __A  :					int						     =       hidden_states + (hidden_state,)

          if not return_dict:
               return tuple(v for v in [hidden_state, hidden_states] if v is not None		)

          return TFBaseModelOutputWithNoAttention(last_hidden_state=lowerCamelCase ,    hidden_states=lowerCamelCase		)







class        __magic_name__  (					lowerCAmelCase   ):

     """simple docstring"""






     lowerCamelCase__						=							ResNetConfig
     lowerCamelCase__						=							'resnet'
     lowerCamelCase__						=							'pixel_values'


     @property
     def lowerCAmelCase__     (      self		):


          '''simple docstring'''





          return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) ,    dtype=tf.floataa		)}


_UpperCamelCase          =     r"""
    This model is a TensorFlow
    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a
    regular TensorFlow Module and refer to the TensorFlow documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
"""


_UpperCamelCase          =     r"""
    Args:
        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConvNextImageProcessor.__call__`] for details.

        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""







@keras_serializable
class        __magic_name__  (					tf.keras.layers.Layer   ):

     """simple docstring"""






     lowerCamelCase__						=							ResNetConfig


     def __init__(      self ,    lowerCamelCase ,    **lowerCamelCase		):


          '''simple docstring'''





          super().__init__(**lowerCamelCase		)
          __A  :					int						     =       config
          __A  :					Any						     =       TFResNetEmbeddings(lowerCamelCase ,    name="embedder"		)
          __A  :					Any						     =       TFResNetEncoder(lowerCamelCase ,    name="encoder"		)
          __A  :					int						     =       tf.keras.layers.GlobalAveragePoolingaD(keepdims=lowerCamelCase		)


     @unpack_inputs
     def lowerCAmelCase__     (      self ,    lowerCamelCase ,    lowerCamelCase = None ,    lowerCamelCase = None ,    lowerCamelCase = False ,    ):


          '''simple docstring'''





          __A  :					int						     =       (
              output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
          )
          __A  :					Dict						     =       return_dict if return_dict is not None else self.config.use_return_dict

          # TF 2.0 image layers can't use NCHW format when running on CPU.
          # We transpose to NHWC format and then transpose back after the full forward pass.
          # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
          __A  :					str						     =       tf.transpose(lowerCamelCase ,    perm=[0, 2, 3, 1]		)
          __A  :					Tuple						     =       self.embedder(lowerCamelCase ,    training=lowerCamelCase		)

          __A  :					Dict						     =       self.encoder(
              lowerCamelCase ,    output_hidden_states=lowerCamelCase ,    return_dict=lowerCamelCase ,    training=lowerCamelCase		)

          __A  :					Tuple						     =       encoder_outputs[0]

          __A  :					Tuple						     =       self.pooler(lowerCamelCase		)

          # Transpose all the outputs to the NCHW format
          # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
          __A  :					List[Any]						     =       tf.transpose(lowerCamelCase ,    (0, 3, 1, 2)		)
          __A  :					int						     =       tf.transpose(lowerCamelCase ,    (0, 3, 1, 2)		)
          __A  :					str						     =       ()
          for hidden_state in encoder_outputs[1:]:
               __A  :					Tuple						     =       hidden_states + tuple(tf.transpose(lowerCamelCase ,    (0, 3, 1, 2)		) for h in hidden_state		)

          if not return_dict:
               return (last_hidden_state, pooled_output) + hidden_states

          __A  :					Any						     =       hidden_states if output_hidden_states else None

          return TFBaseModelOutputWithPoolingAndNoAttention(
              last_hidden_state=lowerCamelCase ,    pooler_output=lowerCamelCase ,    hidden_states=lowerCamelCase ,    )







@add_start_docstrings(
    'The bare ResNet model outputting raw features without any specific head on top.'						,		lowerCAmelCase						,		)
class        __magic_name__  (					lowerCAmelCase   ):

     """simple docstring"""






     def __init__(      self ,    lowerCamelCase ,    **lowerCamelCase		):


          '''simple docstring'''





          super().__init__(lowerCamelCase ,    **lowerCamelCase		)
          __A  :					List[str]						     =       TFResNetMainLayer(config=lowerCamelCase ,    name="resnet"		)


     @add_start_docstrings_to_model_forward(lowerCamelCase		)
     @add_code_sample_docstrings(
         checkpoint=_CHECKPOINT_FOR_DOC ,    output_type=lowerCamelCase ,    config_class=_CONFIG_FOR_DOC ,    modality="vision" ,    expected_output=_EXPECTED_OUTPUT_SHAPE ,    )
     @unpack_inputs
     def lowerCAmelCase__     (      self ,    lowerCamelCase ,    lowerCamelCase = None ,    lowerCamelCase = None ,    lowerCamelCase = False ,    ):


          '''simple docstring'''





          __A  :					List[Any]						     =       (
              output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
          )
          __A  :					Optional[int]						     =       return_dict if return_dict is not None else self.config.use_return_dict

          __A  :					Union[str, Any]						     =       self.resnet(
              pixel_values=lowerCamelCase ,    output_hidden_states=lowerCamelCase ,    return_dict=lowerCamelCase ,    training=lowerCamelCase ,    )
          return resnet_outputs







@add_start_docstrings(
    '\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '						,		lowerCAmelCase						,		)
class        __magic_name__  (					lowerCAmelCase						,		lowerCAmelCase   ):

     """simple docstring"""






     def __init__(      self ,    lowerCamelCase ,    **lowerCamelCase		):


          '''simple docstring'''





          super().__init__(lowerCamelCase ,    **lowerCamelCase		)
          __A  :					str						     =       config.num_labels
          __A  :					Union[str, Any]						     =       TFResNetMainLayer(lowerCamelCase ,    name="resnet"		)
          # classification head
          __A  :					int						     =       (
              tf.keras.layers.Dense(config.num_labels ,    name="classifier.1"		)
              if config.num_labels > 0
              else tf.keras.layers.Activation("linear" ,    name="classifier.1"		)
          )


     def lowerCAmelCase__     (      self ,    lowerCamelCase		):


          '''simple docstring'''





          __A  :					Dict						     =       tf.keras.layers.Flatten()(lowerCamelCase		)
          __A  :					int						     =       self.classifier_layer(lowerCamelCase		)
          return logits


     @add_start_docstrings_to_model_forward(lowerCamelCase		)
     @add_code_sample_docstrings(
         checkpoint=_IMAGE_CLASS_CHECKPOINT ,    output_type=lowerCamelCase ,    config_class=_CONFIG_FOR_DOC ,    expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,    )
     @unpack_inputs
     def lowerCAmelCase__     (      self ,    lowerCamelCase = None ,    lowerCamelCase = None ,    lowerCamelCase = None ,    lowerCamelCase = None ,    lowerCamelCase = False ,    ):


          '''simple docstring'''





          __A  :					int						     =       return_dict if return_dict is not None else self.config.use_return_dict

          __A  :					Dict						     =       self.resnet(
              lowerCamelCase ,    output_hidden_states=lowerCamelCase ,    return_dict=lowerCamelCase ,    training=lowerCamelCase		)

          __A  :					Dict						     =       outputs.pooler_output if return_dict else outputs[1]

          __A  :					Tuple						     =       self.classifier(lowerCamelCase		)

          __A  :					List[Any]						     =       None if labels is None else self.hf_compute_loss(lowerCamelCase ,    lowerCamelCase		)

          if not return_dict:
               __A  :					List[str]						     =       (logits,) + outputs[2:]
               return (loss,) + output if loss is not None else output

          return TFImageClassifierOutputWithNoAttention(loss=lowerCamelCase ,    logits=lowerCamelCase ,    hidden_states=outputs.hidden_states		)





'''simple docstring'''


import os
from string import ascii_letters

_UpperCamelCase          =     ascii_letters + """ \t\n"""


def 		_lowercase   ():




     '''simple docstring'''





     __A  :					Any						     =       os.path.split(os.path.realpath(SCREAMING_SNAKE_CASE       )       )
     __A  :					dict[str, None]						     =       {}
     with open(path[0] + "/dictionary.txt"       ) as dictionary_file:
          for word in dictionary_file.read().split("\n"       ):
               __A  :					int						     =       None
     return english_words


_UpperCamelCase          =     load_dictionary()


def 		_lowercase   (SCREAMING_SNAKE_CASE       ):




     '''simple docstring'''





     __A  :					int						     =       message.upper()
     __A  :					int						     =       remove_non_letters(SCREAMING_SNAKE_CASE       )
     __A  :					str						     =       message.split()
     __A  :					Tuple						     =       len([word for word in possible_words if word in ENGLISH_WORDS]       )
     return float(SCREAMING_SNAKE_CASE       ) / len(SCREAMING_SNAKE_CASE       )


def 		_lowercase   (SCREAMING_SNAKE_CASE       ):




     '''simple docstring'''





     return "".join(symbol for symbol in message if symbol in LETTERS_AND_SPACE       )


def 		_lowercase   (SCREAMING_SNAKE_CASE					,				SCREAMING_SNAKE_CASE = 20					,				SCREAMING_SNAKE_CASE = 85       ):




     '''simple docstring'''





     __A  :					Optional[Any]						     =       get_english_count(SCREAMING_SNAKE_CASE       ) * 100 >= word_percentage
     __A  :					Optional[int]						     =       len(remove_non_letters(SCREAMING_SNAKE_CASE       )       )
     __A  :					Any						     =       (float(SCREAMING_SNAKE_CASE       ) / len(SCREAMING_SNAKE_CASE       )) * 100
     __A  :					int						     =       message_letters_percentage >= letter_percentage
     return words_match and letters_match


if __name__ == "__main__":
      import doctest

      doctest.testmod()

