






import unittest

from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
      from PIL import Image
else:







      class 				UpperCAmelCase_  :




           @staticmethod
           def   __UpperCAmelCase  (				*_lowerCAmelCase	,						**_lowerCAmelCase		):
                pass







@is_pipeline_test
@require_vision
@require_torch
class 				UpperCAmelCase_  (		unittest.TestCase		):
     __lowerCamelCase      				=  MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING




     def   __UpperCAmelCase  (				self	,						_lowerCAmelCase	,						_lowerCAmelCase	,						_lowerCAmelCase		):
          UpperCAmelCase__      :  Dict				      =			pipeline(
              """zero-shot-object-detection"""	,						model="""hf-internal-testing/tiny-random-owlvit-object-detection"""		)

          UpperCAmelCase__      :  Dict				      =			[
              {
                  """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""",
                  """candidate_labels""": ["""cat""", """remote""", """couch"""],
              }
          ]
          return object_detector, examples




     def   __UpperCAmelCase  (				self	,						_lowerCAmelCase	,						_lowerCAmelCase		):
          UpperCAmelCase__      :  Tuple				      =			object_detector(examples[0]	,						threshold=0.0		)

          UpperCAmelCase__      :  List[str]				      =			len(_lowerCAmelCase		)
          self.assertGreater(_lowerCAmelCase	,						0		)
          self.assertEqual(
              _lowerCAmelCase	,						[
                  {
                      """score""": ANY(_lowerCAmelCase		),
                      """label""": ANY(_lowerCAmelCase		),
                      """box""": {"""xmin""": ANY(_lowerCAmelCase		), """ymin""": ANY(_lowerCAmelCase		), """xmax""": ANY(_lowerCAmelCase		), """ymax""": ANY(_lowerCAmelCase		)},
                  }
                  for i in range(_lowerCAmelCase		)
              ]	,						)




     @require_tf
     @unittest.skip("""Zero Shot Object Detection not implemented in TF"""		)
     def   __UpperCAmelCase  (				self		):
          pass




     @require_torch
     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  List[str]				      =			pipeline(
              """zero-shot-object-detection"""	,						model="""hf-internal-testing/tiny-random-owlvit-object-detection"""		)

          UpperCAmelCase__      :  str				      =			object_detector(
              """./tests/fixtures/tests_samples/COCO/000000039769.png"""	,						candidate_labels=["""cat""", """remote""", """couch"""]	,						threshold=0.6_4	,						)

          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						decimals=4		)	,						[
                  {"""score""": 0.7_2_3_5, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
                  {"""score""": 0.7_2_1_8, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
                  {"""score""": 0.7_1_8_4, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
                  {"""score""": 0.6_7_4_8, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
                  {"""score""": 0.6_6_5_6, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
                  {"""score""": 0.6_6_1_4, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
                  {"""score""": 0.6_4_5_6, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
                  {"""score""": 0.6_4_2, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}},
                  {"""score""": 0.6_4_1_9, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
              ]	,						)

          UpperCAmelCase__      :  int				      =			object_detector(
              [
                  {
                      """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""",
                      """candidate_labels""": ["""cat""", """remote""", """couch"""],
                  }
              ]	,						threshold=0.6_4	,						)

          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						decimals=4		)	,						[
                  [
                      {"""score""": 0.7_2_3_5, """label""": """cat""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
                      {"""score""": 0.7_2_1_8, """label""": """remote""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
                      {"""score""": 0.7_1_8_4, """label""": """couch""", """box""": {"""xmin""": 204, """ymin""": 167, """xmax""": 232, """ymax""": 190}},
                      {"""score""": 0.6_7_4_8, """label""": """remote""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
                      {"""score""": 0.6_6_5_6, """label""": """cat""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
                      {"""score""": 0.6_6_1_4, """label""": """couch""", """box""": {"""xmin""": 571, """ymin""": 83, """xmax""": 598, """ymax""": 103}},
                      {"""score""": 0.6_4_5_6, """label""": """remote""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
                      {"""score""": 0.6_4_2, """label""": """remote""", """box""": {"""xmin""": 67, """ymin""": 274, """xmax""": 93, """ymax""": 297}},
                      {"""score""": 0.6_4_1_9, """label""": """cat""", """box""": {"""xmin""": 494, """ymin""": 105, """xmax""": 521, """ymax""": 127}},
                  ]
              ]	,						)




     @require_torch
     @slow
     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Optional[Any]				      =			pipeline("""zero-shot-object-detection"""		)

          UpperCAmelCase__      :  Optional[Any]				      =			object_detector(
              """http://images.cocodataset.org/val2017/000000039769.jpg"""	,						candidate_labels=["""cat""", """remote""", """couch"""]	,						)
          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						decimals=4		)	,						[
                  {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
                  {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
                  {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
                  {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}},
                  {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}},
              ]	,						)

          UpperCAmelCase__      :  Union[str, Any]				      =			object_detector(
              [
                  {
                      """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""",
                      """candidate_labels""": ["""cat""", """remote""", """couch"""],
                  },
                  {
                      """image""": """http://images.cocodataset.org/val2017/000000039769.jpg""",
                      """candidate_labels""": ["""cat""", """remote""", """couch"""],
                  },
              ]	,						)
          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						decimals=4		)	,						[
                  [
                      {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
                      {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
                      {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
                      {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}},
                      {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}},
                  ],
                  [
                      {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
                      {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
                      {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
                      {"""score""": 0.1_4_7_4, """label""": """remote""", """box""": {"""xmin""": 335, """ymin""": 74, """xmax""": 371, """ymax""": 187}},
                      {"""score""": 0.1_2_0_8, """label""": """couch""", """box""": {"""xmin""": 4, """ymin""": 0, """xmax""": 642, """ymax""": 476}},
                  ],
              ]	,						)




     @require_tf
     @unittest.skip("""Zero Shot Object Detection not implemented in TF"""		)
     def   __UpperCAmelCase  (				self		):
          pass




     @require_torch
     @slow
     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  List[Any]				      =			0.2
          UpperCAmelCase__      :  List[Any]				      =			pipeline("""zero-shot-object-detection"""		)

          UpperCAmelCase__      :  Tuple				      =			object_detector(
              """http://images.cocodataset.org/val2017/000000039769.jpg"""	,						candidate_labels=["""cat""", """remote""", """couch"""]	,						threshold=_lowerCAmelCase	,						)
          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						decimals=4		)	,						[
                  {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
                  {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
                  {"""score""": 0.2_5_3_7, """label""": """cat""", """box""": {"""xmin""": 1, """ymin""": 55, """xmax""": 315, """ymax""": 472}},
              ]	,						)




     @require_torch
     @slow
     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Optional[Any]				      =			2
          UpperCAmelCase__      :  int				      =			pipeline("""zero-shot-object-detection"""		)

          UpperCAmelCase__      :  Any				      =			object_detector(
              """http://images.cocodataset.org/val2017/000000039769.jpg"""	,						candidate_labels=["""cat""", """remote""", """couch"""]	,						top_k=_lowerCAmelCase	,						)
          self.assertEqual(
              nested_simplify(_lowerCAmelCase	,						decimals=4		)	,						[
                  {"""score""": 0.2_8_6_8, """label""": """cat""", """box""": {"""xmin""": 324, """ymin""": 20, """xmax""": 640, """ymax""": 373}},
                  {"""score""": 0.2_7_7, """label""": """remote""", """box""": {"""xmin""": 40, """ymin""": 72, """xmax""": 177, """ymax""": 115}},
              ]	,						)







"""simple docstring"""




from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
			import numpy
			import tensorflow as tf

			from transformers import (
			    TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
			    TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
			    TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
			    BertConfig,
			    DPRConfig,
			    TFDPRContextEncoder,
			    TFDPRQuestionEncoder,
			    TFDPRReader,
			)

class    a_   :




					def __init__(						self    :  Union[str, Any]	,    snake_case__    :  Dict	,    snake_case__    :  int=13	,    snake_case__    :  List[str]=7	,    snake_case__    :  Any=True	,    snake_case__    :  Any=True	,    snake_case__    :  Dict=True	,    snake_case__    :  List[Any]=True	,    snake_case__    :  List[str]=99	,    snake_case__    :  Any=32	,    snake_case__    :  List[str]=2	,    snake_case__    :  Any=4	,    snake_case__    :  Dict=37	,    snake_case__    :  Optional[int]="gelu"	,    snake_case__    :  Optional[int]=0.1	,    snake_case__    :  Dict=0.1	,    snake_case__    :  Optional[int]=512	,    snake_case__    :  Union[str, Any]=16	,    snake_case__    :  str=2	,    snake_case__    :  Dict=0.02	,    snake_case__    :  Tuple=3	,    snake_case__    :  List[Any]=4	,    snake_case__    :  List[Any]=None	,    snake_case__    :  str=0	,    ):
							lowerCAmelCase__   = parent
							lowerCAmelCase__   = batch_size
							lowerCAmelCase__   = seq_length
							lowerCAmelCase__   = is_training
							lowerCAmelCase__   = use_input_mask
							lowerCAmelCase__   = use_token_type_ids
							lowerCAmelCase__   = use_labels
							lowerCAmelCase__   = vocab_size
							lowerCAmelCase__   = hidden_size
							lowerCAmelCase__   = num_hidden_layers
							lowerCAmelCase__   = num_attention_heads
							lowerCAmelCase__   = intermediate_size
							lowerCAmelCase__   = hidden_act
							lowerCAmelCase__   = hidden_dropout_prob
							lowerCAmelCase__   = attention_probs_dropout_prob
							lowerCAmelCase__   = max_position_embeddings
							lowerCAmelCase__   = type_vocab_size
							lowerCAmelCase__   = type_sequence_label_size
							lowerCAmelCase__   = initializer_range
							lowerCAmelCase__   = num_labels
							lowerCAmelCase__   = num_choices
							lowerCAmelCase__   = scope
							lowerCAmelCase__   = projection_dim




					def     _SCREAMING_SNAKE_CASE    (						self    :  Optional[int]  ):
							lowerCAmelCase__   = ids_tensor([self.batch_size, self.seq_length]	,    self.vocab_size  )

							lowerCAmelCase__   = None
							if self.use_input_mask:
									# follow test_modeling_tf_ctrl.py
									lowerCAmelCase__   = random_attention_mask([self.batch_size, self.seq_length]  )

							lowerCAmelCase__   = None
							if self.use_token_type_ids:
									lowerCAmelCase__   = ids_tensor([self.batch_size, self.seq_length]	,    self.type_vocab_size  )

							lowerCAmelCase__   = None
							lowerCAmelCase__   = None
							lowerCAmelCase__   = None
							if self.use_labels:
									lowerCAmelCase__   = ids_tensor([self.batch_size]	,    self.type_sequence_label_size  )
									lowerCAmelCase__   = ids_tensor([self.batch_size, self.seq_length]	,    self.num_labels  )
									lowerCAmelCase__   = ids_tensor([self.batch_size]	,    self.num_choices  )

							lowerCAmelCase__   = BertConfig(
							    vocab_size=self.vocab_size	,    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	,    max_position_embeddings=self.max_position_embeddings	,    type_vocab_size=self.type_vocab_size	,    is_decoder=snake_case__	,    initializer_range=self.initializer_range	,    )
							lowerCAmelCase__   = DPRConfig(projection_dim=self.projection_dim	,    **config.to_dict()  )

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels




					def     _SCREAMING_SNAKE_CASE    (						self    :  Optional[Any]	,    snake_case__    :  int	,    snake_case__    :  Optional[int]	,    snake_case__    :  Optional[Any]	,    snake_case__    :  str	,    snake_case__    :  Tuple	,    snake_case__    :  Dict	,    snake_case__    :  List[Any]  ):
							lowerCAmelCase__   = TFDPRContextEncoder(config=snake_case__  )
							lowerCAmelCase__   = model(snake_case__	,    attention_mask=snake_case__	,    token_type_ids=snake_case__  )
							lowerCAmelCase__   = model(snake_case__	,    token_type_ids=snake_case__  )
							lowerCAmelCase__   = model(snake_case__  )
							self.parent.assertEqual(result.pooler_output.shape	,    (self.batch_size, self.projection_dim or self.hidden_size)  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  Any	,    snake_case__    :  str	,    snake_case__    :  Dict	,    snake_case__    :  str	,    snake_case__    :  Any	,    snake_case__    :  Union[str, Any]	,    snake_case__    :  List[str]	,    snake_case__    :  Dict  ):
							lowerCAmelCase__   = TFDPRQuestionEncoder(config=snake_case__  )
							lowerCAmelCase__   = model(snake_case__	,    attention_mask=snake_case__	,    token_type_ids=snake_case__  )
							lowerCAmelCase__   = model(snake_case__	,    token_type_ids=snake_case__  )
							lowerCAmelCase__   = model(snake_case__  )
							self.parent.assertEqual(result.pooler_output.shape	,    (self.batch_size, self.projection_dim or self.hidden_size)  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  Tuple	,    snake_case__    :  Tuple	,    snake_case__    :  Any	,    snake_case__    :  str	,    snake_case__    :  Tuple	,    snake_case__    :  List[str]	,    snake_case__    :  List[str]	,    snake_case__    :  Tuple  ):
							lowerCAmelCase__   = TFDPRReader(config=snake_case__  )
							lowerCAmelCase__   = model(snake_case__	,    attention_mask=snake_case__  )

							self.parent.assertEqual(result.start_logits.shape	,    (self.batch_size, self.seq_length)  )
							self.parent.assertEqual(result.end_logits.shape	,    (self.batch_size, self.seq_length)  )
							self.parent.assertEqual(result.relevance_logits.shape	,    (self.batch_size,)  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  Any  ):
							lowerCAmelCase__   = self.prepare_config_and_inputs()
							(
							    (
							    lowerCAmelCase__
							) ,       (
							    lowerCAmelCase__
							) ,       (
							    lowerCAmelCase__
							) ,       (
							    lowerCAmelCase__
							) ,       (
							    lowerCAmelCase__
							) ,       (
							    lowerCAmelCase__
							) ,       (
							    lowerCAmelCase__
							) ,       
							)   = config_and_inputs
							lowerCAmelCase__   = {"""input_ids""": input_ids}
							return config, inputs_dict

@require_tf
class    a_   (  __UpperCamelCase			,		__UpperCamelCase			,		unittest.TestCase      ):
					UpperCamelCase_			:						Optional[Any]      =     (
					    (
					        TFDPRContextEncoder,
					        TFDPRQuestionEncoder,
					        TFDPRReader,
					    )
					    if is_tf_available()
					    else ()
					)
					UpperCamelCase_			:						Any      =     {"feature-extraction": TFDPRQuestionEncoder} if is_tf_available() else {}

					UpperCamelCase_			:						Optional[Any]      =     False
					UpperCamelCase_			:						Tuple      =     False
					UpperCamelCase_			:						Tuple      =     False
					UpperCamelCase_			:						Optional[int]      =     False
					UpperCamelCase_			:						Optional[Any]      =     False




					def     _SCREAMING_SNAKE_CASE    (						self    :  Any  ):
							lowerCAmelCase__   = TFDPRModelTester(self  )
							lowerCAmelCase__   = ConfigTester(self	,    config_class=snake_case__	,    hidden_size=37  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  Optional[int]  ):
							self.config_tester.run_common_tests()




					def     _SCREAMING_SNAKE_CASE    (						self    :  Dict  ):
							lowerCAmelCase__   = self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_dpr_context_encoder(*snake_case__  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  Tuple  ):
							lowerCAmelCase__   = self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_dpr_question_encoder(*snake_case__  )




					def     _SCREAMING_SNAKE_CASE    (						self    :  int  ):
							lowerCAmelCase__   = self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_dpr_reader(*snake_case__  )




					@slow
					def     _SCREAMING_SNAKE_CASE    (						self    :  List[Any]  ):
							for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowerCAmelCase__   = TFDPRContextEncoder.from_pretrained(snake_case__  )
									self.assertIsNotNone(snake_case__  )

							for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowerCAmelCase__   = TFDPRContextEncoder.from_pretrained(snake_case__  )
									self.assertIsNotNone(snake_case__  )

							for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowerCAmelCase__   = TFDPRQuestionEncoder.from_pretrained(snake_case__  )
									self.assertIsNotNone(snake_case__  )

							for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowerCAmelCase__   = TFDPRReader.from_pretrained(snake_case__  )
									self.assertIsNotNone(snake_case__  )

@require_tf
class    a_   (  unittest.TestCase      ):




					@slow
					def     _SCREAMING_SNAKE_CASE    (						self    :  List[str]  ):
							lowerCAmelCase__   = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base"""  )

							lowerCAmelCase__   = tf.constant(
							    [[101, 7592, 1010, 2003, 2026, 3899, 10140, 1029, 102]]  )  # [CLS] hello, is my dog cute? [SEP]
							lowerCAmelCase__   = model(snake_case__  )[0]  # embedding shape = (1, 768)
							# compare the actual values for a slice.
							lowerCAmelCase__   = tf.constant(
							    [
							        [
							            0.0323_6253,
							            0.1275_3335,
							            0.1681_8509,
							            0.0027_9786,
							            0.389_6933,
							            0.2426_4945,
							            0.217_8971,
							            -0.0233_5227,
							            -0.0848_1959,
							            -0.1432_4117,
							        ]
							    ]  )
							self.assertTrue(numpy.allclose(output[:, :10].numpy()	,    expected_slice.numpy()	,    atol=1E-4  )  )




