






'''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 UpperCAmelCase_					:




      """simple docstring"""




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


       '''simple docstring'''

       lowercase					:   int				  =parent
       lowercase					:   str				  =batch_size
       lowercase					:   List[Any]				  =image_size
       lowercase					:   Tuple				  =patch_size
       lowercase					:   str				  =num_channels
       lowercase					:   int				  =is_training
       lowercase					:   Dict				  =use_labels
       lowercase					:   Dict				  =hidden_size
       lowercase					:   Any				  =num_hidden_layers
       lowercase					:   Optional[Any]				  =num_attention_heads
       lowercase					:   Optional[int]				  =intermediate_size
       lowercase					:   int				  =hidden_act
       lowercase					:   Dict				  =hidden_dropout_prob
       lowercase					:   int				  =attention_probs_dropout_prob
       lowercase					:   List[str]				  =type_sequence_label_size
       lowercase					:   Any				  =initializer_range
       lowercase					:   str				  =num_labels
       lowercase					:   str				  =scope
       lowercase					:   Dict				  =n_targets
       lowercase					:   Any				  =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
       lowercase					:   int				  =(image_size[1] // patch_size) * (image_size[0] // patch_size)
       lowercase					:   Tuple				  =num_patches + 1 + self.num_detection_tokens






      def 				A__      ( self			:		Tuple		)  ->  List[str]:


       '''simple docstring'''

       lowercase					:   List[Any]				  =floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]		)

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

       lowercase					:   Any				  =self.get_config()

       return config, pixel_values, labels






      def 				A__      ( self			:		Optional[Any]		)  ->  Optional[Any]:


       '''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=UpperCAmelCase     ,      initializer_range=self.initializer_range     ,      num_detection_tokens=self.num_detection_tokens     ,      num_labels=self.num_labels     ,      )






      def 				A__      ( self			:		str     ,      UpperCAmelCase			:		List[str]     ,      UpperCAmelCase			:		List[Any]     ,      UpperCAmelCase			:		List[str]		)  ->  Tuple:


       '''simple docstring'''

       lowercase					:   Optional[Any]				  =YolosModel(config=UpperCAmelCase		)
       model.to(UpperCAmelCase		)
       model.eval()
       lowercase					:   Dict				  =model(UpperCAmelCase		)
       self.parent.assertEqual(
           result.last_hidden_state.shape     ,      (self.batch_size, self.expected_seq_len, self.hidden_size)		)






      def 				A__      ( self			:		Optional[Any]     ,      UpperCAmelCase			:		List[Any]     ,      UpperCAmelCase			:		Dict     ,      UpperCAmelCase			:		Dict		)  ->  Any:


       '''simple docstring'''

       lowercase					:   Tuple				  =YolosForObjectDetection(UpperCAmelCase		)
       model.to(UpperCAmelCase		)
       model.eval()

       lowercase					:   Tuple				  =model(pixel_values=UpperCAmelCase		)
       lowercase					:   str				  =model(UpperCAmelCase		)

       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)		)

       lowercase					:   str				  =model(pixel_values=UpperCAmelCase     ,      labels=UpperCAmelCase		)

       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 				A__      ( self			:		str		)  ->  List[Any]:


       '''simple docstring'''

       lowercase					:   Dict				  =self.prepare_config_and_inputs()
       lowercase  ,		lowercase  ,		lowercase					:   Union[str, Any]				  =config_and_inputs
       lowercase					:   Union[str, Any]				  ={'''pixel_values''': pixel_values}
       return config, inputs_dict





@require_torch
class UpperCAmelCase_					(    __A				,       __A				,       unittest.TestCase				):




      """simple docstring"""




      UpperCamelCase_								=			(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
      UpperCamelCase_								=			(
          {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
      )

      UpperCamelCase_								=			False
      UpperCamelCase_								=			False
      UpperCamelCase_								=			False
      UpperCamelCase_								=			False






      def 				A__      ( self			:		Union[str, Any]     ,      UpperCAmelCase			:		str     ,      UpperCAmelCase			:		Any     ,      UpperCAmelCase			:		int=False		)  ->  Any:


       '''simple docstring'''

       lowercase					:   Dict				  =super()._prepare_for_class(UpperCAmelCase     ,      UpperCAmelCase     ,      return_labels=UpperCAmelCase		)

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

       return inputs_dict






      def 				A__      ( self			:		Dict		)  ->  List[Any]:


       '''simple docstring'''

       lowercase					:   List[str]				  =YolosModelTester(self		)
       lowercase					:   Optional[Any]				  =ConfigTester(self     ,      config_class=UpperCAmelCase     ,      has_text_modality=UpperCAmelCase     ,      hidden_size=37		)






      def 				A__      ( self			:		str		)  ->  Optional[int]:


       '''simple docstring'''

       self.config_tester.run_common_tests()






      def 				A__      ( self			:		Dict		)  ->  List[str]:


       '''simple docstring'''

       pass






      def 				A__      ( self			:		Union[str, Any]		)  ->  List[Any]:


       '''simple docstring'''

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

       for model_class in self.all_model_classes:
        lowercase					:   Optional[int]				  =model_class(UpperCAmelCase		)
        self.assertIsInstance(model.get_input_embeddings()     ,      (nn.Module)		)
        lowercase					:   List[Any]				  =model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(UpperCAmelCase     ,      nn.Linear		)		)






      def 				A__      ( self			:		List[Any]		)  ->  Any:


       '''simple docstring'''

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

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

        lowercase					:   Optional[int]				  =['''pixel_values''']
        self.assertListEqual(arg_names[:1]     ,      UpperCAmelCase		)






      def 				A__      ( self			:		int		)  ->  Any:


       '''simple docstring'''

       lowercase					:   Union[str, Any]				  =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCAmelCase		)






      def 				A__      ( self			:		str		)  ->  Optional[int]:


       '''simple docstring'''

       lowercase  ,		lowercase					:   Tuple				  =self.model_tester.prepare_config_and_inputs_for_common()
       lowercase					:   Any				  =True

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

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

        self.assertListEqual(
            list(attentions[0].shape[-3:]		)     ,      [self.model_tester.num_attention_heads, seq_len, seq_len]     ,      )
        lowercase					:   Dict				  =len(UpperCAmelCase		)

        # Check attention is always last and order is fine
        lowercase					:   Optional[int]				  =True
        lowercase					:   Tuple				  =True
        lowercase					:   Dict				  =model_class(UpperCAmelCase		)
        model.to(UpperCAmelCase		)
        model.eval()
        with torch.no_grad():
         lowercase					:   Tuple				  =model(**self._prepare_for_class(UpperCAmelCase     ,      UpperCAmelCase		)		)

        lowercase					:   Optional[int]				  =1
        self.assertEqual(out_len + added_hidden_states     ,      len(UpperCAmelCase		)		)

        lowercase					:   Optional[int]				  =outputs.attentions

        self.assertEqual(len(UpperCAmelCase		)     ,      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 				A__      ( self			:		Tuple		)  ->  Union[str, Any]:


       '''simple docstring'''

       def check_hidden_states_output(UpperCAmelCase			:		List[str]     ,      UpperCAmelCase			:		Dict     ,      UpperCAmelCase			:		Optional[int]		):
        lowercase					:   List[Any]				  =model_class(UpperCAmelCase		)
        model.to(UpperCAmelCase		)
        model.eval()

        with torch.no_grad():
         lowercase					:   Dict				  =model(**self._prepare_for_class(UpperCAmelCase     ,      UpperCAmelCase		)		)

        lowercase					:   Optional[Any]				  =outputs.hidden_states

        lowercase					:   Any				  =getattr(
            self.model_tester     ,      '''expected_num_hidden_layers'''     ,      self.model_tester.num_hidden_layers + 1		)
        self.assertEqual(len(UpperCAmelCase		)     ,      UpperCAmelCase		)

        # YOLOS has a different seq_length
        lowercase					:   int				  =self.model_tester.expected_seq_len

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

       lowercase  ,		lowercase					:   int				  =self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        lowercase					:   Optional[Any]				  =True
        check_hidden_states_output(UpperCAmelCase     ,      UpperCAmelCase     ,      UpperCAmelCase		)

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

        check_hidden_states_output(UpperCAmelCase     ,      UpperCAmelCase     ,      UpperCAmelCase		)






      def 				A__      ( self			:		int		)  ->  Tuple:


       '''simple docstring'''

       lowercase					:   List[Any]				  =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_object_detection(*UpperCAmelCase		)






      @slow
      def 				A__      ( self			:		Any		)  ->  int:


       '''simple docstring'''

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





def 							lowercase_				(    )       ->      List[str]:



 """simple docstring"""




 lowercase					:   Optional[int]				  =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
 return image





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




      """simple docstring"""




      @cached_property
      def 				A__      ( self			:		str		)  ->  Union[str, Any]:


       '''simple docstring'''

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






      @slow
      def 				A__      ( self			:		Tuple		)  ->  Optional[int]:


       '''simple docstring'''

       lowercase					:   Optional[Any]				  =YolosForObjectDetection.from_pretrained('''hustvl/yolos-small'''		).to(UpperCAmelCase		)

       lowercase					:   Optional[int]				  =self.default_image_processor
       lowercase					:   Optional[Any]				  =prepare_img()
       lowercase					:   Tuple				  =image_processor(images=UpperCAmelCase     ,      return_tensors='''pt'''		).to(UpperCAmelCase		)

       # forward pass
       with torch.no_grad():
        lowercase					:   Optional[Any]				  =model(inputs.pixel_values		)

       # verify outputs
       lowercase					:   Dict				  =torch.Size((1, 100, 92)		)
       self.assertEqual(outputs.logits.shape     ,      UpperCAmelCase		)

       lowercase					:   Optional[int]				  =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=UpperCAmelCase     ,      )
       lowercase					:   str				  =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=UpperCAmelCase		)
       self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]     ,      UpperCAmelCase     ,      atol=1e-4		)		)
       self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]     ,      UpperCAmelCase     ,      atol=1e-4		)		)

       # verify postprocessing
       lowercase					:   int				  =image_processor.post_process_object_detection(
           UpperCAmelCase     ,      threshold=0.3     ,      target_sizes=[image.size[::-1]]		)[0]
       lowercase					:   Union[str, Any]				  =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(UpperCAmelCase		)
       lowercase					:   List[Any]				  =[75, 75, 17, 63, 17]
       lowercase					:   Union[str, Any]				  =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(UpperCAmelCase		)

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











'''simple docstring'''



from __future__ import annotations

from collections.abc import Generator

import requests
from bsa import BeautifulSoup

SCREAMING_SNAKE_CASE						=	'https://www.indeed.co.in/jobs?q=mobile+app+development&l='


def 							lowercase_				(    __A :       str = "mumbai"			)       ->      Generator[tuple[str, str], None, None]:



 """simple docstring"""




 lowercase					:   List[Any]				  =BeautifulSoup(requests.get(url + location			).content					,      '''html.parser'''			)
 # This attribute finds out all the specifics listed in a job
 for job in soup.find_all('''div'''					,      attrs={'''data-tn-component''': '''organicJob'''}			):
  lowercase					:   List[str]				  =job.find('''a'''					,      attrs={'''data-tn-element''': '''jobTitle'''}			).text.strip()
  lowercase					:   Union[str, Any]				  =job.find('''span'''					,      {'''class''': '''company'''}			).text.strip()
  yield job_title, company_name


if __name__ == "__main__":
      for i, job in enumerate(fetch_jobs('Bangalore'), 1):
            print(f"""Job {i:>2} is {job[0]} at {job[1]}""")



