




from typing import List, Optional, Tuple, Union

import torch
from torch import nn
from torch.nn import CrossEntropyLoss

from ... import AutoBackbone
from ...modeling_outputs import SemanticSegmenterOutput
from ...modeling_utils import PreTrainedModel
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings
from ...utils.backbone_utils import BackboneMixin
from .configuration_upernet import UperNetConfig


_snake_case            = [
    "openmmlab/upernet-convnext-tiny",
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
_snake_case            = "UperNetConfig"







class 		lowercase							(     nn.Module	):

     def __init__(						self	,  _a	,  _a	,  _a	,  _a = 0	,  _a = False	,  _a = 1	,  )		->							Union[str, Any]:
           super().__init__()
           _A							:  Union[str, Any]    =		nn.Convad(
               in_channels=a_	,  out_channels=a_	,  kernel_size=a_	,  padding=a_	,  bias=a_	,  dilation=a_	,  )
           _A							:  Optional[int]    =		nn.BatchNormad(a_       )
           _A							:  Tuple    =		nn.ReLU()



     def       a__			(						self	,  _a       )		->							str:
           _A							:  Union[str, Any]    =		self.conv(a_       )
           _A							:  Optional[int]    =		self.batch_norm(a_       )
           _A							:  Dict    =		self.activation(a_       )

           return output







class 		lowercase							(     nn.Module	):

     def __init__(						self	,  _a	,  _a	,  _a       )		->							List[str]:
           super().__init__()
           _A							:  List[str]    =		[
               nn.AdaptiveAvgPoolad(a_       ),
               UperNetConvModule(a_	,  a_	,  kernel_size=1       ),
           ]
           for i, layer in enumerate(self.layers       ):
                 self.add_module(str(a_       )	,  a_       )



     def       a__			(						self	,  _a       )		->							int:
           _A							:  List[Any]    =		input
           for layer in self.layers:
                 _A							:  str    =		layer(a_       )
           return hidden_state







class 		lowercase							(     nn.Module	):

     def __init__(						self	,  _a	,  _a	,  _a	,  _a       )		->							Union[str, Any]:
           super().__init__()
           _A							:  List[str]    =		pool_scales
           _A							:  Optional[Any]    =		align_corners
           _A							:  List[Any]    =		in_channels
           _A							:  Dict    =		channels
           _A							:  Optional[int]    =		[]
           for i, pool_scale in enumerate(a_       ):
                 _A							:  Optional[int]    =		UperNetPyramidPoolingBlock(pool_scale=a_	,  in_channels=a_	,  channels=a_       )
                 self.blocks.append(a_       )
                 self.add_module(str(a_       )	,  a_       )



     def       a__			(						self	,  _a       )		->							List[Any]:
           _A							:  str    =		[]
           for ppm in self.blocks:
                 _A							:  Any    =		ppm(a_       )
                 _A							:  Dict    =		nn.functional.interpolate(
                     a_	,  size=x.size()[2:]	,  mode="""bilinear"""	,  align_corners=self.align_corners       )
                 ppm_outs.append(a_       )
           return ppm_outs







class 		lowercase							(     nn.Module	):

     def __init__(						self	,  _a	,  _a       )		->							Union[str, Any]:
           super().__init__()

           _A							:  Tuple    =		config
           _A							:  Tuple    =		config.pool_scales  # e.g. (1, 2, 3, 6)
           _A							:  str    =		in_channels
           _A							:  Dict    =		config.hidden_size
           _A							:  Any    =		False
           _A							:  List[Any]    =		nn.Convad(self.channels	,  config.num_labels	,  kernel_size=1       )

           # PSP Module
           _A							:  List[Any]    =		UperNetPyramidPoolingModule(
               self.pool_scales	,  self.in_channels[-1]	,  self.channels	,  align_corners=self.align_corners	,  )
           _A							:  int    =		UperNetConvModule(
               self.in_channels[-1] + len(self.pool_scales       ) * self.channels	,  self.channels	,  kernel_size=3	,  padding=1	,  )
           # FPN Module
           _A							:  str    =		nn.ModuleList()
           _A							:  Tuple    =		nn.ModuleList()
           for in_channels in self.in_channels[:-1]:  # skip the top layer
                 _A							:  List[Any]    =		UperNetConvModule(a_	,  self.channels	,  kernel_size=1       )
                 _A							:  Optional[Any]    =		UperNetConvModule(self.channels	,  self.channels	,  kernel_size=3	,  padding=1       )
                 self.lateral_convs.append(a_       )
                 self.fpn_convs.append(a_       )

           _A							:  str    =		UperNetConvModule(
               len(self.in_channels       ) * self.channels	,  self.channels	,  kernel_size=3	,  padding=1	,  )

     def       a__			(						self       )		->							Optional[Any]:
           self.apply(self._init_weights       )

     def       a__			(						self	,  _a       )		->							Tuple:



           if isinstance(a_	,  nn.Convad       ):
                 module.weight.data.normal_(mean=0.0	,  std=self.config.initializer_range       )
                 if module.bias is not None:
                       module.bias.data.zero_()

     def       a__			(						self	,  _a       )		->							List[Any]:
           _A							:  Optional[int]    =		inputs[-1]
           _A							:  Tuple    =		[x]
           psp_outs.extend(self.psp_modules(a_       )       )
           _A							:  Tuple    =		torch.cat(a_	,  dim=1       )
           _A							:  Optional[Any]    =		self.bottleneck(a_       )

           return output



     def       a__			(						self	,  _a       )		->							int:
           _A							:  int    =		[lateral_conv(encoder_hidden_states[i]       ) for i, lateral_conv in enumerate(self.lateral_convs       )]

           laterals.append(self.psp_forward(a_       )       )

           # build top-down path
           _A							:  List[str]    =		len(a_       )
           for i in range(used_backbone_levels - 1	,  0	,  -1       ):
                 _A							:  Dict    =		laterals[i - 1].shape[2:]
                 _A							:  Tuple    =		laterals[i - 1] + nn.functional.interpolate(
                     laterals[i]	,  size=a_	,  mode="""bilinear"""	,  align_corners=self.align_corners       )

           # build outputs
           _A							:  Optional[int]    =		[self.fpn_convs[i](laterals[i]       ) for i in range(used_backbone_levels - 1       )]
           # append psp feature
           fpn_outs.append(laterals[-1]       )

           for i in range(used_backbone_levels - 1	,  0	,  -1       ):
                 _A							:  int    =		nn.functional.interpolate(
                     fpn_outs[i]	,  size=fpn_outs[0].shape[2:]	,  mode="""bilinear"""	,  align_corners=self.align_corners       )
           _A							:  Optional[Any]    =		torch.cat(a_	,  dim=1       )
           _A							:  Any    =		self.fpn_bottleneck(a_       )
           _A							:  Dict    =		self.classifier(a_       )

           return output







class 		lowercase							(     nn.Module	):

     def __init__(						self	,  _a	,  _a = 2	,  _a = 3	,  _a = 1       )		->							Optional[int]:
           super().__init__()

           _A							:  List[Any]    =		config
           _A							:  Dict    =		config.auxiliary_in_channels
           _A							:  Dict    =		config.auxiliary_channels
           _A							:  int    =		config.auxiliary_num_convs
           _A							:  Any    =		config.auxiliary_concat_input
           _A							:  Union[str, Any]    =		in_index

           _A							:  int    =		(kernel_size // 2) * dilation
           _A							:  Tuple    =		[]
           convs.append(
               UperNetConvModule(
                   self.in_channels	,  self.channels	,  kernel_size=a_	,  padding=a_	,  dilation=a_       )       )
           for i in range(self.num_convs - 1       ):
                 convs.append(
                     UperNetConvModule(
                         self.channels	,  self.channels	,  kernel_size=a_	,  padding=a_	,  dilation=a_       )       )
           if self.num_convs == 0:
                 _A							:  str    =		nn.Identity()
           else:
                 _A							:  List[Any]    =		nn.Sequential(*a_       )
           if self.concat_input:
                 _A							:  Dict    =		UperNetConvModule(
                     self.in_channels + self.channels	,  self.channels	,  kernel_size=a_	,  padding=kernel_size // 2       )

           _A							:  Optional[Any]    =		nn.Convad(self.channels	,  config.num_labels	,  kernel_size=1       )

     def       a__			(						self       )		->							List[str]:
           self.apply(self._init_weights       )

     def       a__			(						self	,  _a       )		->							Optional[int]:



           if isinstance(a_	,  nn.Convad       ):
                 module.weight.data.normal_(mean=0.0	,  std=self.config.initializer_range       )
                 if module.bias is not None:
                       module.bias.data.zero_()



     def       a__			(						self	,  _a       )		->							Optional[int]:
           _A							:  Any    =		encoder_hidden_states[self.in_index]
           _A							:  Optional[Any]    =		self.convs(a_       )
           if self.concat_input:
                 _A							:  Any    =		self.conv_cat(torch.cat([hidden_states, output]	,  dim=1       )       )
           _A							:  str    =		self.classifier(a_       )
           return output







class 		lowercase							(     __a	):
     _a											=		UperNetConfig
     _a											=		"pixel_values"
     _a											=		True

     def       a__			(						self	,  _a       )		->							int:



           if isinstance(a_	,  a_       ):
                 module.backbone.init_weights()
                 module.decode_head.init_weights()
                 module.auxiliary_head.init_weights()

     def       a__			(						self       )		->							Union[str, Any]:
           self.backbone.init_weights()
           self.decode_head.init_weights()
           self.auxiliary_head.init_weights()



     def       a__			(						self	,  _a	,  _a=False       )		->							str:



           if isinstance(a_	,  a_       ):
                 _A							:  Union[str, Any]    =		value


_snake_case            = r"\n    Parameters:\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n        config ([`UperNetConfig`]): 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"

_snake_case            = r"\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n            [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n        output_attentions (`bool`, *optional*):\n            Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n            `attentions` under returned tensors for more detail.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n            returned tensors for 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(
    "UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.",__a,)
class 		lowercase							(     __a	):

     def __init__(						self	,  _a       )		->							Union[str, Any]:
           super().__init__(a_       )

           _A							:  Tuple    =		AutoBackbone.from_config(config.backbone_config       )

           # Semantic segmentation head(s)
           _A							:  int    =		UperNetHead(a_	,  in_channels=self.backbone.channels       )
           _A							:  Tuple    =		UperNetFCNHead(a_       ) if config.use_auxiliary_head else None

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



     @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("""batch_size, sequence_length"""       )       )
     @replace_return_docstrings(output_type=a_	,  config_class=_CONFIG_FOR_DOC       )
     def       a__			(						self	,  _a = None	,  _a = None	,  _a = None	,  _a = None	,  _a = None	,  )		->							Dict:
           _A							:  Dict    =		return_dict if return_dict is not None else self.config.use_return_dict
           _A							:  Optional[int]    =		(
               output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
           )
           _A							:  Tuple    =		output_attentions if output_attentions is not None else self.config.output_attentions

           _A							:  str    =		self.backbone.forward_with_filtered_kwargs(
               a_	,  output_hidden_states=a_	,  output_attentions=a_       )
           _A							:  Dict    =		outputs.feature_maps

           _A							:  Optional[Any]    =		self.decode_head(a_       )
           _A							:  int    =		nn.functional.interpolate(a_	,  size=pixel_values.shape[2:]	,  mode="""bilinear"""	,  align_corners=a_       )

           _A							:  Dict    =		None
           if self.auxiliary_head is not None:
                 _A							:  Optional[Any]    =		self.auxiliary_head(a_       )
                 _A							:  List[str]    =		nn.functional.interpolate(
                     a_	,  size=pixel_values.shape[2:]	,  mode="""bilinear"""	,  align_corners=a_       )

           _A							:  Any    =		None
           if labels is not None:
                 if self.config.num_labels == 1:
                       raise ValueError("""The number of labels should be greater than one"""       )
                 else:
                       # compute weighted loss
                       _A							:  str    =		CrossEntropyLoss(ignore_index=self.config.loss_ignore_index       )
                       _A							:  Any    =		loss_fct(a_	,  a_       )
                       _A							:  List[str]    =		loss_fct(a_	,  a_       )
                       _A							:  Optional[Any]    =		main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

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

           return SemanticSegmenterOutput(
               loss=a_	,  logits=a_	,  hidden_states=outputs.hidden_states	,  attentions=outputs.attentions	,  )







def        lowerCAmelCase_			(  snake_case_,snake_case_  ):
      _A							:  Union[str, Any]    =		""""""
      for i in table:
            res += inp[i - 1]
      return res







def        lowerCAmelCase_			(  snake_case_  ):
      return data[1:] + data[0]







def        lowerCAmelCase_			(  snake_case_,snake_case_  ):
      _A							:  Dict    =		""""""
      for i in range(len(snake_case_  )  ):
            if a[i] == b[i]:
                  res += "0"
            else:
                  res += "1"
      return res







def        lowerCAmelCase_			(  snake_case_,snake_case_  ):
      _A							:  int    =		int("""0b""" + data[0] + data[-1],2  )
      _A							:  Any    =		int("""0b""" + data[1:3],2  )
      return bin(s[row][col]  )[2:]







def        lowerCAmelCase_			(  snake_case_,snake_case_,snake_case_,snake_case_,snake_case_  ):
      _A							:  List[str]    =		message[:4]
      _A							:  List[Any]    =		message[4:]
      _A							:  Union[str, Any]    =		apply_table(snake_case_,snake_case_  )
      _A							:  List[Any]    =		xor(snake_case_,snake_case_  )
      _A							:  Optional[Any]    =		apply_sbox(snake_case_,temp[:4]  )  # noqa: E741
      _A							:  List[Any]    =		apply_sbox(snake_case_,temp[4:]  )
      _A							:  int    =		"""0""" * (2 - len(snake_case_  )) + l  # noqa: E741
      _A							:  Union[str, Any]    =		"""0""" * (2 - len(snake_case_  )) + r
      _A							:  List[Any]    =		apply_table(l + r,snake_case_  )
      _A							:  Any    =		xor(snake_case_,snake_case_  )
      return temp + right


if __name__ == "__main__":
  _snake_case            = input("Enter 10 bit key: ")
  _snake_case            = input("Enter 8 bit message: ")

  _snake_case            = [6, 3, 7, 4, 8, 5, 10, 9]
  _snake_case            = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
  _snake_case            = [2, 4, 3, 1]
  _snake_case            = [2, 6, 3, 1, 4, 8, 5, 7]
  _snake_case            = [4, 1, 3, 5, 7, 2, 8, 6]
  _snake_case            = [4, 1, 2, 3, 2, 3, 4, 1]
  _snake_case            = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]]
  _snake_case            = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]]

  # key generation
  _snake_case            = apply_table(key, paa_table)
  _snake_case            = temp[:5]
  _snake_case            = temp[5:]
  _snake_case            = left_shift(left)
  _snake_case            = left_shift(right)
  _snake_case            = apply_table(left + right, pa_table)
  _snake_case            = left_shift(left)
  _snake_case            = left_shift(right)
  _snake_case            = left_shift(left)
  _snake_case            = left_shift(right)
  _snake_case            = apply_table(left + right, pa_table)

  # encryption
  _snake_case            = apply_table(message, IP)
  _snake_case            = function(expansion, sa, sa, keya, temp)
  _snake_case            = temp[4:] + temp[:4]
  _snake_case            = function(expansion, sa, sa, keya, temp)
  _snake_case            = apply_table(temp, IP_inv)
  print("Cipher text is:", CT)

  # decryption
  _snake_case            = apply_table(CT, IP)
  _snake_case            = function(expansion, sa, sa, keya, temp)
  _snake_case            = temp[4:] + temp[:4]
  _snake_case            = function(expansion, sa, sa, keya, temp)
  _snake_case            = apply_table(temp, IP_inv)
  print("Plain text after decypting is:", PT)

