


'''simple docstring'''
import inspect
import unittest

from transformers import YolosConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch
  from torch import nn

  from transformers import YolosForObjectDetection, YolosModel
  from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor




class      lowerCamelCase_  :






      def __init__(   self							:       Tuple		,		_A							:       Any		,		_A							:       List[str]=13		,		_A							:       Optional[int]=[30, 30]		,		_A							:       List[str]=2		,		_A							:       Union[str, Any]=3		,		_A							:       Union[str, Any]=True		,		_A							:       Optional[Any]=True		,		_A							:       Tuple=32		,		_A							:       Optional[Any]=5		,		_A							:       List[Any]=4		,		_A							:       Any=37		,		_A							:       List[str]="gelu"		,		_A							:       Tuple=0.1		,		_A							:       str=0.1		,		_A							:       Tuple=10		,		_A							:       List[Any]=0.0_2		,		_A							:       Any=3		,		_A							:       Optional[int]=None		,		_A							:       Tuple=8		,		_A							:       Optional[Any]=10		,		):


          '''simple docstring'''


          UpperCAmelCase__     :						List[str]						=							parent
          UpperCAmelCase__     :						Dict						=							batch_size
          UpperCAmelCase__     :						str						=							image_size
          UpperCAmelCase__     :						List[Any]						=							patch_size
          UpperCAmelCase__     :						str						=							num_channels
          UpperCAmelCase__     :						Any						=							is_training
          UpperCAmelCase__     :						Optional[int]						=							use_labels
          UpperCAmelCase__     :						str						=							hidden_size
          UpperCAmelCase__     :						Optional[Any]						=							num_hidden_layers
          UpperCAmelCase__     :						Dict						=							num_attention_heads
          UpperCAmelCase__     :						List[str]						=							intermediate_size
          UpperCAmelCase__     :						List[str]						=							hidden_act
          UpperCAmelCase__     :						str						=							hidden_dropout_prob
          UpperCAmelCase__     :						List[str]						=							attention_probs_dropout_prob
          UpperCAmelCase__     :						Optional[Any]						=							type_sequence_label_size
          UpperCAmelCase__     :						List[str]						=							initializer_range
          UpperCAmelCase__     :						str						=							num_labels
          UpperCAmelCase__     :						List[str]						=							scope
          UpperCAmelCase__     :						Union[str, Any]						=							n_targets
          UpperCAmelCase__     :						int						=							num_detection_tokens
          # we set the expected sequence length (which is used in several tests)
          # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
          UpperCAmelCase__     :						Any						=							(image_size[1] // patch_size) * (image_size[0] // patch_size)
          UpperCAmelCase__     :						Tuple						=							num_patches + 1 + self.num_detection_tokens






      def lowercase_				(   self							:       Any					):


          '''simple docstring'''


          UpperCAmelCase__     :						str						=							floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]					)

          UpperCAmelCase__     :						Optional[int]						=							None
          if self.use_labels:
              # labels is a list of Dict (each Dict being the labels for a given example in the batch)
              UpperCAmelCase__     :						List[Any]						=							[]
              for i in range(self.batch_size					):
                  UpperCAmelCase__     :						str						=							{}
                  UpperCAmelCase__     :						Optional[Any]						=							torch.randint(
                      high=self.num_labels		,		size=(self.n_targets,)		,		device=_A					)
                  UpperCAmelCase__     :						Union[str, Any]						=							torch.rand(self.n_targets		,		4		,		device=_A					)
                  labels.append(_A					)

          UpperCAmelCase__     :						List[Any]						=							self.get_config()

          return config, pixel_values, labels






      def lowercase_				(   self							:       Tuple					):


          '''simple docstring'''


          return YolosConfig(
              image_size=self.image_size		,		patch_size=self.patch_size		,		num_channels=self.num_channels		,		hidden_size=self.hidden_size		,		num_hidden_layers=self.num_hidden_layers		,		num_attention_heads=self.num_attention_heads		,		intermediate_size=self.intermediate_size		,		hidden_act=self.hidden_act		,		hidden_dropout_prob=self.hidden_dropout_prob		,		attention_probs_dropout_prob=self.attention_probs_dropout_prob		,		is_decoder=_A		,		initializer_range=self.initializer_range		,		num_detection_tokens=self.num_detection_tokens		,		num_labels=self.num_labels		,		)






      def lowercase_				(   self							:       Union[str, Any]		,		_A							:       int		,		_A							:       List[str]		,		_A							:       int					):


          '''simple docstring'''


          UpperCAmelCase__     :						List[Any]						=							YolosModel(config=_A					)
          model.to(_A					)
          model.eval()
          UpperCAmelCase__     :						List[Any]						=							model(_A					)
          self.parent.assertEqual(
              result.last_hidden_state.shape		,		(self.batch_size, self.expected_seq_len, self.hidden_size)					)






      def lowercase_				(   self							:       List[Any]		,		_A							:       Union[str, Any]		,		_A							:       Dict		,		_A							:       Dict					):


          '''simple docstring'''


          UpperCAmelCase__     :						List[str]						=							YolosForObjectDetection(_A					)
          model.to(_A					)
          model.eval()

          UpperCAmelCase__     :						Optional[Any]						=							model(pixel_values=_A					)
          UpperCAmelCase__     :						Dict						=							model(_A					)

          self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.num_detection_tokens, self.num_labels + 1)					)
          self.parent.assertEqual(result.pred_boxes.shape		,		(self.batch_size, self.num_detection_tokens, 4)					)

          UpperCAmelCase__     :						Dict						=							model(pixel_values=_A		,		labels=_A					)

          self.parent.assertEqual(result.loss.shape		,		()					)
          self.parent.assertEqual(result.logits.shape		,		(self.batch_size, self.num_detection_tokens, self.num_labels + 1)					)
          self.parent.assertEqual(result.pred_boxes.shape		,		(self.batch_size, self.num_detection_tokens, 4)					)






      def lowercase_				(   self							:       Any					):


          '''simple docstring'''


          UpperCAmelCase__     :						int						=							self.prepare_config_and_inputs()
          UpperCAmelCase__		,		UpperCAmelCase__		,		UpperCAmelCase__     :						str						=							config_and_inputs
          UpperCAmelCase__     :						Dict						=							{'''pixel_values''': pixel_values}
          return config, inputs_dict




@require_torch
class      lowerCamelCase_  (      __a	,			__a	,			unittest.TestCase ):
      lowerCAmelCase__							=	(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
      lowerCAmelCase__							=	(
          {'feature-extraction': YolosModel, 'object-detection': YolosForObjectDetection} if is_torch_available() else {}
      )

      lowerCAmelCase__							=	False
      lowerCAmelCase__							=	False
      lowerCAmelCase__							=	False
      lowerCAmelCase__							=	False






      def lowercase_				(   self							:       Union[str, Any]		,		_A							:       List[str]		,		_A							:       Union[str, Any]		,		_A							:       Any=False					):


          '''simple docstring'''


          UpperCAmelCase__     :						Tuple						=							super()._prepare_for_class(_A		,		_A		,		return_labels=_A					)

          if return_labels:
              if model_class.__name__ == "YolosForObjectDetection":
                  UpperCAmelCase__     :						int						=							[]
                  for i in range(self.model_tester.batch_size					):
                      UpperCAmelCase__     :						str						=							{}
                      UpperCAmelCase__     :						str						=							torch.ones(
                          size=(self.model_tester.n_targets,)		,		device=_A		,		dtype=torch.long					)
                      UpperCAmelCase__     :						str						=							torch.ones(
                          self.model_tester.n_targets		,		4		,		device=_A		,		dtype=torch.float					)
                      labels.append(_A					)
                  UpperCAmelCase__     :						str						=							labels

          return inputs_dict






      def lowercase_				(   self							:       Optional[Any]					):


          '''simple docstring'''


          UpperCAmelCase__     :						int						=							YolosModelTester(self					)
          UpperCAmelCase__     :						Optional[int]						=							ConfigTester(self		,		config_class=_A		,		has_text_modality=_A		,		hidden_size=37					)






      def lowercase_				(   self							:       Optional[Any]					):


          '''simple docstring'''


          self.config_tester.run_common_tests()






      def lowercase_				(   self							:       Union[str, Any]					):


          '''simple docstring'''


          pass






      def lowercase_				(   self							:       Optional[Any]					):


          '''simple docstring'''


          UpperCAmelCase__		,		UpperCAmelCase__     :						Tuple						=							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              UpperCAmelCase__     :						Any						=							model_class(_A					)
              self.assertIsInstance(model.get_input_embeddings()		,		(nn.Module)					)
              UpperCAmelCase__     :						Union[str, Any]						=							model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(_A		,		nn.Linear					)					)






      def lowercase_				(   self							:       Tuple					):


          '''simple docstring'''


          UpperCAmelCase__		,		UpperCAmelCase__     :						List[str]						=							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              UpperCAmelCase__     :						Dict						=							model_class(_A					)
              UpperCAmelCase__     :						Optional[Any]						=							inspect.signature(model.forward					)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              UpperCAmelCase__     :						List[str]						=							[*signature.parameters.keys()]

              UpperCAmelCase__     :						str						=							['''pixel_values''']
              self.assertListEqual(arg_names[:1]		,		_A					)






      def lowercase_				(   self							:       int					):


          '''simple docstring'''


          UpperCAmelCase__     :						Optional[int]						=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_A					)






      def lowercase_				(   self							:       int					):


          '''simple docstring'''


          UpperCAmelCase__		,		UpperCAmelCase__     :						Union[str, Any]						=							self.model_tester.prepare_config_and_inputs_for_common()
          UpperCAmelCase__     :						List[Any]						=							True

          # in YOLOS, the seq_len is different
          UpperCAmelCase__     :						Union[str, Any]						=							self.model_tester.expected_seq_len
          for model_class in self.all_model_classes:
              UpperCAmelCase__     :						Any						=							True
              UpperCAmelCase__     :						Any						=							False
              UpperCAmelCase__     :						List[Any]						=							True
              UpperCAmelCase__     :						Union[str, Any]						=							model_class(_A					)
              model.to(_A					)
              model.eval()
              with torch.no_grad():
                  UpperCAmelCase__     :						Optional[int]						=							model(**self._prepare_for_class(_A		,		_A					)					)
              UpperCAmelCase__     :						Any						=							outputs.attentions
              self.assertEqual(len(_A					)		,		self.model_tester.num_hidden_layers					)

              # check that output_attentions also work using config
              del inputs_dict["output_attentions"]
              UpperCAmelCase__     :						Union[str, Any]						=							True
              UpperCAmelCase__     :						int						=							model_class(_A					)
              model.to(_A					)
              model.eval()
              with torch.no_grad():
                  UpperCAmelCase__     :						Any						=							model(**self._prepare_for_class(_A		,		_A					)					)
              UpperCAmelCase__     :						str						=							outputs.attentions
              self.assertEqual(len(_A					)		,		self.model_tester.num_hidden_layers					)

              self.assertListEqual(
                  list(attentions[0].shape[-3:]					)		,		[self.model_tester.num_attention_heads, seq_len, seq_len]		,		)
              UpperCAmelCase__     :						str						=							len(_A					)

              # Check attention is always last and order is fine
              UpperCAmelCase__     :						Optional[int]						=							True
              UpperCAmelCase__     :						List[Any]						=							True
              UpperCAmelCase__     :						Optional[int]						=							model_class(_A					)
              model.to(_A					)
              model.eval()
              with torch.no_grad():
                  UpperCAmelCase__     :						List[str]						=							model(**self._prepare_for_class(_A		,		_A					)					)

              UpperCAmelCase__     :						Any						=							1
              self.assertEqual(out_len + added_hidden_states		,		len(_A					)					)

              UpperCAmelCase__     :						List[str]						=							outputs.attentions

              self.assertEqual(len(_A					)		,		self.model_tester.num_hidden_layers					)
              self.assertListEqual(
                  list(self_attentions[0].shape[-3:]					)		,		[self.model_tester.num_attention_heads, seq_len, seq_len]		,		)






      def lowercase_				(   self							:       Optional[int]					):


          '''simple docstring'''


          def check_hidden_states_output(_A							:       Optional[int]		,		_A							:       int		,		_A							:       List[str]					):
              UpperCAmelCase__     :						Union[str, Any]						=							model_class(_A					)
              model.to(_A					)
              model.eval()

              with torch.no_grad():
                  UpperCAmelCase__     :						str						=							model(**self._prepare_for_class(_A		,		_A					)					)

              UpperCAmelCase__     :						Optional[int]						=							outputs.hidden_states

              UpperCAmelCase__     :						List[str]						=							getattr(
                  self.model_tester		,		'''expected_num_hidden_layers'''		,		self.model_tester.num_hidden_layers + 1					)
              self.assertEqual(len(_A					)		,		_A					)

              # YOLOS has a different seq_length
              UpperCAmelCase__     :						Optional[Any]						=							self.model_tester.expected_seq_len

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

          UpperCAmelCase__		,		UpperCAmelCase__     :						Any						=							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              UpperCAmelCase__     :						int						=							True
              check_hidden_states_output(_A		,		_A		,		_A					)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              UpperCAmelCase__     :						Any						=							True

              check_hidden_states_output(_A		,		_A		,		_A					)






      def lowercase_				(   self							:       str					):


          '''simple docstring'''


          UpperCAmelCase__     :						List[str]						=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_object_detection(*_A					)






      @slow
      def lowercase_				(   self							:       Optional[Any]					):


          '''simple docstring'''


          for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase__     :						str						=							YolosModel.from_pretrained(_A					)
              self.assertIsNotNone(_A					)





def    a__			(   )       ->      Dict:
    UpperCAmelCase__     :						List[str]						=							Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
    return image







@require_torch
@require_vision
class      lowerCamelCase_  (      unittest.TestCase ):






      @cached_property
      def lowercase_				(   self							:       List[str]					):


          '''simple docstring'''


          return AutoImageProcessor.from_pretrained('''hustvl/yolos-small'''					) if is_vision_available() else None






      @slow
      def lowercase_				(   self							:       Optional[Any]					):


          '''simple docstring'''


          UpperCAmelCase__     :						List[Any]						=							YolosForObjectDetection.from_pretrained('''hustvl/yolos-small'''					).to(_A					)

          UpperCAmelCase__     :						Optional[Any]						=							self.default_image_processor
          UpperCAmelCase__     :						Dict						=							prepare_img()
          UpperCAmelCase__     :						Dict						=							image_processor(images=_A		,		return_tensors='''pt'''					).to(_A					)

          # forward pass
          with torch.no_grad():
              UpperCAmelCase__     :						Union[str, Any]						=							model(inputs.pixel_values					)

          # verify outputs
          UpperCAmelCase__     :						Any						=							torch.Size((1, 100, 92)					)
          self.assertEqual(outputs.logits.shape		,		_A					)

          UpperCAmelCase__     :						Dict						=							torch.tensor(
              [[-2_4.0_2_4_8, -1_0.3_0_2_4, -1_4.8_2_9_0], [-4_2.0_3_9_2, -1_6.8_2_0_0, -2_7.4_3_3_4], [-2_7.2_7_4_3, -1_1.8_1_5_4, -1_8.7_1_4_8]]		,		device=_A		,		)
          UpperCAmelCase__     :						Optional[Any]						=							torch.tensor(
              [[0.2_5_5_9, 0.5_4_5_5, 0.4_7_0_6], [0.2_9_8_9, 0.7_2_7_9, 0.1_8_7_5], [0.7_7_3_2, 0.4_0_1_7, 0.4_4_6_2]]		,		device=_A					)
          self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]		,		_A		,		atol=1e-4					)					)
          self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]		,		_A		,		atol=1e-4					)					)

          # verify postprocessing
          UpperCAmelCase__     :						Any						=							image_processor.post_process_object_detection(
              _A		,		threshold=0.3		,		target_sizes=[image.size[::-1]]					)[0]
          UpperCAmelCase__     :						str						=							torch.tensor([0.9_9_9_4, 0.9_7_9_0, 0.9_9_6_4, 0.9_9_7_2, 0.9_8_6_1]					).to(_A					)
          UpperCAmelCase__     :						Any						=							[75, 75, 17, 63, 17]
          UpperCAmelCase__     :						int						=							torch.tensor([3_3_5.0_6_0_9, 7_9.3_8_4_8, 3_7_5.4_2_1_6, 1_8_7.2_4_9_5]					).to(_A					)

          self.assertEqual(len(results['''scores''']					)		,		5					)
          self.assertTrue(torch.allclose(results['''scores''']		,		_A		,		atol=1e-4					)					)
          self.assertSequenceEqual(results['''labels'''].tolist()		,		_A					)
          self.assertTrue(torch.allclose(results['''boxes'''][0, :]		,		_A					)					)


'''simple docstring'''
import sys
import webbrowser

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

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




