





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




 """simple docstring"""



 def __init__(       self       :							Union[str, Any]							,	__A       :							str							,	__A       :							Tuple=1_3							,	__A       :							Optional[int]=[3_0, 3_0]							,	__A       :							str=2							,	__A       :							List[Any]=3							,	__A       :							Dict=True							,	__A       :							Union[str, Any]=True							,	__A       :							Tuple=3_2							,	__A       :							str=5							,	__A       :							Dict=4							,	__A       :							Optional[int]=3_7							,	__A       :							Tuple="gelu"							,	__A       :							Tuple=0.1							,	__A       :							List[str]=0.1							,	__A       :							List[str]=1_0							,	__A       :							Optional[int]=0.02							,	__A       :							str=3							,	__A       :							Dict=None							,	__A       :							List[str]=8							,	__A       :							Any=1_0							,	):
        __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        _lowerCamelCase					(       self       :							Optional[Any]	):
        __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=__A	)
                      __UpperCamelCase       =  torch.rand(self.n_targets							,	4							,	device=__A	)
                      labels.append(__A	)

        __UpperCamelCase       =  self.get_config()

        return config, pixel_values, labels






 def        _lowerCamelCase					(       self       :							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        _lowerCamelCase					(       self       :							Optional[Any]							,	__A       :							str							,	__A       :							Dict							,	__A       :							Dict	):
        __UpperCamelCase       =  YolosModel(config=__A	)
        model.to(__A	)
        model.eval()
        __UpperCamelCase       =  model(__A	)
        self.parent.assertEqual(
            result.last_hidden_state.shape							,	(self.batch_size, self.expected_seq_len, self.hidden_size)	)






 def        _lowerCamelCase					(       self       :							Optional[Any]							,	__A       :							Union[str, Any]							,	__A       :							Dict							,	__A       :							Optional[Any]	):
        __UpperCamelCase       =  YolosForObjectDetection(__A	)
        model.to(__A	)
        model.eval()

        __UpperCamelCase       =  model(pixel_values=__A	)
        __UpperCamelCase       =  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       =  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        _lowerCamelCase					(       self       :							List[Any]	):
        __UpperCamelCase       =  self.prepare_config_and_inputs()
        __UpperCamelCase       ,						__UpperCamelCase       ,						__UpperCamelCase       =  config_and_inputs
        __UpperCamelCase       =  {'pixel_values': pixel_values}
        return config, inputs_dict






@require_torch
class      snake_case     (    __lowerCamelCase			,       __lowerCamelCase			,       unittest.TestCase       ):




 """simple docstring"""



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

 SCREAMING_SNAKE_CASE_	:					Dict					=False
 SCREAMING_SNAKE_CASE_	:					Tuple					=False
 SCREAMING_SNAKE_CASE_	:					Optional[int]					=False
 SCREAMING_SNAKE_CASE_	:					Tuple					=False






 def        _lowerCamelCase					(       self       :							Optional[Any]							,	__A       :							Optional[int]							,	__A       :							Dict							,	__A       :							str=False	):
        __UpperCamelCase       =  super()._prepare_for_class(__A							,	__A							,	return_labels=__A	)

        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=__A							,	dtype=torch.long	)
                             __UpperCamelCase       =  torch.ones(
                                 self.model_tester.n_targets							,	4							,	device=__A							,	dtype=torch.float	)
                             labels.append(__A	)
                      __UpperCamelCase       =  labels

        return inputs_dict






 def        _lowerCamelCase					(       self       :							Tuple	):
        __UpperCamelCase       =  YolosModelTester(self	)
        __UpperCamelCase       =  ConfigTester(self							,	config_class=__A							,	has_text_modality=__A							,	hidden_size=3_7	)






 def        _lowerCamelCase					(       self       :							List[str]	):
        self.config_tester.run_common_tests()






 def        _lowerCamelCase					(       self       :							Union[str, Any]	):
        # YOLOS does not use inputs_embeds
        pass






 def        _lowerCamelCase					(       self       :							Any	):
        __UpperCamelCase       ,						__UpperCamelCase       =  self.model_tester.prepare_config_and_inputs_for_common()

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






 def        _lowerCamelCase					(       self       :							Any	):
        __UpperCamelCase       ,						__UpperCamelCase       =  self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               __UpperCamelCase       =  model_class(__A	)
               __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]							,	__A	)






 def        _lowerCamelCase					(       self       :							Optional[Any]	):
        __UpperCamelCase       =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__A	)






 def        _lowerCamelCase					(       self       :							List[str]	):
        __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(__A	)
               model.to(__A	)
               model.eval()
               with torch.no_grad():
                      __UpperCamelCase       =  model(**self._prepare_for_class(__A							,	__A	)	)
               __UpperCamelCase       =  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       =  True
               __UpperCamelCase       =  model_class(__A	)
               model.to(__A	)
               model.eval()
               with torch.no_grad():
                      __UpperCamelCase       =  model(**self._prepare_for_class(__A							,	__A	)	)
               __UpperCamelCase       =  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       =  len(__A	)

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

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

               __UpperCamelCase       =  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        _lowerCamelCase					(       self       :							str	):
        def check_hidden_states_output(__A       :							List[str]							,	__A       :							int							,	__A       :							Tuple	):
               __UpperCamelCase       =  model_class(__A	)
               model.to(__A	)
               model.eval()

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

               __UpperCamelCase       =  outputs.hidden_states

               __UpperCamelCase       =  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       =  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(__A							,	__A							,	__A	)

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

               check_hidden_states_output(__A							,	__A							,	__A	)






 def        _lowerCamelCase					(       self       :							Optional[Any]	):
        __UpperCamelCase       =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_object_detection(*__A	)






 @slow
 def        _lowerCamelCase					(       self       :							List[str]	):
        for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __UpperCamelCase       =  YolosModel.from_pretrained(__A	)
               self.assertIsNotNone(__A	)






def 				lowercase__   (   ) ->      Union[str, Any]:



       """simple docstring"""






       __UpperCamelCase       =  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
       return image


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




 """simple docstring"""



 @cached_property
 def        _lowerCamelCase					(       self       :							Any	):
        return AutoImageProcessor.from_pretrained('hustvl/yolos-small'	) if is_vision_available() else None






 @slow
 def        _lowerCamelCase					(       self       :							Tuple	):
        __UpperCamelCase       =  YolosForObjectDetection.from_pretrained('hustvl/yolos-small'	).to(__A	)

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

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

        # verify outputs
        __UpperCamelCase       =  torch.Size((1, 1_0_0, 9_2)	)
        self.assertEqual(outputs.logits.shape							,	__A	)

        __UpperCamelCase       =  torch.tensor(
            [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]]							,	device=__A							,	)
        __UpperCamelCase       =  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
        __UpperCamelCase       =  image_processor.post_process_object_detection(
            __A							,	threshold=0.3							,	target_sizes=[image.size[::-1]]	)[0]
        __UpperCamelCase       =  torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]	).to(__A	)
        __UpperCamelCase       =  [7_5, 7_5, 1_7, 6_3, 1_7]
        __UpperCamelCase       =  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	)	)







'''simple docstring'''
from typing import List, Optional, Union

from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType

class      snake_case     (    __lowerCamelCase       ):




 """simple docstring"""



 SCREAMING_SNAKE_CASE_	:					Any					=["image_processor", "tokenizer"]
 SCREAMING_SNAKE_CASE_	:					List[Any]					="BlipImageProcessor"
 SCREAMING_SNAKE_CASE_	:					Optional[int]					=("BertTokenizer", "BertTokenizerFast")






 def __init__(       self       :							Dict							,	__A       :							Optional[int]							,	__A       :							List[Any]	):
        __UpperCamelCase       =  False
        super().__init__(__A							,	__A	)
        __UpperCamelCase       =  self.image_processor






 def __call__(       self       :							List[Any]							,	__A       :							ImageInput = None							,	__A       :							Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None							,	__A       :							bool = True							,	__A       :							Union[bool, str, PaddingStrategy] = False							,	__A       :							Union[bool, str, TruncationStrategy] = None							,	__A       :							Optional[int] = None							,	__A       :							int = 0							,	__A       :							Optional[int] = None							,	__A       :							Optional[bool] = None							,	__A       :							bool = False							,	__A       :							bool = False							,	__A       :							bool = False							,	__A       :							bool = False							,	__A       :							bool = False							,	__A       :							bool = True							,	__A       :							Optional[Union[str, TensorType]] = None							,	**__A       :							List[Any]							,	):
        if images is None and text is None:
               raise ValueError('You have to specify either images or text.'	)

        # Get only text
        if images is None:
               __UpperCamelCase       =  self.tokenizer
               __UpperCamelCase       =  self.tokenizer(
                   text=__A							,	add_special_tokens=__A							,	padding=__A							,	truncation=__A							,	max_length=__A							,	stride=__A							,	pad_to_multiple_of=__A							,	return_attention_mask=__A							,	return_overflowing_tokens=__A							,	return_special_tokens_mask=__A							,	return_offsets_mapping=__A							,	return_token_type_ids=__A							,	return_length=__A							,	verbose=__A							,	return_tensors=__A							,	**__A							,	)
               return text_encoding

        # add pixel_values
        __UpperCamelCase       =  self.image_processor(__A							,	return_tensors=__A	)

        if text is not None:
               __UpperCamelCase       =  self.tokenizer(
                   text=__A							,	add_special_tokens=__A							,	padding=__A							,	truncation=__A							,	max_length=__A							,	stride=__A							,	pad_to_multiple_of=__A							,	return_attention_mask=__A							,	return_overflowing_tokens=__A							,	return_special_tokens_mask=__A							,	return_offsets_mapping=__A							,	return_token_type_ids=__A							,	return_length=__A							,	verbose=__A							,	return_tensors=__A							,	**__A							,	)
        else:
               __UpperCamelCase       =  None

        if text_encoding is not None:
               encoding_image_processor.update(__A	)

        return encoding_image_processor






 def        _lowerCamelCase					(       self       :							List[Any]							,	*__A       :							Dict							,	**__A       :							Optional[int]	):
        return self.tokenizer.batch_decode(*__A							,	**__A	)






 def        _lowerCamelCase					(       self       :							List[Any]							,	*__A       :							List[str]							,	**__A       :							Dict	):
        return self.tokenizer.decode(*__A							,	**__A	)






 @property
 def        _lowerCamelCase					(       self       :							Tuple	):
        __UpperCamelCase       =  self.tokenizer.model_input_names
        __UpperCamelCase       =  self.image_processor.model_input_names
        return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names	)	)
