


from __future__ import annotations

import math
from collections import Counter
from string import ascii_lowercase







def 	SCREAMING_SNAKE_CASE_						(      __A			:      str    )     ->		None:

       """simple docstring"""

       a_							,		a_ :		Dict							=  analyze_text(__A    )
       a_ :		Optional[Any]							=  list(' ' + ascii_lowercase    )
       # what is our total sum of probabilities.
       a_ :		List[str]							=  sum(single_char_strings.values()    )

       # one length string
       a_ :		Any							=  0
       # for each alpha we go in our dict and if it is in it we calculate entropy
       for ch in my_alphas:
              if ch in single_char_strings:
                     a_ :		Optional[Any]							=  single_char_strings[ch]
                     a_ :		Tuple							=  my_str / all_sum
                     my_fir_sum += prob * math.loga(__A    )  # entropy formula.

    # print entropy
       print(F"""{round(-1 * my_fir_sum    ):.1f}"""    )

       # two len string
       a_ :		Optional[Any]							=  sum(two_char_strings.values()    )
       a_ :		List[Any]							=  0
       # for each alpha (two in size) calculate entropy.
       for cha in my_alphas:
              for cha in my_alphas:
                     a_ :		Optional[Any]							=  cha + cha
                     if sequence in two_char_strings:
                            a_ :		str							=  two_char_strings[sequence]
                            a_ :		int							=  int(__A    ) / all_sum
                            my_sec_sum += prob * math.loga(__A    )

    # print second entropy
       print(F"""{round(-1 * my_sec_sum    ):.1f}"""    )

       # print the difference between them
       print(F"""{round((-1 * my_sec_sum) - (-1 * my_fir_sum)    ):.1f}"""    )







def 	SCREAMING_SNAKE_CASE_						(      __A			:      str    )     ->		tuple[dict, dict]:

       """simple docstring"""

       a_ :		Tuple							=  Counter()  # type: ignore
       a_ :		List[str]							=  Counter()  # type: ignore
       single_char_strings[text[-1]] += 1

       # first case when we have space at start.
       two_char_strings[" " + text[0]] += 1
       for i in range(0  ,   len(__A    ) - 1    ):
              single_char_strings[text[i]] += 1
              two_char_strings[text[i : i + 2]] += 1
       return single_char_strings, two_char_strings







def 	SCREAMING_SNAKE_CASE_						(      )     ->		Any:

       """simple docstring"""

       import doctest

       doctest.testmod()
       # text = (
       #     "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark "
       #     "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest "
       #     "jointure saw horrible. He private he on be imagine suppose. Fertile "
       #     "beloved evident through no service elderly is. Blind there if every no so "
       #     "at. Own neglected you preferred way sincerity delivered his attempted. To "
       #     "of message cottage windows do besides against uncivil.  Delightful "
       #     "unreserved impossible few estimating men favourable see entreaties. She "
       #     "propriety immediate was improving. He or entrance humoured likewise "
       #     "moderate. Much nor game son say feel. Fat make met can must form into "
       #     "gate. Me we offending prevailed discovery. "
       # )

       # calculate_prob(text)


if __name__ == "__main__":
   main()






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


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

# General docstring
UpperCAmelCase_				:			Dict   =	'UperNetConfig'
class 			SCREAMING_SNAKE_CASE__  (    nn.Module      ):
      def __init__(	self    :	int					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	Union[int, Tuple[int, int]]					,							SCREAMING_SNAKE_CASE__    :	Union[int, Tuple[int, int], str] = 0					,							SCREAMING_SNAKE_CASE__    :	bool = False					,							SCREAMING_SNAKE_CASE__    :	Union[int, Tuple[int, int]] = 1					,							)		->      None:
             super().__init__()
             a_ :		Dict							=  nn.Convad(
                 in_channels=SCREAMING_SNAKE_CASE__					,							out_channels=SCREAMING_SNAKE_CASE__					,							kernel_size=SCREAMING_SNAKE_CASE__					,							padding=SCREAMING_SNAKE_CASE__					,							bias=SCREAMING_SNAKE_CASE__					,							dilation=SCREAMING_SNAKE_CASE__					,							)
             a_ :		List[str]							=  nn.BatchNormad(SCREAMING_SNAKE_CASE__					)
             a_ :		Tuple							=  nn.ReLU()

      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	torch.Tensor					)		->      torch.Tensor:
             a_ :		int							=  self.conv(SCREAMING_SNAKE_CASE__					)
             a_ :		Optional[int]							=  self.batch_norm(SCREAMING_SNAKE_CASE__					)
             a_ :		List[Any]							=  self.activation(SCREAMING_SNAKE_CASE__					)

             return output
class 			SCREAMING_SNAKE_CASE__  (    nn.Module      ):
      def __init__(	self    :	str					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	int					)		->      None:
             super().__init__()
             a_ :		str							=  [
                 nn.AdaptiveAvgPoolad(SCREAMING_SNAKE_CASE__					),
                 UperNetConvModule(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					,							kernel_size=1					),
             ]
             for i, layer in enumerate(self.layers					):
                    self.add_module(str(SCREAMING_SNAKE_CASE__					)					,							SCREAMING_SNAKE_CASE__					)

      def 	SCREAMING_SNAKE_CASE							(	self    :	Any					,							SCREAMING_SNAKE_CASE__    :	torch.Tensor					)		->      torch.Tensor:
             a_ :		Optional[int]							=  input
             for layer in self.layers:
                    a_ :		int							=  layer(SCREAMING_SNAKE_CASE__					)
             return hidden_state
class 			SCREAMING_SNAKE_CASE__  (    nn.Module      ):
      def __init__(	self    :	Tuple					,							SCREAMING_SNAKE_CASE__    :	Tuple[int, ...]					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	int					,							SCREAMING_SNAKE_CASE__    :	bool					)		->      None:
             super().__init__()
             a_ :		Tuple							=  pool_scales
             a_ :		List[Any]							=  align_corners
             a_ :		Tuple							=  in_channels
             a_ :		Optional[Any]							=  channels
             a_ :		Tuple							=  []
             for i, pool_scale in enumerate(SCREAMING_SNAKE_CASE__					):
                    a_ :		Optional[int]							=  UperNetPyramidPoolingBlock(pool_scale=SCREAMING_SNAKE_CASE__					,							in_channels=SCREAMING_SNAKE_CASE__					,							channels=SCREAMING_SNAKE_CASE__					)
                    self.blocks.append(SCREAMING_SNAKE_CASE__					)
                    self.add_module(str(SCREAMING_SNAKE_CASE__					)					,							SCREAMING_SNAKE_CASE__					)

      def 	SCREAMING_SNAKE_CASE							(	self    :	Any					,							SCREAMING_SNAKE_CASE__    :	torch.Tensor					)		->      List[torch.Tensor]:
             a_ :		List[Any]							=  []
             for ppm in self.blocks:
                    a_ :		List[Any]							=  ppm(SCREAMING_SNAKE_CASE__					)
                    a_ :		str							=  nn.functional.interpolate(
                        SCREAMING_SNAKE_CASE__					,							size=x.size()[2:]					,							mode='bilinear'					,							align_corners=self.align_corners					)
                    ppm_outs.append(SCREAMING_SNAKE_CASE__					)
             return ppm_outs
class 			SCREAMING_SNAKE_CASE__  (    nn.Module      ):
      def __init__(	self    :	Tuple					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	str					)		->      Tuple:
             super().__init__()

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

             # PSP Module
             a_ :		int							=  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_ :		Dict							=  nn.ModuleList()
             for in_channels in self.in_channels[:-1]:  # skip the top layer
                    a_ :		str							=  UperNetConvModule(SCREAMING_SNAKE_CASE__					,							self.channels					,							kernel_size=1					)
                    a_ :		Union[str, Any]							=  UperNetConvModule(self.channels					,							self.channels					,							kernel_size=3					,							padding=1					)
                    self.lateral_convs.append(SCREAMING_SNAKE_CASE__					)
                    self.fpn_convs.append(SCREAMING_SNAKE_CASE__					)

             a_ :		Optional[int]							=  UperNetConvModule(
                 len(self.in_channels					) * self.channels					,							self.channels					,							kernel_size=3					,							padding=1					,							)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[Any]					)		->      str:
             self.apply(self._init_weights					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	List[str]					,							SCREAMING_SNAKE_CASE__    :	Dict					)		->      str:
             if isinstance(SCREAMING_SNAKE_CASE__					,							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 	SCREAMING_SNAKE_CASE							(	self    :	Optional[Any]					,							SCREAMING_SNAKE_CASE__    :	Tuple					)		->      Dict:
             a_ :		Dict							=  inputs[-1]
             a_ :		str							=  [x]
             psp_outs.extend(self.psp_modules(SCREAMING_SNAKE_CASE__					)					)
             a_ :		List[Any]							=  torch.cat(SCREAMING_SNAKE_CASE__					,							dim=1					)
             a_ :		Dict							=  self.bottleneck(SCREAMING_SNAKE_CASE__					)

             return output

      def 	SCREAMING_SNAKE_CASE							(	self    :	str					,							SCREAMING_SNAKE_CASE__    :	torch.Tensor					)		->      torch.Tensor:
             # build laterals
             a_ :		List[str]							=  [lateral_conv(encoder_hidden_states[i]					) for i, lateral_conv in enumerate(self.lateral_convs					)]

             laterals.append(self.psp_forward(SCREAMING_SNAKE_CASE__					)					)

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

             # build outputs
             a_ :		List[Any]							=  [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[int]							=  torch.cat(SCREAMING_SNAKE_CASE__					,							dim=1					)
             a_ :		Tuple							=  self.fpn_bottleneck(SCREAMING_SNAKE_CASE__					)
             a_ :		Dict							=  self.classifier(SCREAMING_SNAKE_CASE__					)

             return output
class 			SCREAMING_SNAKE_CASE__  (    nn.Module      ):
      def __init__(	self    :	int					,							SCREAMING_SNAKE_CASE__    :	Any					,							SCREAMING_SNAKE_CASE__    :	int = 2					,							SCREAMING_SNAKE_CASE__    :	int = 3					,							SCREAMING_SNAKE_CASE__    :	Union[int, Tuple[int, int]] = 1					)		->      None:
             super().__init__()

             a_ :		Optional[int]							=  config
             a_ :		str							=  config.auxiliary_in_channels
             a_ :		Optional[int]							=  config.auxiliary_channels
             a_ :		List[str]							=  config.auxiliary_num_convs
             a_ :		Dict							=  config.auxiliary_concat_input
             a_ :		int							=  in_index

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

             a_ :		List[str]							=  nn.Convad(self.channels					,							config.num_labels					,							kernel_size=1					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					)		->      List[str]:
             self.apply(self._init_weights					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	Union[str, Any]					,							SCREAMING_SNAKE_CASE__    :	Any					)		->      List[str]:
             if isinstance(SCREAMING_SNAKE_CASE__					,							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 	SCREAMING_SNAKE_CASE							(	self    :	Union[str, Any]					,							SCREAMING_SNAKE_CASE__    :	torch.Tensor					)		->      torch.Tensor:
             # just take the relevant feature maps
             a_ :		Optional[int]							=  encoder_hidden_states[self.in_index]
             a_ :		int							=  self.convs(SCREAMING_SNAKE_CASE__					)
             if self.concat_input:
                    a_ :		Optional[Any]							=  self.conv_cat(torch.cat([hidden_states, output]					,							dim=1					)					)
             a_ :		Dict							=  self.classifier(SCREAMING_SNAKE_CASE__					)
             return output
class 			SCREAMING_SNAKE_CASE__  (    lowercase__      ):
      snake_case__    :					Any					       =						UperNetConfig
      snake_case__    :					Optional[int]					       =						'''pixel_values'''
      snake_case__    :					Optional[int]					       =						True
      def 	SCREAMING_SNAKE_CASE							(	self    :	List[str]					,							SCREAMING_SNAKE_CASE__    :	Optional[Any]					)		->      str:
             if isinstance(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					):
                    module.backbone.init_weights()
                    module.decode_head.init_weights()
                    module.auxiliary_head.init_weights()
      def 	SCREAMING_SNAKE_CASE							(	self    :	Dict					)		->      Dict:
             self.backbone.init_weights()
             self.decode_head.init_weights()
             self.auxiliary_head.init_weights()

      def 	SCREAMING_SNAKE_CASE							(	self    :	Optional[int]					,							SCREAMING_SNAKE_CASE__    :	str					,							SCREAMING_SNAKE_CASE__    :	int=False					)		->      Any:
             if isinstance(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					):
                    a_ :		Dict							=  value
UpperCAmelCase_				:			int   =	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'

UpperCAmelCase_				:			Tuple   =	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.'''						,   lowercase__						,   )
class 			SCREAMING_SNAKE_CASE__  (    lowercase__      ):
      def __init__(	self    :	Union[str, Any]					,							SCREAMING_SNAKE_CASE__    :	Optional[int]					)		->      str:
             super().__init__(SCREAMING_SNAKE_CASE__					)

             a_ :		List[str]							=  AutoBackbone.from_config(config.backbone_config					)

             # Semantic segmentation head(s)
             a_ :		List[Any]							=  UperNetHead(SCREAMING_SNAKE_CASE__					,							in_channels=self.backbone.channels					)
             a_ :		Dict							=  UperNetFCNHead(SCREAMING_SNAKE_CASE__					) 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=SCREAMING_SNAKE_CASE__					,							config_class=_CONFIG_FOR_DOC					)
      def 	SCREAMING_SNAKE_CASE							(	self    :	List[Any]					,							SCREAMING_SNAKE_CASE__    :	Optional[torch.Tensor] = None					,							SCREAMING_SNAKE_CASE__    :	Optional[bool] = None					,							SCREAMING_SNAKE_CASE__    :	Optional[bool] = None					,							SCREAMING_SNAKE_CASE__    :	Optional[torch.Tensor] = None					,							SCREAMING_SNAKE_CASE__    :	Optional[bool] = None					,							)		->      Union[tuple, SemanticSegmenterOutput]:
             a_ :		Optional[Any]							=  return_dict if return_dict is not None else self.config.use_return_dict
             a_ :		Tuple							=  (
                 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
             )
             a_ :		int							=  output_attentions if output_attentions is not None else self.config.output_attentions

             a_ :		str							=  self.backbone.forward_with_filtered_kwargs(
                 SCREAMING_SNAKE_CASE__					,							output_hidden_states=SCREAMING_SNAKE_CASE__					,							output_attentions=SCREAMING_SNAKE_CASE__					)
             a_ :		Optional[int]							=  outputs.feature_maps

             a_ :		Tuple							=  self.decode_head(SCREAMING_SNAKE_CASE__					)
             a_ :		List[Any]							=  nn.functional.interpolate(SCREAMING_SNAKE_CASE__					,							size=pixel_values.shape[2:]					,							mode='bilinear'					,							align_corners=SCREAMING_SNAKE_CASE__					)

             a_ :		Union[str, Any]							=  None
             if self.auxiliary_head is not None:
                    a_ :		Any							=  self.auxiliary_head(SCREAMING_SNAKE_CASE__					)
                    a_ :		int							=  nn.functional.interpolate(
                        SCREAMING_SNAKE_CASE__					,							size=pixel_values.shape[2:]					,							mode='bilinear'					,							align_corners=SCREAMING_SNAKE_CASE__					)

             a_ :		List[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_ :		List[str]							=  CrossEntropyLoss(ignore_index=self.config.loss_ignore_index					)
                           a_ :		Optional[Any]							=  loss_fct(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					)
                           a_ :		str							=  loss_fct(SCREAMING_SNAKE_CASE__					,							SCREAMING_SNAKE_CASE__					)
                           a_ :		str							=  main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

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

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


