





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       __A							:




      """simple docstring"""







      def __init__(		self   ,				a__   ,				a__=13   ,				a__=[30, 30]   ,				a__=2   ,				a__=3   ,				a__=True   ,				a__=True   ,				a__=32   ,				a__=5   ,				a__=4   ,				a__=37   ,				a__="gelu"   ,				a__=0.1   ,				a__=0.1   ,				a__=10   ,				a__=0.02   ,				a__=3   ,				a__=None   ,				a__=8   ,				a__=10   ,				):



             """simple docstring"""





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


      def 					__snake_case      (		self):



             """simple docstring"""





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

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

             _lowerCamelCase				:  Dict						=		self.get_config()

             return config, pixel_values, labels


      def 					__snake_case      (		self):



             """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 					__snake_case      (		self   ,				a__   ,				a__   ,				a__):



             """simple docstring"""





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


      def 					__snake_case      (		self   ,				a__   ,				a__   ,				a__):



             """simple docstring"""





             _lowerCamelCase				:  List[str]						=		YolosForObjectDetection(a__)
             model.to(a__)
             model.eval()

             _lowerCamelCase				:  Union[str, Any]						=		model(pixel_values=a__)
             _lowerCamelCase				:  Tuple						=		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))

             _lowerCamelCase				:  Tuple						=		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 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Tuple						=		self.prepare_config_and_inputs()
             _lowerCamelCase,	_lowerCamelCase,	_lowerCamelCase				:  List[Any]						=		config_and_inputs
             _lowerCamelCase				:  Dict						=		{'''pixel_values''': pixel_values}
             return config, inputs_dict







@require_torch
class       __A							(   lowerCamelCase__			,lowerCamelCase__			,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 					__snake_case      (		self   ,				a__   ,				a__   ,				a__=False):



             """simple docstring"""





             _lowerCamelCase				:  Optional[int]						=		super()._prepare_for_class(a__   ,				a__   ,				return_labels=a__)

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

             return inputs_dict


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Optional[Any]						=		YolosModelTester(self)
             _lowerCamelCase				:  str						=		ConfigTester(self   ,				config_class=a__   ,				has_text_modality=a__   ,				hidden_size=37)


      def 					__snake_case      (		self):



             """simple docstring"""





             self.config_tester.run_common_tests()


      def 					__snake_case      (		self):



             """simple docstring"""





             pass


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase,	_lowerCamelCase				:  Optional[int]						=		self.model_tester.prepare_config_and_inputs_for_common()

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


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase,	_lowerCamelCase				:  str						=		self.model_tester.prepare_config_and_inputs_for_common()

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

                    _lowerCamelCase				:  Optional[Any]						=		['''pixel_values''']
                    self.assertListEqual(arg_names[:1]   ,				a__)


      def 					__snake_case      (		self):



             """simple docstring"""





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


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase,	_lowerCamelCase				:  Dict						=		self.model_tester.prepare_config_and_inputs_for_common()
             _lowerCamelCase				:  Optional[int]						=		True

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

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

                    _lowerCamelCase				:  int						=		1
                    self.assertEqual(out_len + added_hidden_states   ,				len(a__))

                    _lowerCamelCase				:  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 					__snake_case      (		self):



             """simple docstring"""





             def check_hidden_states_output(a__   ,				a__   ,				a__):
                    _lowerCamelCase				:  str						=		model_class(a__)
                    model.to(a__)
                    model.eval()

                    with torch.no_grad():
                           _lowerCamelCase				:  Any						=		model(**self._prepare_for_class(a__   ,				a__))

                    _lowerCamelCase				:  List[str]						=		outputs.hidden_states

                    _lowerCamelCase				:  Optional[int]						=		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
                    _lowerCamelCase				:  Optional[Any]						=		self.model_tester.expected_seq_len

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

             _lowerCamelCase,	_lowerCamelCase				:  str						=		self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    _lowerCamelCase				:  List[str]						=		True
                    check_hidden_states_output(a__   ,				a__   ,				a__)

                    # check that output_hidden_states also work using config
                    del inputs_dict["output_hidden_states"]
                    _lowerCamelCase				:  List[str]						=		True

                    check_hidden_states_output(a__   ,				a__   ,				a__)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Any						=		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_object_detection(*a__)



      @slow
      def 					__snake_case      (		self):



             """simple docstring"""





             for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    _lowerCamelCase				:  Optional[Any]						=		YolosModel.from_pretrained(a__)
                    self.assertIsNotNone(a__)




def  __UpperCAmelCase(   ):
       _lowerCamelCase				:  int						=		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
       return image







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




      """simple docstring"""







      @cached_property
      def 					__snake_case      (		self):



             """simple docstring"""





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



      @slow
      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[str]						=		YolosForObjectDetection.from_pretrained('''hustvl/yolos-small''').to(a__)

             _lowerCamelCase				:  int						=		self.default_image_processor
             _lowerCamelCase				:  Dict						=		prepare_img()
             _lowerCamelCase				:  str						=		image_processor(images=a__   ,				return_tensors='''pt''').to(a__)

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

             # verify outputs
             _lowerCamelCase				:  int						=		torch.Size((1, 100, 92))
             self.assertEqual(outputs.logits.shape   ,				a__)

             _lowerCamelCase				:  Dict						=		torch.tensor(
                 [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]]   ,				device=a__   ,				)
             _lowerCamelCase				:  str						=		torch.tensor(
                 [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]]   ,				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
             _lowerCamelCase				:  Optional[Any]						=		image_processor.post_process_object_detection(
                 a__   ,				threshold=0.3   ,				target_sizes=[image.size[::-1]])[0]
             _lowerCamelCase				:  Any						=		torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]).to(a__)
             _lowerCamelCase				:  str						=		[75, 75, 17, 63, 17]
             _lowerCamelCase				:  Union[str, Any]						=		torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]).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__))








from __future__ import annotations




def  __UpperCAmelCase(   lowercase_			,     lowercase_ = None			,     lowercase_ = None			,     lowercase_ = False			,     ):
       _lowerCamelCase				:  Tuple						=		cipher_alphabet or [chr(lowercase_   ) for i in range(97			,     1_23   )]

       # If the argument is None or the user provided an empty dictionary
       if not frequencies_dict:
              # Frequencies of letters in the english language (how much they show up)
              _lowerCamelCase				:  Dict						=		{
                  '''a''': 0.0_8_4_9_7,
                  '''b''': 0.0_1_4_9_2,
                  '''c''': 0.0_2_2_0_2,
                  '''d''': 0.0_4_2_5_3,
                  '''e''': 0.1_1_1_6_2,
                  '''f''': 0.0_2_2_2_8,
                  '''g''': 0.0_2_0_1_5,
                  '''h''': 0.0_6_0_9_4,
                  '''i''': 0.0_7_5_4_6,
                  '''j''': 0.0_0_1_5_3,
                  '''k''': 0.0_1_2_9_2,
                  '''l''': 0.0_4_0_2_5,
                  '''m''': 0.0_2_4_0_6,
                  '''n''': 0.0_6_7_4_9,
                  '''o''': 0.0_7_5_0_7,
                  '''p''': 0.0_1_9_2_9,
                  '''q''': 0.0_0_0_9_5,
                  '''r''': 0.0_7_5_8_7,
                  '''s''': 0.0_6_3_2_7,
                  '''t''': 0.0_9_3_5_6,
                  '''u''': 0.0_2_7_5_8,
                  '''v''': 0.0_0_9_7_8,
                  '''w''': 0.0_2_5_6_0,
                  '''x''': 0.0_0_1_5_0,
                  '''y''': 0.0_1_9_9_4,
                  '''z''': 0.0_0_0_7_7,
              }
       else:
              # Custom frequencies dictionary
              _lowerCamelCase				:  Tuple						=		frequencies_dict

       if not case_sensitive:
              _lowerCamelCase				:  Optional[int]						=		ciphertext.lower()

       # Chi squared statistic values
       _lowerCamelCase				:  dict[int, tuple[float, str]]						=		{}

       # cycle through all of the shifts
       for shift in range(len(lowercase_   )   ):
              _lowerCamelCase				:  Any						=		''''''

              # decrypt the message with the shift
              for letter in ciphertext:
                     try:
                            # Try to index the letter in the alphabet
                            _lowerCamelCase				:  int						=		(alphabet_letters.index(letter.lower()   ) - shift) % len(
                                lowercase_   )
                            decrypted_with_shift += (
                                alphabet_letters[new_key].upper()
                                if case_sensitive and letter.isupper()
                                else alphabet_letters[new_key]
                            )
                     except ValueError:
                            # Append the character if it isn't in the alphabet
                            decrypted_with_shift += letter

              _lowerCamelCase				:  Optional[Any]						=		0.0

              # Loop through each letter in the decoded message with the shift
              for letter in decrypted_with_shift:
                     if case_sensitive:
                            _lowerCamelCase				:  Any						=		letter.lower()
                            if letter in frequencies:
                                   # Get the amount of times the letter occurs in the message
                                   _lowerCamelCase				:  List[str]						=		decrypted_with_shift.lower().count(lowercase_   )

                                   # Get the excepcted amount of times the letter should appear based
                                   # on letter frequencies
                                   _lowerCamelCase				:  Optional[Any]						=		frequencies[letter] * occurrences

                                   # Complete the chi squared statistic formula
                                   _lowerCamelCase				:  int						=		((occurrences - expected) ** 2) / expected

                                   # Add the margin of error to the total chi squared statistic
                                   chi_squared_statistic += chi_letter_value
                     else:
                            if letter.lower() in frequencies:
                                   # Get the amount of times the letter occurs in the message
                                   _lowerCamelCase				:  Union[str, Any]						=		decrypted_with_shift.count(lowercase_   )

                                   # Get the excepcted amount of times the letter should appear based
                                   # on letter frequencies
                                   _lowerCamelCase				:  List[str]						=		frequencies[letter] * occurrences

                                   # Complete the chi squared statistic formula
                                   _lowerCamelCase				:  str						=		((occurrences - expected) ** 2) / expected

                                   # Add the margin of error to the total chi squared statistic
                                   chi_squared_statistic += chi_letter_value

        # Add the data to the chi_squared_statistic_values dictionary
              _lowerCamelCase				:  Tuple						=		(
                  chi_squared_statistic,
                  decrypted_with_shift,
              )

       # Get the most likely cipher by finding the cipher with the smallest chi squared
       # statistic
       def chi_squared_statistic_values_sorting_key(lowercase_   ) -> tuple[float, str]:
              return chi_squared_statistic_values[key]

       _lowerCamelCase				:  int						=		min(
           lowercase_			,     key=lowercase_			,     )

       # Get all the data from the most likely cipher (key, decoded message)
       (
           (
           _lowerCamelCase
       ),	(
           _lowerCamelCase
       ),	
       )				:  Optional[int]						=		chi_squared_statistic_values[most_likely_cipher]

       # Return the data on the most likely shift
       return (
           most_likely_cipher,
           most_likely_cipher_chi_squared_value,
           decoded_most_likely_cipher,
       )

