

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, 2_048, 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 SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    Any       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int = 3       ,							lowerCAmelCase :    int = 1       ,							lowerCAmelCase :    str = "relu"       ,							**lowerCAmelCase :    int    )							->	None:






     """simple docstring"""







     super().__init__(**lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[Any]					    =						kernel_size // 2
     __lowerCAmelCase  :			Union[str, 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
     __lowerCAmelCase  :			str					    =						tf.keras.layers.BatchNormalization(epsilon=1e-5       ,							momentum=0.9       ,							name="""normalization"""    )
     __lowerCAmelCase  :			Tuple					    =						ACTaFN[activation] if activation is not None else tf.keras.layers.Activation("""linear"""    )







  def        SCREAMING_SNAKE_CASE    (			self :    Dict       ,							lowerCAmelCase :    tf.Tensor    )							->	tf.Tensor:






     """simple docstring"""







     __lowerCAmelCase  :			List[Any]					    =						(self.pad_value, self.pad_value)
     __lowerCAmelCase  :			Optional[Any]					    =						tf.pad(lowerCAmelCase       ,							[(0, 0), height_pad, width_pad, (0, 0)]    )
     __lowerCAmelCase  :			Tuple					    =						self.conv(lowerCAmelCase    )
     return hidden_state







  def        SCREAMING_SNAKE_CASE    (			self :    int       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False    )							->	tf.Tensor:






     """simple docstring"""







     __lowerCAmelCase  :			Union[str, Any]					    =						self.convolution(lowerCAmelCase    )
     __lowerCAmelCase  :			Dict					    =						self.normalization(lowerCAmelCase       ,							training=lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[int]					    =						self.activation(lowerCAmelCase    )
     return hidden_state






class SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    str       ,							lowerCAmelCase :    ResNetConfig       ,							**lowerCAmelCase :    Union[str, Any]    )							->	None:






     """simple docstring"""







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







  def        SCREAMING_SNAKE_CASE    (			self :    Dict       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False    )							->	tf.Tensor:






     """simple docstring"""







     __lowerCAmelCase    ,__lowerCAmelCase    ,__lowerCAmelCase    ,__lowerCAmelCase  :			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."""    )
     __lowerCAmelCase  :			Union[str, Any]					    =						pixel_values
     __lowerCAmelCase  :			int					    =						self.embedder(lowerCAmelCase    )
     __lowerCAmelCase  :			Any					    =						tf.pad(lowerCAmelCase       ,							[[0, 0], [1, 1], [1, 1], [0, 0]]    )
     __lowerCAmelCase  :			Any					    =						self.pooler(lowerCAmelCase    )
     return hidden_state






class SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    List[Any]       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int = 2       ,							**lowerCAmelCase :    Dict    )							->	None:






     """simple docstring"""







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







  def        SCREAMING_SNAKE_CASE    (			self :    int       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False    )							->	tf.Tensor:






     """simple docstring"""







     __lowerCAmelCase  :			List[Any]					    =						x
     __lowerCAmelCase  :			int					    =						self.convolution(lowerCAmelCase    )
     __lowerCAmelCase  :			Dict					    =						self.normalization(lowerCAmelCase       ,							training=lowerCAmelCase    )
     return hidden_state






class SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    int       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int = 1       ,							lowerCAmelCase :    str = "relu"       ,							**lowerCAmelCase :    Tuple    )							->	None:






     """simple docstring"""







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







  def        SCREAMING_SNAKE_CASE    (			self :    List[str]       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False    )							->	tf.Tensor:






     """simple docstring"""







     __lowerCAmelCase  :			Any					    =						hidden_state
     __lowerCAmelCase  :			Tuple					    =						self.conva(lowerCAmelCase       ,							training=lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[int]					    =						self.conva(lowerCAmelCase       ,							training=lowerCAmelCase    )
     __lowerCAmelCase  :			List[Any]					    =						self.shortcut(lowerCAmelCase       ,							training=lowerCAmelCase    )
     hidden_state += residual
     __lowerCAmelCase  :			List[str]					    =						self.activation(lowerCAmelCase    )
     return hidden_state






class SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    Dict       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int = 1       ,							lowerCAmelCase :    str = "relu"       ,							lowerCAmelCase :    int = 4       ,							**lowerCAmelCase :    int       ,							)							->	None:






     """simple docstring"""







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







  def        SCREAMING_SNAKE_CASE    (			self :    Tuple       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False    )							->	tf.Tensor:






     """simple docstring"""







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






class SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    Any       ,							lowerCAmelCase :    ResNetConfig       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int = 2       ,							lowerCAmelCase :    int = 2       ,							**lowerCAmelCase :    int    )							->	None:






     """simple docstring"""







     super().__init__(**lowerCAmelCase    )

     __lowerCAmelCase  :			Dict					    =						TFResNetBottleNeckLayer if config.layer_type == """bottleneck""" else TFResNetBasicLayer

     __lowerCAmelCase  :			Dict					    =						[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    )
     ]
     __lowerCAmelCase  :			Optional[Any]					    =						layers







  def        SCREAMING_SNAKE_CASE    (			self :    Any       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False    )							->	tf.Tensor:






     """simple docstring"""







     for layer in self.stage_layers:
        __lowerCAmelCase  :			Union[str, Any]					    =						layer(lowerCAmelCase       ,							training=lowerCAmelCase    )
     return hidden_state






class SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    str       ,							lowerCAmelCase :    ResNetConfig       ,							**lowerCAmelCase :    Any    )							->	None:






     """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
     __lowerCAmelCase  :			Dict					    =						[
         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        SCREAMING_SNAKE_CASE    (			self :    Optional[Any]       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False       ,							lowerCAmelCase :    bool = True       ,							lowerCAmelCase :    bool = False       ,							)							->	TFBaseModelOutputWithNoAttention:






     """simple docstring"""







     __lowerCAmelCase  :			str					    =						() if output_hidden_states else None

     for stage_module in self.stages:
        if output_hidden_states:
           __lowerCAmelCase  :			Union[str, Any]					    =						hidden_states + (hidden_state,)

        __lowerCAmelCase  :			Optional[int]					    =						stage_module(lowerCAmelCase       ,							training=lowerCAmelCase    )

     if output_hidden_states:
        __lowerCAmelCase  :			Optional[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 SCREAMING_SNAKE_CASE	(  a_ ):
  """simple docstring"""






  lowerCamelCase    :			Optional[Any]						      =ResNetConfig
  lowerCamelCase    :			List[Any]						      ="resnet"
  lowerCamelCase    :			List[str]						      ="pixel_values"







  @property
  def        SCREAMING_SNAKE_CASE    (			self :    str    )							->	Union[str, Any]:






     """simple docstring"""







     return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24)       ,							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 SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  lowerCamelCase    :			int						      =ResNetConfig







  def __init__(			self :    Optional[Any]       ,							lowerCAmelCase :    ResNetConfig       ,							**lowerCAmelCase :    List[str]    )							->	None:






     """simple docstring"""







     super().__init__(**lowerCAmelCase    )
     __lowerCAmelCase  :			str					    =						config
     __lowerCAmelCase  :			List[Any]					    =						TFResNetEmbeddings(lowerCAmelCase       ,							name="""embedder"""    )
     __lowerCAmelCase  :			int					    =						TFResNetEncoder(lowerCAmelCase       ,							name="""encoder"""    )
     __lowerCAmelCase  :			List[Any]					    =						tf.keras.layers.GlobalAveragePoolingaD(keepdims=lowerCAmelCase    )







  @unpack_inputs
  def        SCREAMING_SNAKE_CASE    (			self :    Any       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    Optional[bool] = None       ,							lowerCAmelCase :    Optional[bool] = None       ,							lowerCAmelCase :    bool = False       ,							)							->	Union[Tuple[tf.Tensor], TFBaseModelOutputWithPoolingAndNoAttention]:






     """simple docstring"""







     __lowerCAmelCase  :			Optional[Any]					    =						(
         output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
     )
     __lowerCAmelCase  :			List[Any]					    =						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)
     __lowerCAmelCase  :			Optional[Any]					    =						tf.transpose(lowerCAmelCase       ,							perm=[0, 2, 3, 1]    )
     __lowerCAmelCase  :			Any					    =						self.embedder(lowerCAmelCase       ,							training=lowerCAmelCase    )

     __lowerCAmelCase  :			int					    =						self.encoder(
         lowerCAmelCase       ,							output_hidden_states=lowerCAmelCase       ,							return_dict=lowerCAmelCase       ,							training=lowerCAmelCase    )

     __lowerCAmelCase  :			List[str]					    =						encoder_outputs[0]

     __lowerCAmelCase  :			Dict					    =						self.pooler(lowerCAmelCase    )

     # Transpose all the outputs to the NCHW format
     # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
     __lowerCAmelCase  :			Dict					    =						tf.transpose(lowerCAmelCase       ,							(0, 3, 1, 2)    )
     __lowerCAmelCase  :			Dict					    =						tf.transpose(lowerCAmelCase       ,							(0, 3, 1, 2)    )
     __lowerCAmelCase  :			Any					    =						()
     for hidden_state in encoder_outputs[1:]:
        __lowerCAmelCase  :			List[Any]					    =						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

     __lowerCAmelCase  :			Dict					    =						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."   ,							a_   ,							)
class SCREAMING_SNAKE_CASE	(  a_ ):
  """simple docstring"""






  def __init__(			self :    Optional[int]       ,							lowerCAmelCase :    ResNetConfig       ,							**lowerCAmelCase :    int    )							->	None:






     """simple docstring"""







     super().__init__(lowerCAmelCase       ,							**lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[int]					    =						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        SCREAMING_SNAKE_CASE    (			self :    Any       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    Optional[bool] = None       ,							lowerCAmelCase :    Optional[bool] = None       ,							lowerCAmelCase :    bool = False       ,							)							->	Union[Tuple[tf.Tensor], TFBaseModelOutputWithPoolingAndNoAttention]:






     """simple docstring"""







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

     __lowerCAmelCase  :			str					    =						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    "   ,							a_   ,							)
class SCREAMING_SNAKE_CASE	(  a_   ,							a_ ):
  """simple docstring"""






  def __init__(			self :    Dict       ,							lowerCAmelCase :    ResNetConfig       ,							**lowerCAmelCase :    str    )							->	None:






     """simple docstring"""







     super().__init__(lowerCAmelCase       ,							**lowerCAmelCase    )
     __lowerCAmelCase  :			List[str]					    =						config.num_labels
     __lowerCAmelCase  :			List[str]					    =						TFResNetMainLayer(lowerCAmelCase       ,							name="""resnet"""    )
     # classification head
     __lowerCAmelCase  :			Dict					    =						(
         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        SCREAMING_SNAKE_CASE    (			self :    Dict       ,							lowerCAmelCase :    tf.Tensor    )							->	tf.Tensor:






     """simple docstring"""







     __lowerCAmelCase  :			List[str]					    =						tf.keras.layers.Flatten()(lowerCAmelCase    )
     __lowerCAmelCase  :			List[str]					    =						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        SCREAMING_SNAKE_CASE    (			self :    Optional[Any]       ,							lowerCAmelCase :    tf.Tensor = None       ,							lowerCAmelCase :    tf.Tensor = None       ,							lowerCAmelCase :    bool = None       ,							lowerCAmelCase :    bool = None       ,							lowerCAmelCase :    bool = False       ,							)							->	Union[Tuple[tf.Tensor], TFImageClassifierOutputWithNoAttention]:






     """simple docstring"""







     __lowerCAmelCase  :			Optional[int]					    =						return_dict if return_dict is not None else self.config.use_return_dict

     __lowerCAmelCase  :			Tuple					    =						self.resnet(
         lowerCAmelCase       ,							output_hidden_states=lowerCAmelCase       ,							return_dict=lowerCAmelCase       ,							training=lowerCAmelCase    )

     __lowerCAmelCase  :			List[Any]					    =						outputs.pooler_output if return_dict else outputs[1]

     __lowerCAmelCase  :			Optional[Any]					    =						self.classifier(lowerCAmelCase    )

     __lowerCAmelCase  :			int					    =						None if labels is None else self.hf_compute_loss(lowerCAmelCase       ,							lowerCAmelCase    )

     if not return_dict:
        __lowerCAmelCase  :			Optional[int]					    =						(logits,) + outputs[2:]
        return (loss,) + output if loss is not None else output

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





from __future__ import annotations

import os



class SCREAMING_SNAKE_CASE	:
  """simple docstring"""






  lowerCamelCase    :			Union[str, Any]						      =(
      "High card",
      "One pair",
      "Two pairs",
      "Three of a kind",
      "Straight",
      "Flush",
      "Full house",
      "Four of a kind",
      "Straight flush",
      "Royal flush",
  )

  lowerCamelCase    :			Dict						      =(
      "",  # placeholder as tuples are zero-indexed
      "One",
      "Two",
      "Three",
      "Four",
      "Five",
      "Six",
      "Seven",
      "Eight",
      "Nine",
      "Ten",
      "Jack",
      "Queen",
      "King",
      "Ace",
  )







  def __init__(			self :    Tuple       ,							lowerCAmelCase :    str    )							->	None:






     """simple docstring"""







     if not isinstance(lowerCAmelCase       ,							lowerCAmelCase    ):
        __lowerCAmelCase  :			Tuple					    =						f'''Hand should be of type \'str\': {hand!r}'''
        raise TypeError(lowerCAmelCase    )
     # split removes duplicate whitespaces so no need of strip
     if len(hand.split(""" """    )    ) != 5:
        __lowerCAmelCase  :			Any					    =						f'''Hand should contain only 5 cards: {hand!r}'''
        raise ValueError(lowerCAmelCase    )
     __lowerCAmelCase  :			int					    =						hand
     __lowerCAmelCase  :			Any					    =						0
     __lowerCAmelCase  :			str					    =						0
     __lowerCAmelCase    ,__lowerCAmelCase  :			List[str]					    =						self._internal_state()
     __lowerCAmelCase  :			int					    =						self._get_hand_type()
     __lowerCAmelCase  :			Any					    =						self._card_values[0]







  @property
  def        SCREAMING_SNAKE_CASE    (			self :    Union[str, Any]    )							->	Optional[int]:






     """simple docstring"""







     return self._hand







  def        SCREAMING_SNAKE_CASE    (			self :    Dict       ,							lowerCAmelCase :    PokerHand    )							->	str:






     """simple docstring"""







     if self._hand_type > other._hand_type:
        return "Win"
     elif self._hand_type < other._hand_type:
        return "Loss"
     elif self._first_pair == other._first_pair:
        if self._second_pair == other._second_pair:
           return self._compare_cards(lowerCAmelCase    )
        else:
           return "Win" if self._second_pair > other._second_pair else "Loss"
     return "Win" if self._first_pair > other._first_pair else "Loss"







  def        SCREAMING_SNAKE_CASE    (			self :    int    )							->	str:






     """simple docstring"""







     __lowerCAmelCase  :			Optional[int]					    =						PokerHand._HAND_NAME[self._hand_type - 14]
     __lowerCAmelCase  :			str					    =						PokerHand._CARD_NAME[self._high_card]
     __lowerCAmelCase  :			Optional[Any]					    =						PokerHand._CARD_NAME[self._first_pair]
     __lowerCAmelCase  :			Any					    =						PokerHand._CARD_NAME[self._second_pair]
     if self._hand_type in [22, 19, 18]:
        return name + f''', {high}-high'''
     elif self._hand_type in [21, 17, 15]:
        return name + f''', {paira}s'''
     elif self._hand_type in [20, 16]:
        __lowerCAmelCase  :			List[str]					    =						"""over""" if self._hand_type == 20 else """and"""
        return name + f''', {paira}s {join} {paira}s'''
     elif self._hand_type == 23:
        return name
     else:
        return name + f''', {high}'''







  def        SCREAMING_SNAKE_CASE    (			self :    Dict       ,							lowerCAmelCase :    PokerHand    )							->	str:






     """simple docstring"""







     for index, card_value in enumerate(self._card_values    ):
        if card_value != other._card_values[index]:
           return "Win" if card_value > other._card_values[index] else "Loss"
     return "Tie"







  def        SCREAMING_SNAKE_CASE    (			self :    Optional[int]    )							->	int:






     """simple docstring"""







     if self._is_flush():
        if self._is_five_high_straight() or self._is_straight():
           return 23 if sum(self._card_values    ) == 60 else 22
        return 19
     elif self._is_five_high_straight() or self._is_straight():
        return 18
     return 14 + self._is_same_kind()







  def        SCREAMING_SNAKE_CASE    (			self :    List[Any]    )							->	bool:






     """simple docstring"""







     return len(self._card_suit    ) == 1







  def        SCREAMING_SNAKE_CASE    (			self :    List[str]    )							->	bool:






     """simple docstring"""







     if sorted(self._card_values    ) == [2, 3, 4, 5, 14]:
        if self._card_values[0] == 14:
           # Remember, our list is sorted in reverse order
           __lowerCAmelCase  :			Optional[Any]					    =						self._card_values.pop(0    )
           self._card_values.append(lowerCAmelCase    )
        return True
     return False







  def        SCREAMING_SNAKE_CASE    (			self :    List[str]    )							->	bool:






     """simple docstring"""







     for i in range(4    ):
        if self._card_values[i] - self._card_values[i + 1] != 1:
           return False
     return True







  def        SCREAMING_SNAKE_CASE    (			self :    Optional[int]    )							->	int:






     """simple docstring"""







     __lowerCAmelCase  :			str					    =						0
     for i in range(4    ):
        # Compare two cards at a time, if they are same increase 'kind',
        # add the value of the card to val1, if it is repeating again we
        # will add 2 to 'kind' as there are now 3 cards with same value.
        # If we get card of different value than val1, we will do the same
        # thing with val2
        if self._card_values[i] == self._card_values[i + 1]:
           if not vala:
              __lowerCAmelCase  :			List[str]					    =						self._card_values[i]
              kind += 1
           elif vala == self._card_values[i]:
              kind += 2
           elif not vala:
              __lowerCAmelCase  :			Optional[Any]					    =						self._card_values[i]
              kind += 1
           elif vala == self._card_values[i]:
              kind += 2
        # For consistency in hand type (look at note in _get_hand_type function)
     __lowerCAmelCase  :			List[Any]					    =						kind + 2 if kind in [4, 5] else kind
     # first meaning first pair to compare in 'compare_with'
     __lowerCAmelCase  :			Optional[int]					    =						max(lowerCAmelCase       ,							lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[Any]					    =						min(lowerCAmelCase       ,							lowerCAmelCase    )
     # If it's full house (three count pair + two count pair), make sure
     # first pair is three count and if not then switch them both.
     if kind == 6 and self._card_values.count(lowerCAmelCase    ) != 3:
        __lowerCAmelCase    ,__lowerCAmelCase  :			Tuple					    =						second, first
     __lowerCAmelCase  :			Optional[Any]					    =						first
     __lowerCAmelCase  :			Union[str, Any]					    =						second
     return kind







  def        SCREAMING_SNAKE_CASE    (			self :    List[Any]    )							->	tuple[list[int], set[str]]:






     """simple docstring"""







     __lowerCAmelCase  :			dict					    =						{"T": "10", "J": "11", "Q": "12", "K": "13", "A": "14"}
     __lowerCAmelCase  :			Optional[Any]					    =						self._hand.translate(str.maketrans(lowerCAmelCase    )    ).split()
     __lowerCAmelCase  :			List[str]					    =						[int(card[:-1]    ) for card in new_hand]
     __lowerCAmelCase  :			str					    =						{card[-1] for card in new_hand}
     return sorted(lowerCAmelCase       ,							reverse=lowerCAmelCase    ), card_suit







  def __repr__(			self :    List[str]    )							->	Any:






     """simple docstring"""







     return f'''{self.__class__}("{self._hand}")'''







  def __str__(			self :    Any    )							->	Any:






     """simple docstring"""







     return self._hand







  def __eq__(			self :    Union[str, Any]       ,							lowerCAmelCase :    List[Any]    )							->	Union[str, Any]:






     """simple docstring"""







     if isinstance(lowerCAmelCase       ,							lowerCAmelCase    ):
        return self.compare_with(lowerCAmelCase    ) == "Tie"
     return NotImplemented







  def __lt__(			self :    Dict       ,							lowerCAmelCase :    str    )							->	List[str]:






     """simple docstring"""







     if isinstance(lowerCAmelCase       ,							lowerCAmelCase    ):
        return self.compare_with(lowerCAmelCase    ) == "Loss"
     return NotImplemented







  def __le__(			self :    str       ,							lowerCAmelCase :    int    )							->	Union[str, Any]:






     """simple docstring"""







     if isinstance(lowerCAmelCase       ,							lowerCAmelCase    ):
        return self < other or self == other
     return NotImplemented







  def __gt__(			self :    Dict       ,							lowerCAmelCase :    str    )							->	Optional[Any]:






     """simple docstring"""







     if isinstance(lowerCAmelCase       ,							lowerCAmelCase    ):
        return not self < other and self != other
     return NotImplemented







  def __ge__(			self :    Tuple       ,							lowerCAmelCase :    Tuple    )							->	Dict:






     """simple docstring"""







     if isinstance(lowerCAmelCase       ,							lowerCAmelCase    ):
        return not self < other
     return NotImplemented







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






     """simple docstring"""







     return object.__hash__(self    )






def 	snake_case_      ()			->	int:
   # Solution for problem number 54 from Project Euler
   # Input from poker_hands.txt file
   __lowerCAmelCase  :			str					    =						0
   __lowerCAmelCase  :			List[str]					    =						os.path.abspath(os.path.dirname(__A     )     )
   __lowerCAmelCase  :			Optional[Any]					    =						os.path.join(__A					,   """poker_hands.txt"""     )
   with open(__A     ) as file_hand:
      for line in file_hand:
         __lowerCAmelCase  :			Union[str, Any]					    =						line[:1_4].strip()
         __lowerCAmelCase  :			Optional[int]					    =						line[1_5:].strip()
         __lowerCAmelCase    ,__lowerCAmelCase  :			List[str]					    =						PokerHand(__A     ), PokerHand(__A     )
         __lowerCAmelCase  :			List[str]					    =						player.compare_with(__A     )
         if output == "Win":
            answer += 1
   return answer


if __name__ == "__main__":
   solution()


