

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



    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.02		,					UpperCamelCase__=3		,					UpperCamelCase__=None		,					UpperCamelCase__=8		,					UpperCamelCase__=10		,					)    ->   Any:





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



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





           '''simple docstring'''
           A_						       =   floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]							)

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

           A_						       =   self.get_config()

           return config, pixel_values, labels



    def        snake_case_      (       self							)    ->   Dict:





           '''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=UpperCamelCase_		,					initializer_range=self.initializer_range		,					num_detection_tokens=self.num_detection_tokens		,					num_labels=self.num_labels		,					)



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__							)    ->   int:





           '''simple docstring'''
           A_						       =   YolosModel(config=UpperCamelCase_							)
           model.to(UpperCamelCase_							)
           model.eval()
           A_						       =   model(UpperCamelCase_							)
           self.parent.assertEqual(
               result.last_hidden_state.shape		,					(self.batch_size, self.expected_seq_len, self.hidden_size)							)



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__							)    ->   Optional[int]:





           '''simple docstring'''
           A_						       =   YolosForObjectDetection(UpperCamelCase_							)
           model.to(UpperCamelCase_							)
           model.eval()

           A_						       =   model(pixel_values=UpperCamelCase_							)
           A_						       =   model(UpperCamelCase_							)

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

           A_						       =   model(pixel_values=UpperCamelCase_		,					labels=UpperCamelCase_							)

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





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


@require_torch
class        A__   (   A__    ,    A__    ,    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        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__=False							)    ->   Tuple:





           '''simple docstring'''
           A_						       =   super()._prepare_for_class(UpperCamelCase_		,					UpperCamelCase_		,					return_labels=UpperCamelCase_							)

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

           return inputs_dict



    def        snake_case_      (       self							)    ->   int:





           '''simple docstring'''
           A_						       =   YolosModelTester(self							)
           A_						       =   ConfigTester(self		,					config_class=UpperCamelCase_		,					has_text_modality=UpperCamelCase_		,					hidden_size=37							)



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           self.config_tester.run_common_tests()



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





           '''simple docstring'''
           pass



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





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs_for_common()

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



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs_for_common()

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

                  A_						       =   ['''pixel_values''']
                  self.assertListEqual(arg_names[:1]		,					UpperCamelCase_							)



    def        snake_case_      (       self							)    ->   Tuple:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCamelCase_							)



    def        snake_case_      (       self							)    ->   Any:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs_for_common()
           A_						       =   True

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

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

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

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

                  A_						       =   1
                  self.assertEqual(out_len + added_hidden_states		,					len(UpperCamelCase_							)							)

                  A_						       =   outputs.attentions

                  self.assertEqual(len(UpperCamelCase_							)		,					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							)    ->   str:





           '''simple docstring'''


           def check_hidden_states_output(UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__							):
                  A_						       =   model_class(UpperCamelCase_							)
                  model.to(UpperCamelCase_							)
                  model.eval()

                  with torch.no_grad():
                         A_						       =   model(**self._prepare_for_class(UpperCamelCase_		,					UpperCamelCase_							)							)

                  A_						       =   outputs.hidden_states

                  A_						       =   getattr(
                      self.model_tester		,					"""expected_num_hidden_layers"""		,					self.model_tester.num_hidden_layers + 1							)
                  self.assertEqual(len(UpperCamelCase_							)		,					UpperCamelCase_							)

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

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

           A_						       =   self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  A_						       =   True
                  check_hidden_states_output(UpperCamelCase_		,					UpperCamelCase_		,					UpperCamelCase_							)

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

                  check_hidden_states_output(UpperCamelCase_		,					UpperCamelCase_		,					UpperCamelCase_							)



    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_object_detection(*UpperCamelCase_							)







    @slow
    def        snake_case_      (       self							)    ->   Tuple:





           '''simple docstring'''


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

def    UpperCAmelCase__     (   )      ->      int:
       A_						       =   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
       return image







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



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





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







    @slow
    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   YolosForObjectDetection.from_pretrained("""hustvl/yolos-small"""							).to(UpperCamelCase_							)

           A_						       =   self.default_image_processor
           A_						       =   prepare_img()
           A_						       =   image_processor(images=UpperCamelCase_		,					return_tensors="""pt"""							).to(UpperCamelCase_							)

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

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

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

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

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




'''simple docstring'''
from __future__ import annotations

from math import pi, sqrt


def      a (     __a					,   __a  )    ->      tuple:



					'''simple docstring'''






					if inductance <= 0:
										raise ValueError('''Inductance cannot be 0 or negative'''  )

					elif capacitance <= 0:
										raise ValueError('''Capacitance cannot be 0 or negative'''  )

					else:
										return (
										    "Resonant frequency",
										    float(1 / (2 * pi * (sqrt(inductance * capacitance  )))  ),
										)


if __name__ == "__main__":
		import doctest

		doctest.testmod()