

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 SCREAMING_SNAKE_CASE     :
  """simple docstring"""






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






     """simple docstring"""







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







  def 	SCREAMING_SNAKE_CASE   (      self			:   List[Any]   )							->     str:






     """simple docstring"""







     __lowerCAmelCase    =						floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]   )

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

     __lowerCAmelCase    =						self.get_config()

     return config, pixel_values, labels







  def 	SCREAMING_SNAKE_CASE   (      self			:   Dict   )							->     Union[str, 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=lowerCAmelCase	,							initializer_range=self.initializer_range	,							num_detection_tokens=self.num_detection_tokens	,							num_labels=self.num_labels	,							)







  def 	SCREAMING_SNAKE_CASE   (      self			:   List[Any]	,							lowerCAmelCase			:   Any	,							lowerCAmelCase			:   Dict	,							lowerCAmelCase			:   List[Any]   )							->     List[str]:






     """simple docstring"""







     __lowerCAmelCase    =						YolosModel(config=lowerCAmelCase   )
     model.to(lowerCAmelCase   )
     model.eval()
     __lowerCAmelCase    =						model(lowerCAmelCase   )
     self.parent.assertEqual(
         result.last_hidden_state.shape	,							(self.batch_size, self.expected_seq_len, self.hidden_size)   )







  def 	SCREAMING_SNAKE_CASE   (      self			:   Optional[Any]	,							lowerCAmelCase			:   Tuple	,							lowerCAmelCase			:   Optional[int]	,							lowerCAmelCase			:   int   )							->     List[Any]:






     """simple docstring"""







     __lowerCAmelCase    =						YolosForObjectDetection(lowerCAmelCase   )
     model.to(lowerCAmelCase   )
     model.eval()

     __lowerCAmelCase    =						model(pixel_values=lowerCAmelCase   )
     __lowerCAmelCase    =						model(lowerCAmelCase   )

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

     __lowerCAmelCase    =						model(pixel_values=lowerCAmelCase	,							labels=lowerCAmelCase   )

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






     """simple docstring"""







     __lowerCAmelCase    =						self.prepare_config_and_inputs()
     __lowerCAmelCase    =						config_and_inputs
     __lowerCAmelCase    =						{"""pixel_values""": pixel_values}
     return config, inputs_dict






@require_torch
class SCREAMING_SNAKE_CASE     (  a_       ,							a_       ,							unittest.TestCase			):
  """simple docstring"""






  lowerCamelCase   :      str										=(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
  lowerCamelCase   :      int										=(
      {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {}
  )

  lowerCamelCase   :      Dict										=False
  lowerCamelCase   :      Union[str, Any]										=False
  lowerCamelCase   :      Union[str, Any]										=False
  lowerCamelCase   :      Any										=False







  def 	SCREAMING_SNAKE_CASE   (      self			:   int	,							lowerCAmelCase			:   List[Any]	,							lowerCAmelCase			:   Optional[int]	,							lowerCAmelCase			:   Any=False   )							->     Optional[int]:






     """simple docstring"""







     __lowerCAmelCase    =						super()._prepare_for_class(lowerCAmelCase	,							lowerCAmelCase	,							return_labels=lowerCAmelCase   )

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

     return inputs_dict







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






     """simple docstring"""







     __lowerCAmelCase    =						YolosModelTester(self   )
     __lowerCAmelCase    =						ConfigTester(self	,							config_class=lowerCAmelCase	,							has_text_modality=lowerCAmelCase	,							hidden_size=37   )







  def 	SCREAMING_SNAKE_CASE   (      self			:   Tuple   )							->     List[Any]:






     """simple docstring"""







     self.config_tester.run_common_tests()







  def 	SCREAMING_SNAKE_CASE   (      self			:   Optional[int]   )							->     Tuple:






     """simple docstring"""







     pass







  def 	SCREAMING_SNAKE_CASE   (      self			:   int   )							->     List[str]:






     """simple docstring"""







     __lowerCAmelCase    =						self.model_tester.prepare_config_and_inputs_for_common()

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







  def 	SCREAMING_SNAKE_CASE   (      self			:   Union[str, Any]   )							->     Tuple:






     """simple docstring"""







     __lowerCAmelCase    =						self.model_tester.prepare_config_and_inputs_for_common()

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

        __lowerCAmelCase    =						["""pixel_values"""]
        self.assertListEqual(arg_names[:1]	,							lowerCAmelCase   )







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






     """simple docstring"""







     __lowerCAmelCase    =						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCAmelCase   )







  def 	SCREAMING_SNAKE_CASE   (      self			:   Union[str, Any]   )							->     Optional[Any]:






     """simple docstring"""







     __lowerCAmelCase    =						self.model_tester.prepare_config_and_inputs_for_common()
     __lowerCAmelCase    =						True

     # in YOLOS, the seq_len is different
     __lowerCAmelCase    =						self.model_tester.expected_seq_len
     for model_class in self.all_model_classes:
        __lowerCAmelCase    =						True
        __lowerCAmelCase    =						False
        __lowerCAmelCase    =						True
        __lowerCAmelCase    =						model_class(lowerCAmelCase   )
        model.to(lowerCAmelCase   )
        model.eval()
        with torch.no_grad():
           __lowerCAmelCase    =						model(**self._prepare_for_class(lowerCAmelCase	,							lowerCAmelCase   )   )
        __lowerCAmelCase    =						outputs.attentions
        self.assertEqual(len(lowerCAmelCase   )	,							self.model_tester.num_hidden_layers   )

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

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

        # Check attention is always last and order is fine
        __lowerCAmelCase    =						True
        __lowerCAmelCase    =						True
        __lowerCAmelCase    =						model_class(lowerCAmelCase   )
        model.to(lowerCAmelCase   )
        model.eval()
        with torch.no_grad():
           __lowerCAmelCase    =						model(**self._prepare_for_class(lowerCAmelCase	,							lowerCAmelCase   )   )

        __lowerCAmelCase    =						1
        self.assertEqual(out_len + added_hidden_states	,							len(lowerCAmelCase   )   )

        __lowerCAmelCase    =						outputs.attentions

        self.assertEqual(len(lowerCAmelCase   )	,							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 	SCREAMING_SNAKE_CASE   (      self			:   Dict   )							->     List[str]:






     """simple docstring"""







     def check_hidden_states_output(lowerCAmelCase			:   Optional[Any]	,							lowerCAmelCase			:   Tuple	,							lowerCAmelCase			:   Optional[Any]   ):
        __lowerCAmelCase    =						model_class(lowerCAmelCase   )
        model.to(lowerCAmelCase   )
        model.eval()

        with torch.no_grad():
           __lowerCAmelCase    =						model(**self._prepare_for_class(lowerCAmelCase	,							lowerCAmelCase   )   )

        __lowerCAmelCase    =						outputs.hidden_states

        __lowerCAmelCase    =						getattr(
            self.model_tester	,							"""expected_num_hidden_layers"""	,							self.model_tester.num_hidden_layers + 1   )
        self.assertEqual(len(lowerCAmelCase   )	,							lowerCAmelCase   )

        # YOLOS has a different seq_length
        __lowerCAmelCase    =						self.model_tester.expected_seq_len

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

     __lowerCAmelCase    =						self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        __lowerCAmelCase    =						True
        check_hidden_states_output(lowerCAmelCase	,							lowerCAmelCase	,							lowerCAmelCase   )

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

        check_hidden_states_output(lowerCAmelCase	,							lowerCAmelCase	,							lowerCAmelCase   )







  def 	SCREAMING_SNAKE_CASE   (      self			:   Optional[int]   )							->     Optional[int]:






     """simple docstring"""







     __lowerCAmelCase    =						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_object_detection(*lowerCAmelCase   )







  @slow
  def 	SCREAMING_SNAKE_CASE   (      self			:   str   )							->     List[Any]:






     """simple docstring"""







     for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __lowerCAmelCase    =						YolosModel.from_pretrained(lowerCAmelCase   )
        self.assertIsNotNone(lowerCAmelCase   )






def      snake_case_				()      ->     str:
   __lowerCAmelCase    =						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
   return image



@require_torch
@require_vision
class SCREAMING_SNAKE_CASE     (  unittest.TestCase			):
  """simple docstring"""






  @cached_property
  def 	SCREAMING_SNAKE_CASE   (      self			:   str   )							->     List[Any]:






     """simple docstring"""







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







  @slow
  def 	SCREAMING_SNAKE_CASE   (      self			:   Optional[Any]   )							->     int:






     """simple docstring"""







     __lowerCAmelCase    =						YolosForObjectDetection.from_pretrained("""hustvl/yolos-small"""   ).to(lowerCAmelCase   )

     __lowerCAmelCase    =						self.default_image_processor
     __lowerCAmelCase    =						prepare_img()
     __lowerCAmelCase    =						image_processor(images=lowerCAmelCase	,							return_tensors="""pt"""   ).to(lowerCAmelCase   )

     # forward pass
     with torch.no_grad():
        __lowerCAmelCase    =						model(inputs.pixel_values   )

     # verify outputs
     __lowerCAmelCase    =						torch.Size((1, 1_00, 92)   )
     self.assertEqual(outputs.logits.shape	,							lowerCAmelCase   )

     __lowerCAmelCase    =						torch.tensor(
         [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]]	,							device=lowerCAmelCase	,							)
     __lowerCAmelCase    =						torch.tensor(
         [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]]	,							device=lowerCAmelCase   )
     self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]	,							lowerCAmelCase	,							atol=1e-4   )   )
     self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]	,							lowerCAmelCase	,							atol=1e-4   )   )

     # verify postprocessing
     __lowerCAmelCase    =						image_processor.post_process_object_detection(
         lowerCAmelCase	,							threshold=0.3	,							target_sizes=[image.size[::-1]]   )[0]
     __lowerCAmelCase    =						torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]   ).to(lowerCAmelCase   )
     __lowerCAmelCase    =						[75, 75, 17, 63, 17]
     __lowerCAmelCase    =						torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]   ).to(lowerCAmelCase   )

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





from __future__ import annotations





def      snake_case_				(__A					:						list[float] ,       __A					:						list[float]					)      ->     float:
   __lowerCAmelCase  :      Union[str, Any]    =						sorted(numsa + numsa					)
   __lowerCAmelCase   ,__lowerCAmelCase  :      Optional[int]    =						divmod(len(__A					) ,       2					)
   if mod == 1:
      return all_numbers[div]
   else:
      return (all_numbers[div] + all_numbers[div - 1]) / 2


if __name__ == "__main__":
   import doctest

   doctest.testmod()
   __UpperCAmelCase								=			[float(x) for x in input("""Enter the elements of first array: """).split()]
   __UpperCAmelCase								=			[float(x) for x in input("""Enter the elements of second array: """).split()]
   print(F'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')


