





import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
      from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
      from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Union[str, Any]     )      ->						Tuple:
  return 1.0 / (1.0 + np.exp(-_outputs     ))

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Dict     )      ->						Dict:
  _lowercase							= np.max(_outputs			,							axis=-1			,							keepdims=snake_case__     )
  _lowercase							= np.exp(_outputs - maxes     )
  return shifted_exp / shifted_exp.sum(axis=-1			,							keepdims=snake_case__     )





class 				A_				(      UpperCAmelCase	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Optional[Any]      =  '''sigmoid'''
       SCREAMING_SNAKE_CASE_      : Optional[int]      =  '''softmax'''
       SCREAMING_SNAKE_CASE_      : Optional[Any]      =  '''none'''





@add_end_docstrings(
    UpperCAmelCase					,	r'''
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `"default"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `"sigmoid"`: Applies the sigmoid function on the output.
            - `"softmax"`: Applies the softmax function on the output.
            - `"none"`: Does not apply any function on the output.
    '''					,	)
class 				A_				(      UpperCAmelCase	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Union[str, Any]      =  False
       SCREAMING_SNAKE_CASE_      : Tuple      =  ClassificationFunction.NONE







       def __init__(    self	:	List[str]						,**__A	:	Union[str, Any]  )						->					int:
         super().__init__(**__A  )

         self.check_model_type(
             TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
             if self.framework == 'tf'
             else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING  )







       def    __UpperCAmelCase (    self	:	Optional[int]						,__A	:	int=None						,__A	:	Tuple=None						,__A	:	Any=""						,**__A	:	str  )						->					int:
         # Using "" as default argument because we're going to use `top_k=None` in user code to declare
         # "No top_k"
         _lowercase							= tokenizer_kwargs

         _lowercase							= {}
         if hasattr(self.model.config						,'return_all_scores'  ) and return_all_scores is None:
           _lowercase							= self.model.config.return_all_scores

         if isinstance(__A						,__A  ) or top_k is None:
           _lowercase							= top_k
           _lowercase							= False
         elif return_all_scores is not None:
           warnings.warn(
               '`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'
               ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'						,__A						,)
           if return_all_scores:
             _lowercase							= None
           else:
             _lowercase							= 1

         if isinstance(__A						,__A  ):
           _lowercase							= ClassificationFunction[function_to_apply.upper()]

         if function_to_apply is not None:
           _lowercase							= function_to_apply
         return preprocess_params, {}, postprocess_params







       def __call__(    self	:	Dict						,*__A	:	Any						,**__A	:	Union[str, Any]  )						->					str:
         _lowercase							= super().__call__(*__A						,**__A  )
         # TODO try and retrieve it in a nicer way from _sanitize_parameters.
         _lowercase							= 'top_k' not in kwargs
         if isinstance(args[0]						,__A  ) and _legacy:
           # This pipeline is odd, and return a list when single item is run
           return [result]
         else:
           return result







       def    __UpperCAmelCase (    self	:	Union[str, Any]						,__A	:	Optional[Any]						,**__A	:	Optional[Any]  )						->					Dict[str, GenericTensor]:
         _lowercase							= self.framework
         if isinstance(__A						,__A  ):
           return self.tokenizer(**__A						,return_tensors=__A						,**__A  )
         elif isinstance(__A						,__A  ) and len(__A  ) == 1 and isinstance(inputs[0]						,__A  ) and len(inputs[0]  ) == 2:
           # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
           return self.tokenizer(
               text=inputs[0][0]						,text_pair=inputs[0][1]						,return_tensors=__A						,**__A  )
         elif isinstance(__A						,__A  ):
           # This is likely an invalid usage of the pipeline attempting to pass text pairs.
           raise ValueError(
               'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'
               ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'  )
         return self.tokenizer(__A						,return_tensors=__A						,**__A  )







       def    __UpperCAmelCase (    self	:	Optional[int]						,__A	:	List[str]  )						->					int:
         return self.model(**__A  )







       def    __UpperCAmelCase (    self	:	List[Any]						,__A	:	int						,__A	:	Optional[int]=None						,__A	:	Tuple=1						,__A	:	Dict=True  )						->					Optional[Any]:
         # `_legacy` is used to determine if we're running the naked pipeline and in backward
         # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
         # the more natural result containing the list.
         # Default value before `set_parameters`
         if function_to_apply is None:
           if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
             _lowercase							= ClassificationFunction.SIGMOID
           elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
             _lowercase							= ClassificationFunction.SOFTMAX
           elif hasattr(self.model.config						,'function_to_apply'  ) and function_to_apply is None:
             _lowercase							= self.model.config.function_to_apply
           else:
             _lowercase							= ClassificationFunction.NONE

         _lowercase							= model_outputs['logits'][0]
         _lowercase							= outputs.numpy()

         if function_to_apply == ClassificationFunction.SIGMOID:
           _lowercase							= sigmoid(__A  )
         elif function_to_apply == ClassificationFunction.SOFTMAX:
           _lowercase							= softmax(__A  )
         elif function_to_apply == ClassificationFunction.NONE:
           _lowercase							= outputs
         else:
           raise ValueError(F"""Unrecognized `function_to_apply` argument: {function_to_apply}"""  )

         if top_k == 1 and _legacy:
           return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

         _lowercase							= [
             {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__A  )
         ]
         if not _legacy:
           dict_scores.sort(key=lambda __A  : x["score"]						,reverse=__A  )
           if top_k is not None:
             _lowercase							= dict_scores[:top_k]
         return dict_scores






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







       """simple docstring"""





       def __init__(    self	:	Union[str, Any]						,__A	:	Tuple						,__A	:	Dict=13						,__A	:	Union[str, Any]=7						,__A	:	Optional[Any]=True						,__A	:	Dict=True						,__A	:	List[str]=True						,__A	:	int=True						,__A	:	str=99						,__A	:	Tuple=32						,__A	:	List[Any]=2						,__A	:	Dict=4						,__A	:	List[str]=37						,__A	:	Dict="gelu"						,__A	:	Optional[Any]=0.1						,__A	:	Dict=0.1						,__A	:	Dict=512						,__A	:	Any=16						,__A	:	Tuple=2						,__A	:	List[Any]=0.02						,__A	:	Any=3						,__A	:	Tuple=4						,__A	:	Dict=None						,__A	:	List[Any]=0						,)						->					Optional[Any]:
         _lowercase							= parent
         _lowercase							= batch_size
         _lowercase							= seq_length
         _lowercase							= is_training
         _lowercase							= use_input_mask
         _lowercase							= use_token_type_ids
         _lowercase							= use_labels
         _lowercase							= vocab_size
         _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							= max_position_embeddings
         _lowercase							= type_vocab_size
         _lowercase							= type_sequence_label_size
         _lowercase							= initializer_range
         _lowercase							= num_labels
         _lowercase							= num_choices
         _lowercase							= scope
         _lowercase							= projection_dim







       def    __UpperCAmelCase (    self	:	List[Any]  )						->					List[str]:
         _lowercase							= ids_tensor([self.batch_size, self.seq_length]						,self.vocab_size  )

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

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

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

         _lowercase							= 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=__A						,initializer_range=self.initializer_range						,)
         _lowercase							= 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	:	List[Any]						,__A	:	Dict						,__A	:	str						,__A	:	Any						,__A	:	Dict						,__A	:	Tuple						,__A	:	Tuple						,__A	:	int  )						->					List[str]:
         _lowercase							= TFDPRContextEncoder(config=__A  )
         _lowercase							= model(__A						,attention_mask=__A						,token_type_ids=__A  )
         _lowercase							= model(__A						,token_type_ids=__A  )
         _lowercase							= model(__A  )
         self.parent.assertEqual(result.pooler_output.shape						,(self.batch_size, self.projection_dim or self.hidden_size)  )







       def    __UpperCAmelCase (    self	:	List[Any]						,__A	:	Optional[Any]						,__A	:	Tuple						,__A	:	Optional[Any]						,__A	:	Union[str, Any]						,__A	:	Tuple						,__A	:	Tuple						,__A	:	Any  )						->					str:
         _lowercase							= TFDPRQuestionEncoder(config=__A  )
         _lowercase							= model(__A						,attention_mask=__A						,token_type_ids=__A  )
         _lowercase							= model(__A						,token_type_ids=__A  )
         _lowercase							= model(__A  )
         self.parent.assertEqual(result.pooler_output.shape						,(self.batch_size, self.projection_dim or self.hidden_size)  )







       def    __UpperCAmelCase (    self	:	int						,__A	:	List[str]						,__A	:	Optional[int]						,__A	:	List[str]						,__A	:	str						,__A	:	str						,__A	:	int						,__A	:	int  )						->					Optional[Any]:
         _lowercase							= TFDPRReader(config=__A  )
         _lowercase							= model(__A						,attention_mask=__A  )

         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	:	str  )						->					str:
         _lowercase							= self.prepare_config_and_inputs()
         (
             (
             _lowercase
         )						,		(
             _lowercase
         )						,		(
             _lowercase
         )						,		(
             _lowercase
         )						,		(
             _lowercase
         )						,		(
             _lowercase
         )						,		(
             _lowercase
         )						,		
         )							= config_and_inputs
         _lowercase							= {'input_ids': input_ids}
         return config, inputs_dict





@require_tf
class 				A_				(      UpperCAmelCase					,	UpperCAmelCase					,	unittest.TestCase	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Union[str, Any]      =  (
           (
               TFDPRContextEncoder,
               TFDPRQuestionEncoder,
               TFDPRReader,
           )
           if is_tf_available()
           else ()
       )
       SCREAMING_SNAKE_CASE_      : Optional[Any]      =  {'''feature-extraction''': TFDPRQuestionEncoder} if is_tf_available() else {}

       SCREAMING_SNAKE_CASE_      : List[Any]      =  False
       SCREAMING_SNAKE_CASE_      : Dict      =  False
       SCREAMING_SNAKE_CASE_      : int      =  False
       SCREAMING_SNAKE_CASE_      : List[Any]      =  False
       SCREAMING_SNAKE_CASE_      : Optional[int]      =  False







       def    __UpperCAmelCase (    self	:	List[str]  )						->					Optional[int]:
         _lowercase							= TFDPRModelTester(self  )
         _lowercase							= ConfigTester(self						,config_class=__A						,hidden_size=37  )







       def    __UpperCAmelCase (    self	:	Any  )						->					List[str]:
         self.config_tester.run_common_tests()







       def    __UpperCAmelCase (    self	:	Dict  )						->					Optional[int]:
         _lowercase							= self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_dpr_context_encoder(*__A  )







       def    __UpperCAmelCase (    self	:	Optional[Any]  )						->					Optional[Any]:
         _lowercase							= self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_dpr_question_encoder(*__A  )







       def    __UpperCAmelCase (    self	:	Dict  )						->					List[Any]:
         _lowercase							= self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_dpr_reader(*__A  )







       @slow
       def    __UpperCAmelCase (    self	:	Optional[Any]  )						->					str:
         for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _lowercase							= TFDPRContextEncoder.from_pretrained(__A  )
           self.assertIsNotNone(__A  )

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

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

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





@require_tf
class 				A_				(      unittest.TestCase	):







       """simple docstring"""





       @slow
       def    __UpperCAmelCase (    self	:	List[Any]  )						->					int:
         _lowercase							= TFDPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base'  )

         _lowercase							= tf.constant(
             [[101, 7592, 1010, 2003, 2026, 3899, 1_0140, 1029, 102]]  )  # [CLS] hello, is my dog cute? [SEP]
         _lowercase							= model(__A  )[0]  # embedding shape = (1, 768)
         # compare the actual values for a slice.
         _lowercase							= tf.constant(
             [
                 [
                     0.03236253,
                     0.12753335,
                     0.16818509,
                     0.00279786,
                     0.3896933,
                     0.24264945,
                     0.2178971,
                     -0.02335227,
                     -0.08481959,
                     -0.14324117,
                 ]
             ]  )
         self.assertTrue(numpy.allclose(output[:, :10].numpy()						,expected_slice.numpy()						,atol=1e-4  )  )