'''simple docstring'''




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					:		Optional[int]							      =		[
    """openmmlab/upernet-convnext-tiny""",
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
_UpperCamelCase					:		int							      =		"""UperNetConfig"""

class 	_lowercase(  nn.Module					):



   """simple docstring"""





   def __init__(				self:     Optional[Any]      ,a:     Optional[Any]      ,a:     Optional[Any]      ,a:     Union[str, Any]      ,a:     List[Any] = 0      ,a:     Union[str, Any] = False      ,a:     Optional[Any] = 1      ,):
    super().__init__()
    __UpperCAmelCase								=       nn.Convad(
        in_channels=lowerCAmelCase__      ,out_channels=lowerCAmelCase__      ,kernel_size=lowerCAmelCase__      ,padding=lowerCAmelCase__      ,bias=lowerCAmelCase__      ,dilation=lowerCAmelCase__      ,)
    __UpperCAmelCase								=       nn.BatchNormad(lowerCAmelCase__						)
    __UpperCAmelCase								=       nn.ReLU()





   def       snake_case						(				self:     Optional[int]      ,a:     Union[str, Any]						):
    __UpperCAmelCase								=       self.conv(lowerCAmelCase__						)
    __UpperCAmelCase								=       self.batch_norm(lowerCAmelCase__						)
    __UpperCAmelCase								=       self.activation(lowerCAmelCase__						)

    return output




class 	_lowercase(  nn.Module					):



   """simple docstring"""





   def __init__(				self:     Any      ,a:     str      ,a:     Dict      ,a:     Tuple						):
    super().__init__()
    __UpperCAmelCase								=       [
        nn.AdaptiveAvgPoolad(lowerCAmelCase__						),
        UperNetConvModule(lowerCAmelCase__      ,lowerCAmelCase__      ,kernel_size=1						),
    ]
    for i, layer in enumerate(self.layers						):
     self.add_module(str(lowerCAmelCase__						)      ,lowerCAmelCase__						)





   def       snake_case						(				self:     str      ,a:     str						):
    __UpperCAmelCase								=       input
    for layer in self.layers:
     __UpperCAmelCase								=       layer(lowerCAmelCase__						)
    return hidden_state




class 	_lowercase(  nn.Module					):



   """simple docstring"""





   def __init__(				self:     str      ,a:     Dict      ,a:     List[Any]      ,a:     Union[str, Any]      ,a:     List[Any]						):
    super().__init__()
    __UpperCAmelCase								=       pool_scales
    __UpperCAmelCase								=       align_corners
    __UpperCAmelCase								=       in_channels
    __UpperCAmelCase								=       channels
    __UpperCAmelCase								=       []
    for i, pool_scale in enumerate(lowerCAmelCase__						):
     __UpperCAmelCase								=       UperNetPyramidPoolingBlock(pool_scale=lowerCAmelCase__      ,in_channels=lowerCAmelCase__      ,channels=lowerCAmelCase__						)
     self.blocks.append(lowerCAmelCase__						)
     self.add_module(str(lowerCAmelCase__						)      ,lowerCAmelCase__						)





   def       snake_case						(				self:     Optional[Any]      ,a:     List[str]						):
    __UpperCAmelCase								=       []
    for ppm in self.blocks:
     __UpperCAmelCase								=       ppm(lowerCAmelCase__						)
     __UpperCAmelCase								=       nn.functional.interpolate(
         lowerCAmelCase__      ,size=x.size()[2:]      ,mode='bilinear'      ,align_corners=self.align_corners						)
     ppm_outs.append(lowerCAmelCase__						)
    return ppm_outs




class 	_lowercase(  nn.Module					):



   """simple docstring"""





   def __init__(				self:     int      ,a:     str      ,a:     str						):
    super().__init__()

    __UpperCAmelCase								=       config
    __UpperCAmelCase								=       config.pool_scales  # e.g. (1, 2, 3, 6)
    __UpperCAmelCase								=       in_channels
    __UpperCAmelCase								=       config.hidden_size
    __UpperCAmelCase								=       False
    __UpperCAmelCase								=       nn.Convad(self.channels      ,config.num_labels      ,kernel_size=1						)

    # PSP Module
    __UpperCAmelCase								=       UperNetPyramidPoolingModule(
        self.pool_scales      ,self.in_channels[-1]      ,self.channels      ,align_corners=self.align_corners      ,)
    __UpperCAmelCase								=       UperNetConvModule(
        self.in_channels[-1] + len(self.pool_scales						) * self.channels      ,self.channels      ,kernel_size=3      ,padding=1      ,)
    # FPN Module
    __UpperCAmelCase								=       nn.ModuleList()
    __UpperCAmelCase								=       nn.ModuleList()
    for in_channels in self.in_channels[:-1]:  # skip the top layer
     __UpperCAmelCase								=       UperNetConvModule(lowerCAmelCase__      ,self.channels      ,kernel_size=1						)
     __UpperCAmelCase								=       UperNetConvModule(self.channels      ,self.channels      ,kernel_size=3      ,padding=1						)
     self.lateral_convs.append(lowerCAmelCase__						)
     self.fpn_convs.append(lowerCAmelCase__						)

    __UpperCAmelCase								=       UperNetConvModule(
        len(self.in_channels						) * self.channels      ,self.channels      ,kernel_size=3      ,padding=1      ,)





   def       snake_case						(				self:     Optional[int]						):
    self.apply(self._init_weights						)





   def       snake_case						(				self:     List[Any]      ,a:     Optional[int]						):


    if isinstance(lowerCAmelCase__      ,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       snake_case						(				self:     Any      ,a:     Any						):
    __UpperCAmelCase								=       inputs[-1]
    __UpperCAmelCase								=       [x]
    psp_outs.extend(self.psp_modules(lowerCAmelCase__						)						)
    __UpperCAmelCase								=       torch.cat(lowerCAmelCase__      ,dim=1						)
    __UpperCAmelCase								=       self.bottleneck(lowerCAmelCase__						)

    return output





   def       snake_case						(				self:     Optional[int]      ,a:     str						):
    __UpperCAmelCase								=       [lateral_conv(encoder_hidden_states[i]						) for i, lateral_conv in enumerate(self.lateral_convs						)]

    laterals.append(self.psp_forward(lowerCAmelCase__						)						)

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

    # build outputs
    __UpperCAmelCase								=       [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						):
     __UpperCAmelCase								=       nn.functional.interpolate(
         fpn_outs[i]      ,size=fpn_outs[0].shape[2:]      ,mode='bilinear'      ,align_corners=self.align_corners						)
    __UpperCAmelCase								=       torch.cat(lowerCAmelCase__      ,dim=1						)
    __UpperCAmelCase								=       self.fpn_bottleneck(lowerCAmelCase__						)
    __UpperCAmelCase								=       self.classifier(lowerCAmelCase__						)

    return output




class 	_lowercase(  nn.Module					):



   """simple docstring"""





   def __init__(				self:     Optional[Any]      ,a:     Optional[int]      ,a:     List[str] = 2      ,a:     Tuple = 3      ,a:     Union[str, Any] = 1						):
    super().__init__()

    __UpperCAmelCase								=       config
    __UpperCAmelCase								=       config.auxiliary_in_channels
    __UpperCAmelCase								=       config.auxiliary_channels
    __UpperCAmelCase								=       config.auxiliary_num_convs
    __UpperCAmelCase								=       config.auxiliary_concat_input
    __UpperCAmelCase								=       in_index

    __UpperCAmelCase								=       (kernel_size // 2) * dilation
    __UpperCAmelCase								=       []
    convs.append(
        UperNetConvModule(
            self.in_channels      ,self.channels      ,kernel_size=lowerCAmelCase__      ,padding=lowerCAmelCase__      ,dilation=lowerCAmelCase__						)						)
    for i in range(self.num_convs - 1						):
     convs.append(
         UperNetConvModule(
             self.channels      ,self.channels      ,kernel_size=lowerCAmelCase__      ,padding=lowerCAmelCase__      ,dilation=lowerCAmelCase__						)						)
    if self.num_convs == 0:
     __UpperCAmelCase								=       nn.Identity()
    else:
     __UpperCAmelCase								=       nn.Sequential(*lowerCAmelCase__						)
    if self.concat_input:
     __UpperCAmelCase								=       UperNetConvModule(
         self.in_channels + self.channels      ,self.channels      ,kernel_size=lowerCAmelCase__      ,padding=kernel_size // 2						)

    __UpperCAmelCase								=       nn.Convad(self.channels      ,config.num_labels      ,kernel_size=1						)





   def       snake_case						(				self:     Optional[int]						):
    self.apply(self._init_weights						)





   def       snake_case						(				self:     Dict      ,a:     int						):


    if isinstance(lowerCAmelCase__      ,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       snake_case						(				self:     Optional[Any]      ,a:     Optional[Any]						):
    __UpperCAmelCase								=       encoder_hidden_states[self.in_index]
    __UpperCAmelCase								=       self.convs(lowerCAmelCase__						)
    if self.concat_input:
     __UpperCAmelCase								=       self.conv_cat(torch.cat([hidden_states, output]      ,dim=1						)						)
    __UpperCAmelCase								=       self.classifier(lowerCAmelCase__						)
    return output




class 	_lowercase(  _UpperCAmelCase					):



   """simple docstring"""





   __lowerCamelCase     =	UperNetConfig
   __lowerCamelCase     =	'''pixel_values'''
   __lowerCamelCase     =	True





   def       snake_case						(				self:     Optional[int]      ,a:     List[str]						):


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





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





   def       snake_case						(				self:     List[str]      ,a:     Any      ,a:     List[str]=False						):


    if isinstance(lowerCAmelCase__      ,lowerCAmelCase__						):
     __UpperCAmelCase								=       value




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

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

@add_start_docstrings(
    '''UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.''' ,_UpperCAmelCase ,)
class 	_lowercase(  _UpperCAmelCase					):



   """simple docstring"""





   def __init__(				self:     List[str]      ,a:     Union[str, Any]						):
    super().__init__(lowerCAmelCase__						)

    __UpperCAmelCase								=       AutoBackbone.from_config(config.backbone_config						)

    # Semantic segmentation head(s)
    __UpperCAmelCase								=       UperNetHead(lowerCAmelCase__      ,in_channels=self.backbone.channels						)
    __UpperCAmelCase								=       UperNetFCNHead(lowerCAmelCase__						) 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=lowerCAmelCase__      ,config_class=_CONFIG_FOR_DOC						)
   def       snake_case						(				self:     Any      ,a:     Optional[Any] = None      ,a:     List[Any] = None      ,a:     int = None      ,a:     Tuple = None      ,a:     Any = None      ,):
    __UpperCAmelCase								=       return_dict if return_dict is not None else self.config.use_return_dict
    __UpperCAmelCase								=       (
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    __UpperCAmelCase								=       output_attentions if output_attentions is not None else self.config.output_attentions

    __UpperCAmelCase								=       self.backbone.forward_with_filtered_kwargs(
        lowerCAmelCase__      ,output_hidden_states=lowerCAmelCase__      ,output_attentions=lowerCAmelCase__						)
    __UpperCAmelCase								=       outputs.feature_maps

    __UpperCAmelCase								=       self.decode_head(lowerCAmelCase__						)
    __UpperCAmelCase								=       nn.functional.interpolate(lowerCAmelCase__      ,size=pixel_values.shape[2:]      ,mode='bilinear'      ,align_corners=lowerCAmelCase__						)

    __UpperCAmelCase								=       None
    if self.auxiliary_head is not None:
     __UpperCAmelCase								=       self.auxiliary_head(lowerCAmelCase__						)
     __UpperCAmelCase								=       nn.functional.interpolate(
         lowerCAmelCase__      ,size=pixel_values.shape[2:]      ,mode='bilinear'      ,align_corners=lowerCAmelCase__						)

    __UpperCAmelCase								=       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
      __UpperCAmelCase								=       CrossEntropyLoss(ignore_index=self.config.loss_ignore_index						)
      __UpperCAmelCase								=       loss_fct(lowerCAmelCase__      ,lowerCAmelCase__						)
      __UpperCAmelCase								=       loss_fct(lowerCAmelCase__      ,lowerCAmelCase__						)
      __UpperCAmelCase								=       main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

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

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




import sys
import webbrowser

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

if __name__ == "__main__":
		print("""Googling.....""")
		__a    :	Tuple         =    """https://www.google.com/search?q=""" + """ """.join(sys.argv[1:])
		__a    :	List[str]         =    requests.get(url, headers={"""UserAgent""": UserAgent().random})
		# res.raise_for_status()
		with open("""project1a.html""", """wb""") as out_file:  # only for knowing the class
				for data in res.iter_content(1_0_0_0_0):
						out_file.write(data)
		__a    :	Dict         =    BeautifulSoup(res.text, """html.parser""")
		__a    :	Any         =    list(soup.select(""".eZt8xd"""))[:5]

		print(len(links))
		for link in links:
				if link.text == "Maps":
						webbrowser.open(link.get("""href"""))
				else:
						webbrowser.open(F'''https://google.com{link.get("href")}''')