




import collections
import inspect
import unittest
from typing import Dict, List, Tuple

from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import MaskFormerSwinBackbone
 from transformers.models.maskformer import MaskFormerSwinModel

class  _lowerCamelCase						:

      """simple docstring"""

      def __init__(     self					: List[Any] ,       snake_case					: Dict ,       snake_case					: Any=13 ,       snake_case					: Dict=32 ,       snake_case					: List[Any]=2 ,       snake_case					: Optional[int]=3 ,       snake_case					: Optional[int]=16 ,       snake_case					: Dict=[1, 2, 1] ,       snake_case					: List[Any]=[2, 2, 4] ,       snake_case					: str=2 ,       snake_case					: Dict=2.0 ,       snake_case					: Dict=True ,       snake_case					: Tuple=0.0 ,       snake_case					: int=0.0 ,       snake_case					: List[Any]=0.1 ,       snake_case					: Any="gelu" ,       snake_case					: int=False ,       snake_case					: List[Any]=True ,       snake_case					: List[str]=0.02 ,       snake_case					: Union[str, Any]=1E-5 ,       snake_case					: Union[str, Any]=True ,       snake_case					: List[Any]=None ,       snake_case					: Tuple=True ,       snake_case					: Optional[int]=10 ,       snake_case					: Any=8 ,       snake_case					: Optional[int]=["stage1", "stage2", "stage3"] ,       snake_case					: str=[1, 2, 3] ,       ):
          __UpperCamelCase  		=						parent
          __UpperCamelCase  		=						batch_size
          __UpperCamelCase  		=						image_size
          __UpperCamelCase  		=						patch_size
          __UpperCamelCase  		=						num_channels
          __UpperCamelCase  		=						embed_dim
          __UpperCamelCase  		=						depths
          __UpperCamelCase  		=						num_heads
          __UpperCamelCase  		=						window_size
          __UpperCamelCase  		=						mlp_ratio
          __UpperCamelCase  		=						qkv_bias
          __UpperCamelCase  		=						hidden_dropout_prob
          __UpperCamelCase  		=						attention_probs_dropout_prob
          __UpperCamelCase  		=						drop_path_rate
          __UpperCamelCase  		=						hidden_act
          __UpperCamelCase  		=						use_absolute_embeddings
          __UpperCamelCase  		=						patch_norm
          __UpperCamelCase  		=						layer_norm_eps
          __UpperCamelCase  		=						initializer_range
          __UpperCamelCase  		=						is_training
          __UpperCamelCase  		=						scope
          __UpperCamelCase  		=						use_labels
          __UpperCamelCase  		=						type_sequence_label_size
          __UpperCamelCase  		=						encoder_stride
          __UpperCamelCase  		=						out_features
          __UpperCamelCase  		=						out_indices







      def       snake_case	(     self					: str				):
          __UpperCamelCase  		=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

          __UpperCamelCase  		=						None
          if self.use_labels:
              __UpperCamelCase  		=						ids_tensor([self.batch_size] ,       self.type_sequence_label_size				)

          __UpperCamelCase  		=						self.get_config()

          return config, pixel_values, labels







      def       snake_case	(     self					: Any				):
          return MaskFormerSwinConfig(
              image_size=self.image_size ,       patch_size=self.patch_size ,       num_channels=self.num_channels ,       embed_dim=self.embed_dim ,       depths=self.depths ,       num_heads=self.num_heads ,       window_size=self.window_size ,       mlp_ratio=self.mlp_ratio ,       qkv_bias=self.qkv_bias ,       hidden_dropout_prob=self.hidden_dropout_prob ,       attention_probs_dropout_prob=self.attention_probs_dropout_prob ,       drop_path_rate=self.drop_path_rate ,       hidden_act=self.hidden_act ,       use_absolute_embeddings=self.use_absolute_embeddings ,       path_norm=self.patch_norm ,       layer_norm_eps=self.layer_norm_eps ,       initializer_range=self.initializer_range ,       encoder_stride=self.encoder_stride ,       out_features=self.out_features ,       out_indices=self.out_indices ,       )







      def       snake_case	(     self					: str ,       snake_case					: Optional[Any] ,       snake_case					: List[Any] ,       snake_case					: List[Any]				):
          __UpperCamelCase  		=						MaskFormerSwinModel(config=UpperCAmelCase_				)
          model.to(UpperCAmelCase_				)
          model.eval()
          __UpperCamelCase  		=						model(UpperCAmelCase_				)

          __UpperCamelCase  		=						((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths				) - 1))
          __UpperCamelCase  		=						int(config.embed_dim * 2 ** (len(config.depths				) - 1)				)

          self.parent.assertEqual(result.last_hidden_state.shape ,       (self.batch_size, expected_seq_len, expected_dim)				)







      def       snake_case	(     self					: Optional[int] ,       snake_case					: str ,       snake_case					: str ,       snake_case					: Tuple				):
          __UpperCamelCase  		=						MaskFormerSwinBackbone(config=UpperCAmelCase_				)
          model.to(UpperCAmelCase_				)
          model.eval()
          __UpperCamelCase  		=						model(UpperCAmelCase_				)

          # verify feature maps
          self.parent.assertEqual(len(result.feature_maps				) ,       len(config.out_features				)				)
          self.parent.assertListEqual(list(result.feature_maps[0].shape				) ,       [13, 16, 16, 16]				)

          # verify channels
          self.parent.assertEqual(len(model.channels				) ,       len(config.out_features				)				)
          self.parent.assertListEqual(model.channels ,       [16, 32, 64]				)

          # verify ValueError
          with self.parent.assertRaises(UpperCAmelCase_				):
              __UpperCamelCase  		=						['''stem''']
              __UpperCamelCase  		=						MaskFormerSwinBackbone(config=UpperCAmelCase_				)







      def       snake_case	(     self					: Any				):
          __UpperCamelCase  		=						self.prepare_config_and_inputs()
          __UpperCamelCase		,      __UpperCamelCase		,      __UpperCamelCase  		=						config_and_inputs
          __UpperCamelCase  		=						{'''pixel_values''': pixel_values}
          return config, inputs_dict

@require_torch
class  _lowerCamelCase						(			snake_case__							,			snake_case__							,			unittest.TestCase   ):

      """simple docstring"""

      lowerCAmelCase__			: Optional[Any]    =					(
          (
              MaskFormerSwinModel,
              MaskFormerSwinBackbone,
          )
          if is_torch_available()
          else ()
      )
      lowerCAmelCase__			: Tuple    =					{"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {}
      lowerCAmelCase__			: Tuple    =					False
      lowerCAmelCase__			: Optional[int]    =					False
      lowerCAmelCase__			: Dict    =					False
      lowerCAmelCase__			: int    =					False
      lowerCAmelCase__			: List[str]    =					False







      def       snake_case	(     self					: Optional[Any]				):
          __UpperCamelCase  		=						MaskFormerSwinModelTester(self				)
          __UpperCamelCase  		=						ConfigTester(self ,       config_class=UpperCAmelCase_ ,       embed_dim=37				)







      @require_torch_multi_gpu
      @unittest.skip(
          reason=(
              '''`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with'''
              ''' `nn.DataParallel`'''
          )				)
      def       snake_case	(     self					: int				):
          pass







      def       snake_case	(     self					: int				):
          self.create_and_test_config_common_properties()
          self.config_tester.create_and_test_config_to_json_string()
          self.config_tester.create_and_test_config_to_json_file()
          self.config_tester.create_and_test_config_from_and_save_pretrained()
          self.config_tester.create_and_test_config_with_num_labels()
          self.config_tester.check_config_can_be_init_without_params()
          self.config_tester.check_config_arguments_init()







      def       snake_case	(     self					: Any				):
          return







      def       snake_case	(     self					: List[Any]				):
          __UpperCamelCase  		=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*UpperCAmelCase_				)







      def       snake_case	(     self					: Dict				):
          __UpperCamelCase  		=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_backbone(*UpperCAmelCase_				)







      @unittest.skip('''Swin does not use inputs_embeds'''				)
      def       snake_case	(     self					: Optional[Any]				):
          pass







      @unittest.skip('''Swin does not support feedforward chunking'''				)
      def       snake_case	(     self					: Any				):
          pass







      def       snake_case	(     self					: List[Any]				):
          __UpperCamelCase		,      __UpperCamelCase  		=						self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              __UpperCamelCase  		=						model_class(UpperCAmelCase_				)
              self.assertIsInstance(model.get_input_embeddings() ,       (nn.Module)				)
              __UpperCamelCase  		=						model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(UpperCAmelCase_ ,       nn.Linear				)				)







      def       snake_case	(     self					: Optional[Any]				):
          __UpperCamelCase		,      __UpperCamelCase  		=						self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              __UpperCamelCase  		=						model_class(UpperCAmelCase_				)
              __UpperCamelCase  		=						inspect.signature(model.forward				)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              __UpperCamelCase  		=						[*signature.parameters.keys()]

              __UpperCamelCase  		=						['''pixel_values''']
              self.assertListEqual(arg_names[:1] ,       UpperCAmelCase_				)







      @unittest.skip(reason='''MaskFormerSwin is only used as backbone and doesn\'t support output_attentions'''				)
      def       snake_case	(     self					: List[str]				):
          pass







      @unittest.skip(reason='''MaskFormerSwin is only used as an internal backbone'''				)
      def       snake_case	(     self					: int				):
          pass







      def       snake_case	(     self					: Dict ,       snake_case					: Tuple ,       snake_case					: Optional[int] ,       snake_case					: Optional[Any] ,       snake_case					: Optional[Any]				):
          __UpperCamelCase  		=						model_class(UpperCAmelCase_				)
          model.to(UpperCAmelCase_				)
          model.eval()

          with torch.no_grad():
              __UpperCamelCase  		=						model(**self._prepare_for_class(UpperCAmelCase_ ,       UpperCAmelCase_				)				)

          __UpperCamelCase  		=						outputs.hidden_states

          __UpperCamelCase  		=						getattr(
              self.model_tester ,       '''expected_num_hidden_layers''' ,       len(self.model_tester.depths				) + 1				)
          self.assertEqual(len(UpperCAmelCase_				) ,       UpperCAmelCase_				)

          # Swin has a different seq_length
          __UpperCamelCase  		=						(
              config.patch_size
              if isinstance(config.patch_size ,       collections.abc.Iterable				)
              else (config.patch_size, config.patch_size)
          )

          __UpperCamelCase  		=						(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

          self.assertListEqual(
              list(hidden_states[0].shape[-2:]				) ,       [num_patches, self.model_tester.embed_dim] ,       )







      def       snake_case	(     self					: Optional[Any]				):
          __UpperCamelCase		,      __UpperCamelCase  		=						self.model_tester.prepare_config_and_inputs_for_common()

          __UpperCamelCase  		=						(
              self.model_tester.image_size
              if isinstance(self.model_tester.image_size ,       collections.abc.Iterable				)
              else (self.model_tester.image_size, self.model_tester.image_size)
          )

          for model_class in self.all_model_classes:
              __UpperCamelCase  		=						True
              self.check_hidden_states_output(UpperCAmelCase_ ,       UpperCAmelCase_ ,       UpperCAmelCase_ ,       UpperCAmelCase_				)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              __UpperCamelCase  		=						True

              self.check_hidden_states_output(UpperCAmelCase_ ,       UpperCAmelCase_ ,       UpperCAmelCase_ ,       UpperCAmelCase_				)







      def       snake_case	(     self					: Optional[int]				):
          __UpperCamelCase		,      __UpperCamelCase  		=						self.model_tester.prepare_config_and_inputs_for_common()
          __UpperCamelCase  		=						3

          __UpperCamelCase  		=						(
              self.model_tester.image_size
              if isinstance(self.model_tester.image_size ,       collections.abc.Iterable				)
              else (self.model_tester.image_size, self.model_tester.image_size)
          )
          __UpperCamelCase  		=						(
              config.patch_size
              if isinstance(config.patch_size ,       collections.abc.Iterable				)
              else (config.patch_size, config.patch_size)
          )

          __UpperCamelCase  		=						image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
          __UpperCamelCase  		=						image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

          for model_class in self.all_model_classes:
              __UpperCamelCase  		=						True
              self.check_hidden_states_output(UpperCAmelCase_ ,       UpperCAmelCase_ ,       UpperCAmelCase_ ,       (padded_height, padded_width)				)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              __UpperCamelCase  		=						True
              self.check_hidden_states_output(UpperCAmelCase_ ,       UpperCAmelCase_ ,       UpperCAmelCase_ ,       (padded_height, padded_width)				)







      @unittest.skip(reason='''MaskFormerSwin doesn\'t have pretrained checkpoints'''				)
      def       snake_case	(     self					: str				):
          pass







      @unittest.skip(reason='''This will be fixed once MaskFormerSwin is replaced by native Swin'''				)
      def       snake_case	(     self					: Optional[int]				):
          pass







      @unittest.skip(reason='''This will be fixed once MaskFormerSwin is replaced by native Swin'''				)
      def       snake_case	(     self					: int				):
          pass







      def       snake_case	(     self					: List[str]				):
          __UpperCamelCase		,      __UpperCamelCase  		=						self.model_tester.prepare_config_and_inputs_for_common()

          def set_nan_tensor_to_zero(snake_case					: List[Any]				):
              __UpperCamelCase  		=						0
              return t

          def check_equivalence(snake_case					: str ,       snake_case					: List[Any] ,       snake_case					: int ,       snake_case					: Optional[int]={}				):
              with torch.no_grad():
                  __UpperCamelCase  		=						model(**UpperCAmelCase_ ,       return_dict=UpperCAmelCase_ ,       **UpperCAmelCase_				)
                  __UpperCamelCase  		=						model(**UpperCAmelCase_ ,       return_dict=UpperCAmelCase_ ,       **UpperCAmelCase_				).to_tuple()

                  def recursive_check(snake_case					: Any ,       snake_case					: Optional[int]				):
                      if isinstance(UpperCAmelCase_ ,       (List, Tuple)				):
                          for tuple_iterable_value, dict_iterable_value in zip(UpperCAmelCase_ ,       UpperCAmelCase_				):
                              recursive_check(UpperCAmelCase_ ,       UpperCAmelCase_				)
                      elif isinstance(UpperCAmelCase_ ,       UpperCAmelCase_				):
                          for tuple_iterable_value, dict_iterable_value in zip(
                              tuple_object.values() ,       dict_object.values()				):
                              recursive_check(UpperCAmelCase_ ,       UpperCAmelCase_				)
                      elif tuple_object is None:
                          return
                      else:
                          self.assertTrue(
                              torch.allclose(
                                  set_nan_tensor_to_zero(UpperCAmelCase_				) ,       set_nan_tensor_to_zero(UpperCAmelCase_				) ,       atol=1E-5				) ,       msg=(
                                  '''Tuple and dict output are not equal. Difference:'''
                                  F" {torch.max(torch.abs(tuple_object - dict_object				)				)}. Tuple has `nan`:"
                                  F" {torch.isnan(UpperCAmelCase_				).any()} and `inf`: {torch.isinf(UpperCAmelCase_				)}. Dict has"
                                  F" `nan`: {torch.isnan(UpperCAmelCase_				).any()} and `inf`: {torch.isinf(UpperCAmelCase_				)}."
                              ) ,       )

                  recursive_check(UpperCAmelCase_ ,       UpperCAmelCase_				)

          for model_class in self.all_model_classes:
              __UpperCamelCase  		=						model_class(UpperCAmelCase_				)
              model.to(UpperCAmelCase_				)
              model.eval()

              __UpperCamelCase  		=						self._prepare_for_class(UpperCAmelCase_ ,       UpperCAmelCase_				)
              __UpperCamelCase  		=						self._prepare_for_class(UpperCAmelCase_ ,       UpperCAmelCase_				)
              check_equivalence(UpperCAmelCase_ ,       UpperCAmelCase_ ,       UpperCAmelCase_				)

              __UpperCamelCase  		=						self._prepare_for_class(UpperCAmelCase_ ,       UpperCAmelCase_ ,       return_labels=UpperCAmelCase_				)
              __UpperCamelCase  		=						self._prepare_for_class(UpperCAmelCase_ ,       UpperCAmelCase_ ,       return_labels=UpperCAmelCase_				)
              check_equivalence(UpperCAmelCase_ ,       UpperCAmelCase_ ,       UpperCAmelCase_				)

              __UpperCamelCase  		=						self._prepare_for_class(UpperCAmelCase_ ,       UpperCAmelCase_				)
              __UpperCamelCase  		=						self._prepare_for_class(UpperCAmelCase_ ,       UpperCAmelCase_				)
              check_equivalence(UpperCAmelCase_ ,       UpperCAmelCase_ ,       UpperCAmelCase_ ,       {'''output_hidden_states''': True}				)

              __UpperCamelCase  		=						self._prepare_for_class(UpperCAmelCase_ ,       UpperCAmelCase_ ,       return_labels=UpperCAmelCase_				)
              __UpperCamelCase  		=						self._prepare_for_class(UpperCAmelCase_ ,       UpperCAmelCase_ ,       return_labels=UpperCAmelCase_				)
              check_equivalence(UpperCAmelCase_ ,       UpperCAmelCase_ ,       UpperCAmelCase_ ,       {'''output_hidden_states''': True}				)

@require_torch
class  _lowerCamelCase						(			unittest.TestCase							,			snake_case__   ):

      """simple docstring"""

      lowerCAmelCase__			: Union[str, Any]    =					(MaskFormerSwinBackbone,) if is_torch_available() else ()
      lowerCAmelCase__			: Tuple    =					MaskFormerSwinConfig







      def       snake_case	(     self					: str				):
          __UpperCamelCase  		=						MaskFormerSwinModelTester(self				)







      def       snake_case	(     self					: Optional[Any]				):
          __UpperCamelCase		,      __UpperCamelCase  		=						self.model_tester.prepare_config_and_inputs_for_common()
          __UpperCamelCase  		=						inputs_dict['''pixel_values'''].shape[0]

          for backbone_class in self.all_model_classes:
              __UpperCamelCase  		=						backbone_class(UpperCAmelCase_				)
              backbone.to(UpperCAmelCase_				)
              backbone.eval()

              __UpperCamelCase  		=						backbone(**UpperCAmelCase_				)

              # Test default outputs and verify feature maps
              self.assertIsInstance(outputs.feature_maps ,       UpperCAmelCase_				)
              self.assertTrue(len(outputs.feature_maps				) == len(backbone.channels				)				)
              for feature_map, n_channels in zip(outputs.feature_maps ,       backbone.channels				):
                  self.assertTrue(feature_map.shape[:2] ,       (batch_size, n_channels)				)
              self.assertIsNone(outputs.hidden_states				)
              self.assertIsNone(outputs.attentions				)

              # Test output_hidden_states=True
              __UpperCamelCase  		=						backbone(**UpperCAmelCase_ ,       output_hidden_states=UpperCAmelCase_				)
              self.assertIsNotNone(outputs.hidden_states				)
              self.assertTrue(len(outputs.hidden_states				) ,       len(backbone.stage_names				)				)
              # We skip the stem layer
              for hidden_states, n_channels in zip(outputs.hidden_states[1:] ,       backbone.channels				):
                  for hidden_state in hidden_states:
                      # Hidden states are in the format (batch_size, (height * width), n_channels)
                      __UpperCamelCase		,      __UpperCamelCase		,      __UpperCamelCase  		=						hidden_state.shape
                      self.assertTrue((h_batch_size, h_n_channels) ,       (batch_size, n_channels)				)

            # Test output_attentions=True
              if self.has_attentions:
                  __UpperCamelCase  		=						backbone(**UpperCAmelCase_ ,       output_attentions=UpperCAmelCase_				)
                  self.assertIsNotNone(outputs.attentions				)












import sys
import webbrowser

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

if __name__ == "__main__":
 print("Googling.....")
 a_   		=     "https://www.google.com/search?q=" + " ".join(sys.argv[1:])
 a_   		=     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_0000):
   out_file.write(data)
 a_   		=     BeautifulSoup(res.text, "html.parser")
 a_   		=     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')}""")






