


"""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	:	Any      ,       A_	:	Any      ,       A_	:	List[str]=1_3      ,       A_	:	Tuple=[3_0, 3_0]      ,       A_	:	List[Any]=2      ,       A_	:	str=3      ,       A_	:	Dict=True      ,       A_	:	List[str]=True      ,       A_	:	Optional[int]=3_2      ,       A_	:	List[Any]=5      ,       A_	:	Dict=4      ,       A_	:	Optional[Any]=3_7      ,       A_	:	Any="gelu"      ,       A_	:	Any=0.1      ,       A_	:	List[str]=0.1      ,       A_	:	Optional[Any]=1_0      ,       A_	:	int=0.02      ,       A_	:	List[str]=3      ,       A_	:	Optional[Any]=None      ,       A_	:	List[Any]=8      ,       A_	:	Any=1_0      ,       ):






       '''simple docstring'''


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






       '''simple docstring'''


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

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

       __lowercase									=	self.get_config()

       return config, pixel_values, labels
      def SCREAMING_SNAKE_CASE_	(		self	:	List[str]							):






       '''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 SCREAMING_SNAKE_CASE_	(		self	:	str      ,       A_	:	Optional[Any]      ,       A_	:	List[Any]      ,       A_	:	int							):






       '''simple docstring'''


       __lowercase									=	YolosModel(config=A_							)
       model.to(A_							)
       model.eval()
       __lowercase									=	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	:	List[str]      ,       A_	:	List[str]      ,       A_	:	int      ,       A_	:	List[str]							):






       '''simple docstring'''


       __lowercase									=	YolosForObjectDetection(A_							)
       model.to(A_							)
       model.eval()

       __lowercase									=	model(pixel_values=A_							)
       __lowercase									=	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)							)

       __lowercase									=	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	:	Union[str, Any]							):






       '''simple docstring'''


       __lowercase									=	self.prepare_config_and_inputs()
       __lowercase							,		__lowercase							,		__lowercase									=	config_and_inputs
       __lowercase									=	{"""pixel_values""": pixel_values}
       return config, inputs_dict






@require_torch
class    lowerCamelCase__						(		_a			,   _a			,   unittest.TestCase    ):
      a :     Tuple											=		(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
      a :     int											=		(
          {"""feature-extraction""": YolosModel, """object-detection""": YolosForObjectDetection} if is_torch_available() else {}
      )

      a :     int											=		False
      a :     int											=		False
      a :     int											=		False
      a :     Optional[Any]											=		False
      def SCREAMING_SNAKE_CASE_	(		self	:	str      ,       A_	:	Optional[Any]      ,       A_	:	Any      ,       A_	:	List[Any]=False							):






       '''simple docstring'''


       __lowercase									=	super()._prepare_for_class(A_      ,       A_      ,       return_labels=A_							)

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

       return inputs_dict
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[Any]							):






       '''simple docstring'''


       __lowercase									=	YolosModelTester(self							)
       __lowercase									=	ConfigTester(self      ,       config_class=A_      ,       has_text_modality=A_      ,       hidden_size=3_7							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[int]							):






       '''simple docstring'''


       self.config_tester.run_common_tests()
      def SCREAMING_SNAKE_CASE_	(		self	:	int							):






       '''simple docstring'''


       pass
      def SCREAMING_SNAKE_CASE_	(		self	:	Union[str, Any]							):






       '''simple docstring'''


       __lowercase							,		__lowercase									=	self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        __lowercase									=	model_class(A_							)
        self.assertIsInstance(model.get_input_embeddings()      ,       (nn.Module)							)
        __lowercase									=	model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(A_      ,       nn.Linear							)							)
      def SCREAMING_SNAKE_CASE_	(		self	:	List[str]							):






       '''simple docstring'''


       __lowercase							,		__lowercase									=	self.model_tester.prepare_config_and_inputs_for_common()

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

        __lowercase									=	["""pixel_values"""]
        self.assertListEqual(arg_names[:1]      ,       A_							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Dict							):






       '''simple docstring'''


       __lowercase									=	self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_							)
      def SCREAMING_SNAKE_CASE_	(		self	:	int							):






       '''simple docstring'''


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

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

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

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

        __lowercase									=	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	:	Dict							):






       '''simple docstring'''


       def check_hidden_states_output(A_	:	Optional[Any]      ,       A_	:	Union[str, Any]      ,       A_	:	Any							):
        __lowercase									=	model_class(A_							)
        model.to(A_							)
        model.eval()

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

        __lowercase									=	outputs.hidden_states

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

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

       __lowercase							,		__lowercase									=	self.model_tester.prepare_config_and_inputs_for_common()

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

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

        check_hidden_states_output(A_      ,       A_      ,       A_							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Tuple							):






       '''simple docstring'''


       __lowercase									=	self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_object_detection(*A_							)






      @slow
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[int]							):






       '''simple docstring'''


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






def lowerCAmelCase_      (				):






 """simple docstring"""







 __lowercase									=	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
 return image





@require_torch
@require_vision
class    lowerCamelCase__						(		unittest.TestCase    ):
      @cached_property
      def SCREAMING_SNAKE_CASE_	(		self	:	Any							):






       '''simple docstring'''


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






      @slow
      def SCREAMING_SNAKE_CASE_	(		self	:	Tuple							):






       '''simple docstring'''


       __lowercase									=	YolosForObjectDetection.from_pretrained("""hustvl/yolos-small"""							).to(A_							)

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

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

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

       __lowercase									=	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_      ,       )
       __lowercase									=	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
       __lowercase									=	image_processor.post_process_object_detection(
           A_      ,       threshold=0.3      ,       target_sizes=[image.size[::-1]]							)[0]
       __lowercase									=	torch.tensor([0.99_94, 0.97_90, 0.99_64, 0.99_72, 0.98_61]							).to(A_							)
       __lowercase									=	[7_5, 7_5, 1_7, 6_3, 1_7]
       __lowercase									=	torch.tensor([3_3_5.0_6_0_9, 79.38_48, 3_7_5.4_2_1_6, 1_8_7.2_4_9_5]							).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 lowerCAmelCase_      (				UpperCamelCase__	: str				,   UpperCamelCase__	: str ):






 """simple docstring"""







 def get_matched_characters(UpperCamelCase__	: str				,   UpperCamelCase__	: str ) -> str:
  __lowercase									=	[]
  __lowercase									=	min(len(_stra )				,   len(_stra ) ) // 2
  for i, l in enumerate(_stra ):
   __lowercase									=	int(max(0				,   i - limit ) )
   __lowercase									=	int(min(i + limit + 1				,   len(_stra ) ) )
   if l in _stra[left:right]:
    matched.append(UpperCamelCase__ )
    __lowercase									=	f'''{_stra[0:_stra.index(UpperCamelCase__ )]} {_stra[_stra.index(UpperCamelCase__ ) + 1:]}'''

  return "".join(UpperCamelCase__ )

 # matching characters
 __lowercase									=	get_matched_characters(UpperCamelCase__				,   UpperCamelCase__ )
 __lowercase									=	get_matched_characters(UpperCamelCase__				,   UpperCamelCase__ )
 __lowercase									=	len(UpperCamelCase__ )

 # transposition
 __lowercase									=	(
     len([(ca, ca) for ca, ca in zip(UpperCamelCase__				,   UpperCamelCase__ ) if ca != ca] ) // 2
 )

 if not match_count:
  __lowercase									=	0.0
 else:
  __lowercase									=	(
      1
      / 3
      * (
          match_count / len(UpperCamelCase__ )
          + match_count / len(UpperCamelCase__ )
          + (match_count - transpositions) / match_count
      )
  )

 # common prefix up to 4 characters
 __lowercase									=	0
 for ca, ca in zip(stra[:4]				,   stra[:4] ):
  if ca == ca:
   prefix_len += 1
  else:
   break

 return jaro + 0.1 * prefix_len * (1 - jaro)


if __name__ == "__main__":
       import doctest

       doctest.testmod()
       print(jaro_winkler("hello", "world"))
