





"""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      __SCREAMING_SNAKE_CASE    :







  '''simple docstring'''


  def __init__(		self   :       Union[str, Any]					,   __a   :       str					,   __a   :       Union[str, Any]=13					,   __a   :       str=[30, 30]					,   __a   :       int=2					,   __a   :       List[Any]=3					,   __a   :       Optional[int]=True					,   __a   :       List[str]=True					,   __a   :       Optional[int]=32					,   __a   :       Optional[int]=5					,   __a   :       List[str]=4					,   __a   :       Tuple=37					,   __a   :       Tuple="gelu"					,   __a   :       Optional[int]=0.1					,   __a   :       Optional[int]=0.1					,   __a   :       Dict=10					,   __a   :       int=0.02					,   __a   :       Dict=3					,   __a   :       Any=None					,   __a   :       Any=8					,   __a   :       Optional[Any]=10					,   )		->				Dict:
        _UpperCamelCase      :	Optional[int]						=       parent
        _UpperCamelCase      :	List[Any]						=       batch_size
        _UpperCamelCase      :	List[Any]						=       image_size
        _UpperCamelCase      :	List[str]						=       patch_size
        _UpperCamelCase      :	Optional[int]						=       num_channels
        _UpperCamelCase      :	List[str]						=       is_training
        _UpperCamelCase      :	Tuple						=       use_labels
        _UpperCamelCase      :	Tuple						=       hidden_size
        _UpperCamelCase      :	List[Any]						=       num_hidden_layers
        _UpperCamelCase      :	Optional[int]						=       num_attention_heads
        _UpperCamelCase      :	int						=       intermediate_size
        _UpperCamelCase      :	Optional[Any]						=       hidden_act
        _UpperCamelCase      :	Dict						=       hidden_dropout_prob
        _UpperCamelCase      :	Optional[int]						=       attention_probs_dropout_prob
        _UpperCamelCase      :	Union[str, Any]						=       type_sequence_label_size
        _UpperCamelCase      :	List[Any]						=       initializer_range
        _UpperCamelCase      :	str						=       num_labels
        _UpperCamelCase      :	Optional[Any]						=       scope
        _UpperCamelCase      :	Optional[int]						=       n_targets
        _UpperCamelCase      :	Dict						=       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      :	int						=       (image_size[1] // patch_size) * (image_size[0] // patch_size)
        _UpperCamelCase      :	Optional[int]						=       num_patches + 1 + self.num_detection_tokens

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]	)		->				Optional[Any]:
        _UpperCamelCase      :	Any						=       floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]	)

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

        _UpperCamelCase      :	Optional[Any]						=       self.get_config()

        return config, pixel_values, labels

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				Tuple:
        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    __SCREAMING_SNAKE_CASE				(		self   :       int					,   __a   :       Optional[int]					,   __a   :       int					,   __a   :       Dict	)		->				Dict:
        _UpperCamelCase      :	int						=       YolosModel(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Optional[Any]						=       model(__a	)
        self.parent.assertEqual(
            result.last_hidden_state.shape					,   (self.batch_size, self.expected_seq_len, self.hidden_size)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict					,   __a   :       str					,   __a   :       Dict					,   __a   :       int	)		->				Dict:
        _UpperCamelCase      :	Union[str, Any]						=       YolosForObjectDetection(__a	)
        model.to(__a	)
        model.eval()

        _UpperCamelCase      :	List[Any]						=       model(pixel_values=__a	)
        _UpperCamelCase      :	int						=       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    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				str:
        _UpperCamelCase      :	int						=       self.prepare_config_and_inputs()
        _UpperCamelCase,  _UpperCamelCase,  _UpperCamelCase      :	Optional[int]						=       config_and_inputs
        _UpperCamelCase      :	Tuple						=       {"pixel_values": pixel_values}
        return config, inputs_dict





@require_torch
class      __SCREAMING_SNAKE_CASE    (						_UpperCamelCase		,  _UpperCamelCase		,  unittest.TestCase   ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:List[Any]	     =					(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE__							:int	     =					(
      {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {}
  )

  SCREAMING_SNAKE_CASE__							:Dict	     =					False
  SCREAMING_SNAKE_CASE__							:Union[str, Any]	     =					False
  SCREAMING_SNAKE_CASE__							:List[str]	     =					False
  SCREAMING_SNAKE_CASE__							:List[Any]	     =					False

  def    __SCREAMING_SNAKE_CASE				(		self   :       str					,   __a   :       Dict					,   __a   :       Union[str, Any]					,   __a   :       int=False	)		->				Dict:
        _UpperCamelCase      :	Optional[int]						=       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      :	Dict						=       {}
                          _UpperCamelCase      :	Dict						=       torch.ones(
                              size=(self.model_tester.n_targets,)					,   device=__a					,   dtype=torch.long	)
                          _UpperCamelCase      :	List[Any]						=       torch.ones(
                              self.model_tester.n_targets					,   4					,   device=__a					,   dtype=torch.float	)
                          labels.append(__a	)
                    _UpperCamelCase      :	Optional[Any]						=       labels

        return inputs_dict

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				Any:
        _UpperCamelCase      :	int						=       YolosModelTester(self	)
        _UpperCamelCase      :	Union[str, Any]						=       ConfigTester(self					,   config_class=__a					,   has_text_modality=__a					,   hidden_size=37	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict	)		->				Tuple:
        self.config_tester.run_common_tests()

  def    __SCREAMING_SNAKE_CASE				(		self   :       int	)		->				List[Any]:
        # YOLOS does not use inputs_embeds
        pass

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				Any:
        _UpperCamelCase,  _UpperCamelCase      :	Dict						=       self.model_tester.prepare_config_and_inputs_for_common()

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

  def    __SCREAMING_SNAKE_CASE				(		self   :       int	)		->				Union[str, Any]:
        _UpperCamelCase,  _UpperCamelCase      :	Tuple						=       self.model_tester.prepare_config_and_inputs_for_common()

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

              _UpperCamelCase      :	Tuple						=       ["pixel_values"]
              self.assertListEqual(arg_names[:1]					,   __a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       int	)		->				Any:
        _UpperCamelCase      :	Union[str, Any]						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]	)		->				List[Any]:
        _UpperCamelCase,  _UpperCamelCase      :	Optional[Any]						=       self.model_tester.prepare_config_and_inputs_for_common()
        _UpperCamelCase      :	Optional[Any]						=       True

        # in YOLOS, the seq_len is different
        _UpperCamelCase      :	Any						=       self.model_tester.expected_seq_len
        for model_class in self.all_model_classes:
              _UpperCamelCase      :	Tuple						=       True
              _UpperCamelCase      :	Optional[Any]						=       False
              _UpperCamelCase      :	Union[str, Any]						=       True
              _UpperCamelCase      :	int						=       model_class(__a	)
              model.to(__a	)
              model.eval()
              with torch.no_grad():
                    _UpperCamelCase      :	str						=       model(**self._prepare_for_class(__a					,   __a	)	)
              _UpperCamelCase      :	Union[str, 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      :	Any						=       model_class(__a	)
              model.to(__a	)
              model.eval()
              with torch.no_grad():
                    _UpperCamelCase      :	Union[str, Any]						=       model(**self._prepare_for_class(__a					,   __a	)	)
              _UpperCamelCase      :	Optional[int]						=       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      :	List[str]						=       len(__a	)

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

              _UpperCamelCase      :	Union[str, Any]						=       1
              self.assertEqual(out_len + added_hidden_states					,   len(__a	)	)

              _UpperCamelCase      :	List[Any]						=       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    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				Optional[int]:
        def check_hidden_states_output(__a   :       List[Any]					,   __a   :       List[str]					,   __a   :       Union[str, Any]	):
              _UpperCamelCase      :	Optional[Any]						=       model_class(__a	)
              model.to(__a	)
              model.eval()

              with torch.no_grad():
                    _UpperCamelCase      :	Union[str, Any]						=       model(**self._prepare_for_class(__a					,   __a	)	)

              _UpperCamelCase      :	str						=       outputs.hidden_states

              _UpperCamelCase      :	Union[str, Any]						=       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      :	Tuple						=       self.model_tester.expected_seq_len

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

        _UpperCamelCase,  _UpperCamelCase      :	Optional[Any]						=       self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _UpperCamelCase      :	Any						=       True
              check_hidden_states_output(__a					,   __a					,   __a	)

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

              check_hidden_states_output(__a					,   __a					,   __a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				List[Any]:
        _UpperCamelCase      :	Any						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_object_detection(*__a	)


  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				int:
        for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _UpperCamelCase      :	Union[str, Any]						=       YolosModel.from_pretrained(__a	)
              self.assertIsNotNone(__a	)





def 					lowercase__    (					)					->		Tuple:




      """simple docstring"""

      _UpperCamelCase      :	List[Any]						=       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   :       Optional[int]	)		->				str:
        return AutoImageProcessor.from_pretrained("hustvl/yolos-small"	) if is_vision_available() else None


  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				Tuple:
        _UpperCamelCase      :	int						=       YolosForObjectDetection.from_pretrained("hustvl/yolos-small"	).to(__a	)

        _UpperCamelCase      :	int						=       self.default_image_processor
        _UpperCamelCase      :	Tuple						=       prepare_img()
        _UpperCamelCase      :	Any						=       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      :	List[str]						=       torch.Size((1, 100, 92)	)
        self.assertEqual(outputs.logits.shape					,   __a	)

        _UpperCamelCase      :	Optional[Any]						=       torch.tensor(
            [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]]					,   device=__a					,   )
        _UpperCamelCase      :	Optional[int]						=       torch.tensor(
            [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]]					,   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      :	List[str]						=       image_processor.post_process_object_detection(
            __a					,   threshold=0.3					,   target_sizes=[image.size[::-1]]	)[0]
        _UpperCamelCase      :	Any						=       torch.tensor([0.99_94, 0.97_90, 0.99_64, 0.99_72, 0.98_61]	).to(__a	)
        _UpperCamelCase      :	Union[str, Any]						=       [75, 75, 17, 63, 17]
        _UpperCamelCase      :	Dict						=       torch.tensor([3_35.06_09, 79.38_48, 3_75.42_16, 1_87.24_95]	).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"""


def 					lowercase__    (					lowercase_		,lowercase_			)					->		None:




      """simple docstring"""

      _UpperCamelCase      :	List[Any]						=       len(lowercase_			)
      print("The following activities are selected:"			)

      # The first activity is always selected
      _UpperCamelCase      :	List[Any]						=       0
      print(lowercase_		,end=","			)

      # Consider rest of the activities
      for j in range(lowercase_			):
            # If this activity has start time greater than
            # or equal to the finish time of previously
            # selected activity, then select it
            if start[j] >= finish[i]:
                  print(lowercase_		,end=","			)
                  _UpperCamelCase      :	Optional[Any]						=       j


if __name__ == "__main__":
  import doctest

  doctest.testmod()

  lowerCamelCase__				  =   [1, 3, 0, 5, 8, 5]
  lowerCamelCase__				  =   [2, 4, 6, 7, 9, 9]
  print_max_activities(start, finish)
