





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    :

  """simple docstring"""


  def __init__(				self :		List[str]					,  lowerCAmelCase_ :		Any					,  lowerCAmelCase_ :		Any=1_3					,  lowerCAmelCase_ :		Optional[Any]=7					,  lowerCAmelCase_ :		str=True					,  lowerCAmelCase_ :		Dict=True					,  lowerCAmelCase_ :		Dict=True					,  lowerCAmelCase_ :		Tuple=True					,  lowerCAmelCase_ :		List[str]=9_9					,  lowerCAmelCase_ :		Any=3_2					,  lowerCAmelCase_ :		Dict=2					,  lowerCAmelCase_ :		Any=4					,  lowerCAmelCase_ :		Optional[Any]=3_7					,  lowerCAmelCase_ :		Any="gelu"					,  lowerCAmelCase_ :		Optional[int]=0.1					,  lowerCAmelCase_ :		Tuple=0.1					,  lowerCAmelCase_ :		Union[str, Any]=5_1_2					,  lowerCAmelCase_ :		Dict=1_6					,  lowerCAmelCase_ :		Any=2					,  lowerCAmelCase_ :		Tuple=0.02					,  lowerCAmelCase_ :		List[str]=3					,  lowerCAmelCase_ :		Optional[Any]=4					,  lowerCAmelCase_ :		List[str]=None					,  lowerCAmelCase_ :		List[str]=0					,  )							->						str:
     __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 				lowercase		(				self :		Dict     )							->						List[Any]:
     __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 				lowercase		(				self :		str					,  lowerCAmelCase_ :		Optional[Any]					,  lowerCAmelCase_ :		str					,  lowerCAmelCase_ :		str					,  lowerCAmelCase_ :		Dict					,  lowerCAmelCase_ :		str					,  lowerCAmelCase_ :		int					,  lowerCAmelCase_ :		Any     )							->						str:
     __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 				lowercase		(				self :		List[str]					,  lowerCAmelCase_ :		Dict					,  lowerCAmelCase_ :		Optional[int]					,  lowerCAmelCase_ :		Optional[int]					,  lowerCAmelCase_ :		Dict					,  lowerCAmelCase_ :		Union[str, Any]					,  lowerCAmelCase_ :		Optional[Any]					,  lowerCAmelCase_ :		Any     )							->						Tuple:
     __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 				lowercase		(				self :		Dict					,  lowerCAmelCase_ :		Union[str, Any]					,  lowerCAmelCase_ :		Any					,  lowerCAmelCase_ :		Optional[int]					,  lowerCAmelCase_ :		Dict					,  lowerCAmelCase_ :		List[str]					,  lowerCAmelCase_ :		Dict					,  lowerCAmelCase_ :		Tuple     )							->						Union[str, Any]:
     __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 				lowercase		(				self :		int     )							->						Optional[int]:
     __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    (    _UpperCamelCase		,    _UpperCamelCase		,    unittest.TestCase    ):

  """simple docstring"""


  a_        = (
      (
          TFDPRContextEncoder,
          TFDPRQuestionEncoder,
          TFDPRReader,
      )
      if is_tf_available()
      else ()
  )
  a_        = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {}

  a_        = False
  a_        = False
  a_        = False
  a_        = False
  a_        = False






  def 				lowercase		(				self :		List[Any]     )							->						Optional[int]:
     __lowerCAmelCase								=	TFDPRModelTester(self     )
     __lowerCAmelCase								=	ConfigTester(self					,  config_class=lowerCAmelCase_					,  hidden_size=3_7     )






  def 				lowercase		(				self :		Optional[int]     )							->						List[str]:
     self.config_tester.run_common_tests()






  def 				lowercase		(				self :		Any     )							->						Tuple:
     __lowerCAmelCase								=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_dpr_context_encoder(*lowerCAmelCase_     )






  def 				lowercase		(				self :		Any     )							->						List[Any]:
     __lowerCAmelCase								=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_dpr_question_encoder(*lowerCAmelCase_     )






  def 				lowercase		(				self :		str     )							->						List[str]:
     __lowerCAmelCase								=	self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_dpr_reader(*lowerCAmelCase_     )






  @slow
  def 				lowercase		(				self :		List[Any]     )							->						Tuple:
     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    ):

  """simple docstring"""


  @slow
  def 				lowercase		(				self :		Tuple     )							->						Optional[Any]:
     __lowerCAmelCase								=	TFDPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base'     )

     __lowerCAmelCase								=	tf.constant(
         [[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_0_3, 2_0_2_6, 3_8_9_9, 1_0_1_4_0, 1_0_2_9, 1_0_2]]     )  # [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[:, :1_0].numpy()					,  expected_slice.numpy()					,  atol=1e-4     )     )








import re

from filelock import FileLock


try:
     import nltk

     _snake_case  :    Any						    =  True
except (ImportError, ModuleNotFoundError):
     _snake_case  :    Union[str, Any]						    =  False

if NLTK_AVAILABLE:
     with FileLock('.lock') as lock:
          nltk.download('punkt', quiet=True)

def   a_    ( lowerCAmelCase_      :			str	):
   re.sub('<n>',	'',	lowerCAmelCase_	)  # remove pegasus newline char
   assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)"
   return "\n".join(nltk.sent_tokenize(lowerCAmelCase_	)	)

