
"""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			,  __UpperCAmelCase			,  __UpperCAmelCase=13			,  __UpperCAmelCase=[30, 30]			,  __UpperCAmelCase=2			,  __UpperCAmelCase=3			,  __UpperCAmelCase=True			,  __UpperCAmelCase=True			,  __UpperCAmelCase=32			,  __UpperCAmelCase=5			,  __UpperCAmelCase=4			,  __UpperCAmelCase=37			,  __UpperCAmelCase="gelu"			,  __UpperCAmelCase=0.1			,  __UpperCAmelCase=0.1			,  __UpperCAmelCase=10			,  __UpperCAmelCase=0.0_2			,  __UpperCAmelCase=3			,  __UpperCAmelCase=None			,  __UpperCAmelCase=8			,  __UpperCAmelCase=10			,  ):

     '''simple docstring'''




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





    def 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




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

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

     __UpperCamelCase       						= self.get_config()

     return config, pixel_values, labels





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





    def 		UpperCAmelCase      (			self			,  __UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase   ):

     '''simple docstring'''




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





    def 		UpperCAmelCase      (			self			,  __UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase   ):

     '''simple docstring'''




     __UpperCamelCase       						= YolosForObjectDetection(lowerCAmelCase_   )
     model.to(lowerCAmelCase_   )
     model.eval()

     __UpperCamelCase       						= model(pixel_values=lowerCAmelCase_   )
     __UpperCamelCase       						= 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)   )

     __UpperCamelCase       						= 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 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




     __UpperCamelCase       						= self.prepare_config_and_inputs()
     __UpperCamelCase						,			__UpperCamelCase						,			__UpperCamelCase       						= config_and_inputs
     __UpperCamelCase       						= {'pixel_values': pixel_values}
     return config, inputs_dict


@require_torch
class __lowerCAmelCase	(   __UpperCAmelCase    ,						__UpperCAmelCase    ,						unittest.TestCase    ):
    lowercase		     =		(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
    lowercase		     =		(
        {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {}
    )

    lowercase		     =		False
    lowercase		     =		False
    lowercase		     =		False
    lowercase		     =		False





    def 		UpperCAmelCase      (			self			,  __UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase=False   ):

     '''simple docstring'''




     __UpperCamelCase       						= super()._prepare_for_class(lowerCAmelCase_			,  lowerCAmelCase_			,  return_labels=lowerCAmelCase_   )

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

     return inputs_dict





    def 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




     __UpperCamelCase       						= YolosModelTester(self   )
     __UpperCamelCase       						= ConfigTester(self			,  config_class=lowerCAmelCase_			,  has_text_modality=lowerCAmelCase_			,  hidden_size=37   )





    def 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




     self.config_tester.run_common_tests()





    def 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




     pass





    def 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




     __UpperCamelCase						,			__UpperCamelCase       						= self.model_tester.prepare_config_and_inputs_for_common()

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





    def 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




     __UpperCamelCase						,			__UpperCamelCase       						= self.model_tester.prepare_config_and_inputs_for_common()

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

      __UpperCamelCase       						= ['pixel_values']
      self.assertListEqual(arg_names[:1]			,  lowerCAmelCase_   )





    def 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




     __UpperCamelCase       						= self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCAmelCase_   )





    def 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




     __UpperCamelCase						,			__UpperCamelCase       						= self.model_tester.prepare_config_and_inputs_for_common()
     __UpperCamelCase       						= True

     # in YOLOS, the seq_len is different
     __UpperCamelCase       						= self.model_tester.expected_seq_len
     for model_class in self.all_model_classes:
      __UpperCamelCase       						= True
      __UpperCamelCase       						= False
      __UpperCamelCase       						= True
      __UpperCamelCase       						= model_class(lowerCAmelCase_   )
      model.to(lowerCAmelCase_   )
      model.eval()
      with torch.no_grad():
       __UpperCamelCase       						= model(**self._prepare_for_class(lowerCAmelCase_			,  lowerCAmelCase_   )   )
      __UpperCamelCase       						= 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"]
      __UpperCamelCase       						= True
      __UpperCamelCase       						= model_class(lowerCAmelCase_   )
      model.to(lowerCAmelCase_   )
      model.eval()
      with torch.no_grad():
       __UpperCamelCase       						= model(**self._prepare_for_class(lowerCAmelCase_			,  lowerCAmelCase_   )   )
      __UpperCamelCase       						= 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]			,  )
      __UpperCamelCase       						= len(lowerCAmelCase_   )

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

      __UpperCamelCase       						= 1
      self.assertEqual(out_len + added_hidden_states			,  len(lowerCAmelCase_   )   )

      __UpperCamelCase       						= 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 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




     def check_hidden_states_output(__UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase   ):
      __UpperCamelCase       						= model_class(lowerCAmelCase_   )
      model.to(lowerCAmelCase_   )
      model.eval()

      with torch.no_grad():
       __UpperCamelCase       						= model(**self._prepare_for_class(lowerCAmelCase_			,  lowerCAmelCase_   )   )

      __UpperCamelCase       						= outputs.hidden_states

      __UpperCamelCase       						= 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
      __UpperCamelCase       						= self.model_tester.expected_seq_len

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

     __UpperCamelCase						,			__UpperCamelCase       						= self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
      __UpperCamelCase       						= True
      check_hidden_states_output(lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_   )

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

      check_hidden_states_output(lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_   )





    def 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




     __UpperCamelCase       						= self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_object_detection(*lowerCAmelCase_   )







    @slow
    def 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




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






def 							A		(       )   ->			Dict:
 __UpperCamelCase       						= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
 return image





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





    @cached_property
    def 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




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







    @slow
    def 		UpperCAmelCase      (			self   ):

     '''simple docstring'''




     __UpperCamelCase       						= YolosForObjectDetection.from_pretrained('hustvl/yolos-small'   ).to(lowerCAmelCase_   )

     __UpperCamelCase       						= self.default_image_processor
     __UpperCamelCase       						= prepare_img()
     __UpperCamelCase       						= image_processor(images=lowerCAmelCase_			,  return_tensors='pt'   ).to(lowerCAmelCase_   )

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

     # verify outputs
     __UpperCamelCase       						= torch.Size((1, 100, 92)   )
     self.assertEqual(outputs.logits.shape			,  lowerCAmelCase_   )

     __UpperCamelCase       						= 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=lowerCAmelCase_			,  )
     __UpperCamelCase       						= 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=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
     __UpperCamelCase       						= image_processor.post_process_object_detection(
         lowerCAmelCase_			,  threshold=0.3			,  target_sizes=[image.size[::-1]]   )[0]
     __UpperCamelCase       						= 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(lowerCAmelCase_   )
     __UpperCamelCase       						= [75, 75, 17, 63, 17]
     __UpperCamelCase       						= 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(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_   )   )





"""simple docstring"""

import argparse
from collections import defaultdict






def 							A		(       snake_case   :Tuple       ,      snake_case   :List[Any]       ,      snake_case   :List[Any]       ,      snake_case   :Union[str, Any]       ,      snake_case   :Optional[Any]	)   ->			Union[str, Any]:
 __UpperCamelCase       						= f'{file}_{class_name}_{test_name}'
 done_test[_id] += 1

 with open(snake_case       ,      'r'	) as f:
  __UpperCamelCase       						= f.readlines()

 __UpperCamelCase       						= f'class {class_name}('
 __UpperCamelCase       						= f'{4 * " "}def {test_name}('
 __UpperCamelCase       						= f'{8 * " "}{correct_line.split()[0]}'
 __UpperCamelCase       						= f'{1_6 * " "}{correct_line.split()[0]}'
 __UpperCamelCase       						= False
 __UpperCamelCase       						= False
 __UpperCamelCase       						= False
 __UpperCamelCase       						= False
 __UpperCamelCase       						= 0
 __UpperCamelCase       						= 0

 __UpperCamelCase       						= []
 for line in lines:
  if line.startswith(snake_case	):
   __UpperCamelCase       						= True
  elif in_class and line.startswith(snake_case	):
   __UpperCamelCase       						= True
  elif in_class and in_func and (line.startswith(snake_case	) or line.startswith(snake_case	)):
   __UpperCamelCase       						= len(line.split(correct_line.split()[0]	)[0]	)
   count += 1

   if count == done_test[_id]:
    __UpperCamelCase       						= True

  if in_class and in_func and in_line:
   if ")" not in line:
    continue
   else:
    __UpperCamelCase       						= True

  if in_class and in_func and in_line and insert_line:
   new_lines.append(f'{spaces * " "}{correct_line}'	)
   __UpperCamelCase       						= __UpperCamelCase       						= __UpperCamelCase       						= __UpperCamelCase       						= False
  else:
   new_lines.append(snake_case	)

 with open(snake_case       ,      'w'	) as f:
  for line in new_lines:
   f.write(snake_case	)






def 							A		(       snake_case   :List[str]       ,      snake_case   :str=None	)   ->			Tuple:
 if fail is not None:
  with open(snake_case       ,      'r'	) as f:
   __UpperCamelCase       						= {l.strip() for l in f.readlines()}
 else:
  __UpperCamelCase       						= None

 with open(snake_case       ,      'r'	) as f:
  __UpperCamelCase       						= f.readlines()

 __UpperCamelCase       						= defaultdict(snake_case	)
 for line in correct_lines:
  __UpperCamelCase						,			__UpperCamelCase						,			__UpperCamelCase						,			__UpperCamelCase       						= line.split(';'	)
  if test_failures is None or "::".join([file, class_name, test_name]	) in test_failures:
   overwrite_file(snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case	)


if __name__ == "__main__":
      UpperCamelCase			:       str									=				argparse.ArgumentParser()
      parser.add_argument("--correct_filename", help="filename of tests with expected result")
      parser.add_argument("--fail_filename", help="filename of test failures", type=str, default=None)
      UpperCamelCase			:       List[Any]									=				parser.parse_args()

      main(args.correct_filename, args.fail_filename)



