



from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
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 				lowerCAmelCase_		(  nn.Module							):
       def __init__(			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_ = 3,			SCREAMING_SNAKE_CASE_ = 1,			SCREAMING_SNAKE_CASE_ = "relu"       )     ->		List[Any]:
          super().__init__()
          UpperCamelCase    :  Optional[Any]							=	nn.Convad(
              __a,			__a,			kernel_size=__a,			stride=__a,			padding=kernel_size // 2,			bias=__a       )
          UpperCamelCase    :  List[Any]							=	nn.BatchNormad(__a       )
          UpperCamelCase    :  Optional[Any]							=	ACTaFN[activation] if activation is not None else nn.Identity()






       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_       )     ->		str:
          UpperCamelCase    :  List[Any]							=	self.convolution(__a       )
          UpperCamelCase    :  Dict							=	self.normalization(__a       )
          UpperCamelCase    :  List[Any]							=	self.activation(__a       )
          return hidden_state






class 				lowerCAmelCase_		(  nn.Module							):
       def __init__(			self,			SCREAMING_SNAKE_CASE_       )     ->		Optional[Any]:
          super().__init__()
          UpperCamelCase    :  Optional[int]							=	ResNetConvLayer(
              config.num_channels,			config.embedding_size,			kernel_size=7,			stride=2,			activation=config.hidden_act       )
          UpperCamelCase    :  Dict							=	nn.MaxPoolad(kernel_size=3,			stride=2,			padding=1       )
          UpperCamelCase    :  Tuple							=	config.num_channels






       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_       )     ->		List[Any]:
          UpperCamelCase    :  Optional[Any]							=	pixel_values.shape[1]
          if 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.'       )
          UpperCamelCase    :  int							=	self.embedder(__a       )
          UpperCamelCase    :  Tuple							=	self.pooler(__a       )
          return embedding






class 				lowerCAmelCase_		(  nn.Module							):
       def __init__(			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_ = 2       )     ->		List[str]:
          super().__init__()
          UpperCamelCase    :  Union[str, Any]							=	nn.Convad(__a,			__a,			kernel_size=1,			stride=__a,			bias=__a       )
          UpperCamelCase    :  int							=	nn.BatchNormad(__a       )






       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_       )     ->		Optional[Any]:
          UpperCamelCase    :  Optional[Any]							=	self.convolution(__a       )
          UpperCamelCase    :  Dict							=	self.normalization(__a       )
          return hidden_state






class 				lowerCAmelCase_		(  nn.Module							):
       def __init__(			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_ = 1,			SCREAMING_SNAKE_CASE_ = "relu"       )     ->		str:
          super().__init__()
          UpperCamelCase    :  Tuple							=	in_channels != out_channels or stride != 1
          UpperCamelCase    :  Tuple							=	(
              ResNetShortCut(__a,			__a,			stride=__a       ) if should_apply_shortcut else nn.Identity()
          )
          UpperCamelCase    :  str							=	nn.Sequential(
              ResNetConvLayer(__a,			__a,			stride=__a       ),			ResNetConvLayer(__a,			__a,			activation=__a       ),			)
          UpperCamelCase    :  Union[str, Any]							=	ACTaFN[activation]






       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_       )     ->		Dict:
          UpperCamelCase    :  int							=	hidden_state
          UpperCamelCase    :  Dict							=	self.layer(__a       )
          UpperCamelCase    :  Optional[int]							=	self.shortcut(__a       )
          hidden_state += residual
          UpperCamelCase    :  Tuple							=	self.activation(__a       )
          return hidden_state






class 				lowerCAmelCase_		(  nn.Module							):
       def __init__(			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_ = 1,			SCREAMING_SNAKE_CASE_ = "relu",			SCREAMING_SNAKE_CASE_ = 4       )     ->		List[str]:
          super().__init__()
          UpperCamelCase    :  int							=	in_channels != out_channels or stride != 1
          UpperCamelCase    :  str							=	out_channels // reduction
          UpperCamelCase    :  Optional[int]							=	(
              ResNetShortCut(__a,			__a,			stride=__a       ) if should_apply_shortcut else nn.Identity()
          )
          UpperCamelCase    :  Tuple							=	nn.Sequential(
              ResNetConvLayer(__a,			__a,			kernel_size=1       ),			ResNetConvLayer(__a,			__a,			stride=__a       ),			ResNetConvLayer(__a,			__a,			kernel_size=1,			activation=__a       ),			)
          UpperCamelCase    :  Optional[int]							=	ACTaFN[activation]






       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_       )     ->		Union[str, Any]:
          UpperCamelCase    :  Any							=	hidden_state
          UpperCamelCase    :  Any							=	self.layer(__a       )
          UpperCamelCase    :  str							=	self.shortcut(__a       )
          hidden_state += residual
          UpperCamelCase    :  int							=	self.activation(__a       )
          return hidden_state






class 				lowerCAmelCase_		(  nn.Module							):
       def __init__(			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_ = 2,			SCREAMING_SNAKE_CASE_ = 2,			)     ->		Any:
          super().__init__()

          UpperCamelCase    :  List[str]							=	ResNetBottleNeckLayer if config.layer_type == "bottleneck" else ResNetBasicLayer

          UpperCamelCase    :  Dict							=	nn.Sequential(
              # downsampling is done in the first layer with stride of 2
              layer(__a,			__a,			stride=__a,			activation=config.hidden_act       ),			*[layer(__a,			__a,			activation=config.hidden_act       ) for _ in range(depth - 1       )],			)






       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_       )     ->		Tuple:
          UpperCamelCase    :  Tuple							=	input
          for layer in self.layers:
             UpperCamelCase    :  Tuple							=	layer(__a       )
          return hidden_state






class 				lowerCAmelCase_		(  nn.Module							):
       def __init__(			self,			SCREAMING_SNAKE_CASE_       )     ->		Tuple:
          super().__init__()
          UpperCamelCase    :  Any							=	nn.ModuleList([]       )
          # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
          self.stages.append(
              ResNetStage(
                  __a,			config.embedding_size,			config.hidden_sizes[0],			stride=2 if config.downsample_in_first_stage else 1,			depth=config.depths[0],			)       )
          UpperCamelCase    :  Union[str, Any]							=	zip(config.hidden_sizes,			config.hidden_sizes[1:]       )
          for (in_channels, out_channels), depth in zip(__a,			config.depths[1:]       ):
             self.stages.append(ResNetStage(__a,			__a,			__a,			depth=__a       )       )






       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_ = False,			SCREAMING_SNAKE_CASE_ = True       )     ->		Any:
          UpperCamelCase    :  Optional[int]							=	() if output_hidden_states else None

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

             UpperCamelCase    :  List[str]							=	stage_module(__a       )

          if output_hidden_states:
             UpperCamelCase    :  str							=	hidden_states + (hidden_state,)

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

          return BaseModelOutputWithNoAttention(
              last_hidden_state=__a,			hidden_states=__a,			)






class 				lowerCAmelCase_		(  a__							):
       UpperCAmelCase__				:					Dict        =  ResNetConfig
       UpperCAmelCase__				:					Union[str, Any]        =  "resnet"
       UpperCAmelCase__				:					Dict        =  "pixel_values"
       UpperCAmelCase__				:					Tuple        =  True
       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_       )     ->		Any:

          if isinstance(__a,			nn.Convad       ):
             nn.init.kaiming_normal_(module.weight,			mode='fan_out',			nonlinearity='relu'       )
          elif isinstance(__a,			(nn.BatchNormad, nn.GroupNorm)       ):
             nn.init.constant_(module.weight,			1       )
             nn.init.constant_(module.bias,			0       )






       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_=False       )     ->		Optional[Any]:

          if isinstance(__a,			__a       ):
             UpperCamelCase    :  Tuple							=	value






__UpperCAmelCase          =       r'''\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'''

__UpperCAmelCase          =       r'''\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'''



@add_start_docstrings(
    "The bare ResNet model outputting raw features without any specific head on top."       ,    a__       ,    )
class 				lowerCAmelCase_		(  a__							):
       def __init__(			self,			SCREAMING_SNAKE_CASE_       )     ->		int:
          super().__init__(__a       )
          UpperCamelCase    :  Tuple							=	config
          UpperCamelCase    :  List[str]							=	ResNetEmbeddings(__a       )
          UpperCamelCase    :  List[str]							=	ResNetEncoder(__a       )
          UpperCamelCase    :  Any							=	nn.AdaptiveAvgPoolad((1, 1)       )
          # Initialize weights and apply final processing
          self.post_init()






       @add_start_docstrings_to_model_forward(__a       )
       @add_code_sample_docstrings(
           checkpoint=_CHECKPOINT_FOR_DOC,			output_type=__a,			config_class=_CONFIG_FOR_DOC,			modality='vision',			expected_output=_EXPECTED_OUTPUT_SHAPE,			)
       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_ = None,			SCREAMING_SNAKE_CASE_ = None       )     ->		Optional[int]:
          UpperCamelCase    :  Union[str, Any]							=	(
              output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
          )
          UpperCamelCase    :  List[str]							=	return_dict if return_dict is not None else self.config.use_return_dict

          UpperCamelCase    :  List[str]							=	self.embedder(__a       )

          UpperCamelCase    :  int							=	self.encoder(
              __a,			output_hidden_states=__a,			return_dict=__a       )

          UpperCamelCase    :  int							=	encoder_outputs[0]

          UpperCamelCase    :  List[Any]							=	self.pooler(__a       )

          if not return_dict:
             return (last_hidden_state, pooled_output) + encoder_outputs[1:]

          return BaseModelOutputWithPoolingAndNoAttention(
              last_hidden_state=__a,			pooler_output=__a,			hidden_states=encoder_outputs.hidden_states,			)






@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 				lowerCAmelCase_		(  a__							):
       def __init__(			self,			SCREAMING_SNAKE_CASE_       )     ->		Optional[int]:
          super().__init__(__a       )
          UpperCamelCase    :  Tuple							=	config.num_labels
          UpperCamelCase    :  str							=	ResNetModel(__a       )
          # classification head
          UpperCamelCase    :  str							=	nn.Sequential(
              nn.Flatten(),			nn.Linear(config.hidden_sizes[-1],			config.num_labels       ) if config.num_labels > 0 else nn.Identity(),			)
          # initialize weights and apply final processing
          self.post_init()






       @add_start_docstrings_to_model_forward(__a       )
       @add_code_sample_docstrings(
           checkpoint=_IMAGE_CLASS_CHECKPOINT,			output_type=__a,			config_class=_CONFIG_FOR_DOC,			expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,			)
       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_ = None,			SCREAMING_SNAKE_CASE_ = None,			SCREAMING_SNAKE_CASE_ = None,			SCREAMING_SNAKE_CASE_ = None,			)     ->		Optional[int]:
          UpperCamelCase    :  List[Any]							=	return_dict if return_dict is not None else self.config.use_return_dict

          UpperCamelCase    :  List[Any]							=	self.resnet(__a,			output_hidden_states=__a,			return_dict=__a       )

          UpperCamelCase    :  Tuple							=	outputs.pooler_output if return_dict else outputs[1]

          UpperCamelCase    :  int							=	self.classifier(__a       )

          UpperCamelCase    :  Optional[Any]							=	None

          if labels is not None:
             if self.config.problem_type is None:
                if self.num_labels == 1:
                   UpperCamelCase    :  Optional[int]							=	"regression"
                elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                   UpperCamelCase    :  Optional[Any]							=	"single_label_classification"
                else:
                   UpperCamelCase    :  Tuple							=	"multi_label_classification"
             if self.config.problem_type == "regression":
                UpperCamelCase    :  Optional[int]							=	MSELoss()
                if self.num_labels == 1:
                   UpperCamelCase    :  int							=	loss_fct(logits.squeeze(),			labels.squeeze()       )
                else:
                   UpperCamelCase    :  Optional[Any]							=	loss_fct(__a,			__a       )
             elif self.config.problem_type == "single_label_classification":
                UpperCamelCase    :  List[str]							=	CrossEntropyLoss()
                UpperCamelCase    :  Any							=	loss_fct(logits.view(-1,			self.num_labels       ),			labels.view(-1       )       )
             elif self.config.problem_type == "multi_label_classification":
                UpperCamelCase    :  Any							=	BCEWithLogitsLoss()
                UpperCamelCase    :  str							=	loss_fct(__a,			__a       )

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

          return ImageClassifierOutputWithNoAttention(loss=__a,			logits=__a,			hidden_states=outputs.hidden_states       )






@add_start_docstrings(
    "\n    ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n    "       ,    a__       ,    )
class 				lowerCAmelCase_		(  a__       ,    a__							):
       def __init__(			self,			SCREAMING_SNAKE_CASE_       )     ->		int:
          super().__init__(__a       )
          super()._init_backbone(__a       )

          UpperCamelCase    :  Dict							=	[config.embedding_size] + config.hidden_sizes
          UpperCamelCase    :  List[Any]							=	ResNetEmbeddings(__a       )
          UpperCamelCase    :  Union[str, Any]							=	ResNetEncoder(__a       )

          # initialize weights and apply final processing
          self.post_init()






       @add_start_docstrings_to_model_forward(__a       )
       @replace_return_docstrings(output_type=__a,			config_class=_CONFIG_FOR_DOC       )
       def 					snake_case_       (			self,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_ = None,			SCREAMING_SNAKE_CASE_ = None       )     ->		str:
          UpperCamelCase    :  Tuple							=	return_dict if return_dict is not None else self.config.use_return_dict
          UpperCamelCase    :  Optional[Any]							=	(
              output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
          )

          UpperCamelCase    :  Union[str, Any]							=	self.embedder(__a       )

          UpperCamelCase    :  Union[str, Any]							=	self.encoder(__a,			output_hidden_states=__a,			return_dict=__a       )

          UpperCamelCase    :  Tuple							=	outputs.hidden_states

          UpperCamelCase    :  Dict							=	()
          for idx, stage in enumerate(self.stage_names       ):
             if stage in self.out_features:
                feature_maps += (hidden_states[idx],)

          if not return_dict:
             UpperCamelCase    :  str							=	(feature_maps,)
             if output_hidden_states:
                output += (outputs.hidden_states,)
             return output

          return BackboneOutput(
              feature_maps=__a,			hidden_states=outputs.hidden_states if output_hidden_states else None,			attentions=__a,			)








from PIL import Image






def 				A				(					_lowerCamelCase  ):





							'''simple docstring'''




							_lowerCAmelCase   ,    _lowerCAmelCase     :							int    =    image.size
							_lowerCAmelCase     :							Any    =    0
							_lowerCAmelCase     :							Tuple    =    image.load()
							for i in range(_lowerCamelCase  ):
														for j in range(_lowerCamelCase  ):
																					_lowerCAmelCase     :							Union[str, Any]    =    pixels[j, i]
																					mean += pixel
							mean //= width * height

							for j in range(_lowerCamelCase  ):
														for i in range(_lowerCamelCase  ):
																					_lowerCAmelCase     :							Optional[Any]    =    255 if pixels[i, j] > mean else 0
							return image


if __name__ == "__main__":
						_snake_case		=  mean_threshold(Image.open("path_to_image").convert("L"))
						image.save("output_image_path")
