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





  def __init__(	self    ,     _lowerCamelCase    ,     _lowerCamelCase=13    ,     _lowerCamelCase=7    ,     _lowerCamelCase=True    ,     _lowerCamelCase=True    ,     _lowerCamelCase=True    ,     _lowerCamelCase=True    ,     _lowerCamelCase=99    ,     _lowerCamelCase=32    ,     _lowerCamelCase=2    ,     _lowerCamelCase=4    ,     _lowerCamelCase=37    ,     _lowerCamelCase="gelu"    ,     _lowerCamelCase=0.1    ,     _lowerCamelCase=0.1    ,     _lowerCamelCase=512    ,     _lowerCamelCase=16    ,     _lowerCamelCase=2    ,     _lowerCamelCase=0.02    ,     _lowerCamelCase=3    ,     _lowerCamelCase=4    ,     _lowerCamelCase=None    ,     _lowerCamelCase=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 						UpperCAmelCase_	(	self ):
     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=_lowerCamelCase    ,     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 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      TFDPRContextEncoder(config=_lowerCamelCase )
     lowerCAmelCase_			=      model(_lowerCamelCase    ,     attention_mask=_lowerCamelCase    ,     token_type_ids=_lowerCamelCase )
     lowerCAmelCase_			=      model(_lowerCamelCase    ,     token_type_ids=_lowerCamelCase )
     lowerCAmelCase_			=      model(_lowerCamelCase )
     self.parent.assertEqual(result.pooler_output.shape    ,     (self.batch_size, self.projection_dim or self.hidden_size) )





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      TFDPRQuestionEncoder(config=_lowerCamelCase )
     lowerCAmelCase_			=      model(_lowerCamelCase    ,     attention_mask=_lowerCamelCase    ,     token_type_ids=_lowerCamelCase )
     lowerCAmelCase_			=      model(_lowerCamelCase    ,     token_type_ids=_lowerCamelCase )
     lowerCAmelCase_			=      model(_lowerCamelCase )
     self.parent.assertEqual(result.pooler_output.shape    ,     (self.batch_size, self.projection_dim or self.hidden_size) )





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      TFDPRReader(config=_lowerCamelCase )
     lowerCAmelCase_			=      model(_lowerCamelCase    ,     attention_mask=_lowerCamelCase )

     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 						UpperCAmelCase_	(	self ):
     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     __UpperCAmelCase       ( lowercase_						,       lowercase_						,       unittest.TestCase		):
  __A :				List[Any]											= (
      (
          TFDPRContextEncoder,
          TFDPRQuestionEncoder,
          TFDPRReader,
      )
      if is_tf_available()
      else ()
  )
  __A :				Optional[int]											= {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {}

  __A :				Any											= False
  __A :				int											= False
  __A :				Union[str, Any]											= False
  __A :				List[str]											= False
  __A :				List[Any]											= False





  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      TFDPRModelTester(self )
     lowerCAmelCase_			=      ConfigTester(self    ,     config_class=_lowerCamelCase    ,     hidden_size=37 )





  def 						UpperCAmelCase_	(	self ):
     self.config_tester.run_common_tests()





  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_dpr_context_encoder(*_lowerCamelCase )





  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_dpr_question_encoder(*_lowerCamelCase )





  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_dpr_reader(*_lowerCamelCase )







  @slow
  def 						UpperCAmelCase_	(	self ):







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

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

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

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






@require_tf
class     __UpperCAmelCase       ( unittest.TestCase		):





  @slow
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      TFDPRQuestionEncoder.from_pretrained('''facebook/dpr-question_encoder-single-nq-base''' )

     lowerCAmelCase_			=      tf.constant(
         [[101, 7592, 1010, 2003, 2026, 3899, 1_0140, 1029, 102]] )  # [CLS] hello, is my dog cute? [SEP]
     lowerCAmelCase_			=      model(_lowerCamelCase )[0]  # embedding shape = (1, 768)
     # compare the actual values for a slice.
     lowerCAmelCase_			=      tf.constant(
         [
             [
                 0.03_23_62_53,
                 0.12_75_33_35,
                 0.16_81_85_09,
                 0.00_27_97_86,
                 0.3_89_69_33,
                 0.24_26_49_45,
                 0.2_17_89_71,
                 -0.02_33_52_27,
                 -0.08_48_19_59,
                 -0.14_32_41_17,
             ]
         ] )
     self.assertTrue(numpy.allclose(output[:, :10].numpy()    ,     expected_slice.numpy()    ,     atol=1E-4 ) )









'''simple docstring'''

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     __lowerCAmelCase		:





       '''simple docstring'''






       @staticmethod
       def  UpperCamelCase__						(*UpperCamelCase       :       Optional[Any]  ,		**UpperCamelCase       :       Tuple					):

              '''simple docstring'''







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





      '''simple docstring'''






      lowerCAmelCase__   :	Optional[int]       =				MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING



      def  UpperCamelCase__						(self       :       int  ,		UpperCamelCase       :       List[str]  ,		UpperCamelCase       :       List[str]  ,		UpperCamelCase       :       str					):

             '''simple docstring'''







             lowercase__      =					pipeline(
                 '''zero-shot-object-detection'''  ,		model='''hf-internal-testing/tiny-random-owlvit-object-detection'''					)

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



      def  UpperCamelCase__						(self       :       Optional[Any]  ,		UpperCamelCase       :       Tuple  ,		UpperCamelCase       :       Optional[int]					):

             '''simple docstring'''







             lowercase__      =					object_detector(examples[0]  ,		threshold=0.0					)

             lowercase__      =					len(UpperCamelCase					)
             self.assertGreater(UpperCamelCase  ,		0					)
             self.assertEqual(
                 UpperCamelCase  ,		[
                     {
                         '''score''': ANY(UpperCamelCase					),
                         '''label''': ANY(UpperCamelCase					),
                         '''box''': {'''xmin''': ANY(UpperCamelCase					), '''ymin''': ANY(UpperCamelCase					), '''xmax''': ANY(UpperCamelCase					), '''ymax''': ANY(UpperCamelCase					)},
                     }
                     for i in range(UpperCamelCase					)
                 ]  ,		)



      @require_tf
      @unittest.skip('''Zero Shot Object Detection not implemented in TF'''					)
      def  UpperCamelCase__						(self       :       str					):

             '''simple docstring'''







             pass



      @require_torch
      def  UpperCamelCase__						(self       :       Any					):

             '''simple docstring'''







             lowercase__      =					pipeline(
                 '''zero-shot-object-detection'''  ,		model='''hf-internal-testing/tiny-random-owlvit-object-detection'''					)

             lowercase__      =					object_detector(
                 '''./tests/fixtures/tests_samples/COCO/000000039769.png'''  ,		candidate_labels=['''cat''', '''remote''', '''couch''']  ,		threshold=0.64  ,		)

             self.assertEqual(
                 nested_simplify(UpperCamelCase  ,		decimals=4					)  ,		[
                     {'''score''': 0.72_35, '''label''': '''cat''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                     {'''score''': 0.72_18, '''label''': '''remote''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                     {'''score''': 0.71_84, '''label''': '''couch''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                     {'''score''': 0.67_48, '''label''': '''remote''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                     {'''score''': 0.66_56, '''label''': '''cat''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                     {'''score''': 0.66_14, '''label''': '''couch''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                     {'''score''': 0.64_56, '''label''': '''remote''', '''box''': {'''xmin''': 494, '''ymin''': 105, '''xmax''': 521, '''ymax''': 127}},
                     {'''score''': 0.6_42, '''label''': '''remote''', '''box''': {'''xmin''': 67, '''ymin''': 274, '''xmax''': 93, '''ymax''': 297}},
                     {'''score''': 0.64_19, '''label''': '''cat''', '''box''': {'''xmin''': 494, '''ymin''': 105, '''xmax''': 521, '''ymax''': 127}},
                 ]  ,		)

             lowercase__      =					object_detector(
                 [
                     {
                         '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''',
                         '''candidate_labels''': ['''cat''', '''remote''', '''couch'''],
                     }
                 ]  ,		threshold=0.64  ,		)

             self.assertEqual(
                 nested_simplify(UpperCamelCase  ,		decimals=4					)  ,		[
                     [
                         {'''score''': 0.72_35, '''label''': '''cat''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                         {'''score''': 0.72_18, '''label''': '''remote''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                         {'''score''': 0.71_84, '''label''': '''couch''', '''box''': {'''xmin''': 204, '''ymin''': 167, '''xmax''': 232, '''ymax''': 190}},
                         {'''score''': 0.67_48, '''label''': '''remote''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                         {'''score''': 0.66_56, '''label''': '''cat''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                         {'''score''': 0.66_14, '''label''': '''couch''', '''box''': {'''xmin''': 571, '''ymin''': 83, '''xmax''': 598, '''ymax''': 103}},
                         {'''score''': 0.64_56, '''label''': '''remote''', '''box''': {'''xmin''': 494, '''ymin''': 105, '''xmax''': 521, '''ymax''': 127}},
                         {'''score''': 0.6_42, '''label''': '''remote''', '''box''': {'''xmin''': 67, '''ymin''': 274, '''xmax''': 93, '''ymax''': 297}},
                         {'''score''': 0.64_19, '''label''': '''cat''', '''box''': {'''xmin''': 494, '''ymin''': 105, '''xmax''': 521, '''ymax''': 127}},
                     ]
                 ]  ,		)



      @require_torch
      @slow
      def  UpperCamelCase__						(self       :       str					):

             '''simple docstring'''







             lowercase__      =					pipeline('''zero-shot-object-detection'''					)

             lowercase__      =					object_detector(
                 '''http://images.cocodataset.org/val2017/000000039769.jpg'''  ,		candidate_labels=['''cat''', '''remote''', '''couch''']  ,		)
             self.assertEqual(
                 nested_simplify(UpperCamelCase  ,		decimals=4					)  ,		[
                     {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                     {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                     {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 315, '''ymax''': 472}},
                     {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 335, '''ymin''': 74, '''xmax''': 371, '''ymax''': 187}},
                     {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 642, '''ymax''': 476}},
                 ]  ,		)

             lowercase__      =					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(UpperCamelCase  ,		decimals=4					)  ,		[
                     [
                         {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                         {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                         {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 315, '''ymax''': 472}},
                         {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 335, '''ymin''': 74, '''xmax''': 371, '''ymax''': 187}},
                         {'''score''': 0.12_08, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 642, '''ymax''': 476}},
                     ],
                     [
                         {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                         {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                         {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 315, '''ymax''': 472}},
                         {'''score''': 0.14_74, '''label''': '''remote''', '''box''': {'''xmin''': 335, '''ymin''': 74, '''xmax''': 371, '''ymax''': 187}},
                         {'''score''': 0.12_08, '''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       :       int					):

             '''simple docstring'''







             pass



      @require_torch
      @slow
      def  UpperCamelCase__						(self       :       Tuple					):

             '''simple docstring'''







             lowercase__      =					0.2
             lowercase__      =					pipeline('''zero-shot-object-detection'''					)

             lowercase__      =					object_detector(
                 '''http://images.cocodataset.org/val2017/000000039769.jpg'''  ,		candidate_labels=['''cat''', '''remote''', '''couch''']  ,		threshold=UpperCamelCase  ,		)
             self.assertEqual(
                 nested_simplify(UpperCamelCase  ,		decimals=4					)  ,		[
                     {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                     {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                     {'''score''': 0.25_37, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 315, '''ymax''': 472}},
                 ]  ,		)






      @require_torch
      @slow
      def  UpperCamelCase__						(self       :       Dict					):

             '''simple docstring'''







             lowercase__      =					2
             lowercase__      =					pipeline('''zero-shot-object-detection'''					)

             lowercase__      =					object_detector(
                 '''http://images.cocodataset.org/val2017/000000039769.jpg'''  ,		candidate_labels=['''cat''', '''remote''', '''couch''']  ,		top_k=UpperCamelCase  ,		)
             self.assertEqual(
                 nested_simplify(UpperCamelCase  ,		decimals=4					)  ,		[
                     {'''score''': 0.28_68, '''label''': '''cat''', '''box''': {'''xmin''': 324, '''ymin''': 20, '''xmax''': 640, '''ymax''': 373}},
                     {'''score''': 0.2_77, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 177, '''ymax''': 115}},
                 ]  ,		)




