






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 	snake_case__ :
	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__=5_12      ,       lowerCAmelCase__=16      ,       lowerCAmelCase__=2      ,       lowerCAmelCase__=0.0_2      ,       lowerCAmelCase__=3      ,       lowerCAmelCase__=4      ,       lowerCAmelCase__=None      ,       lowerCAmelCase__=0      ,       )							->				Optional[Any]:
							__magic_name__      :       Dict       						= parent
							__magic_name__      :       Union[str, Any]       						= batch_size
							__magic_name__      :       Optional[Any]       						= seq_length
							__magic_name__      :       Optional[Any]       						= is_training
							__magic_name__      :       Union[str, Any]       						= use_input_mask
							__magic_name__      :       List[Any]       						= use_token_type_ids
							__magic_name__      :       int       						= use_labels
							__magic_name__      :       Optional[int]       						= vocab_size
							__magic_name__      :       Dict       						= hidden_size
							__magic_name__      :       Any       						= num_hidden_layers
							__magic_name__      :       Optional[Any]       						= num_attention_heads
							__magic_name__      :       Any       						= intermediate_size
							__magic_name__      :       List[str]       						= hidden_act
							__magic_name__      :       List[Any]       						= hidden_dropout_prob
							__magic_name__      :       Tuple       						= attention_probs_dropout_prob
							__magic_name__      :       Optional[Any]       						= max_position_embeddings
							__magic_name__      :       Optional[int]       						= type_vocab_size
							__magic_name__      :       Optional[Any]       						= type_sequence_label_size
							__magic_name__      :       Optional[Any]       						= initializer_range
							__magic_name__      :       List[str]       						= num_labels
							__magic_name__      :       List[Any]       						= num_choices
							__magic_name__      :       List[str]       						= scope
							__magic_name__      :       str       						= projection_dim
	def       __magic_name__(    self			)							->				int:
							__magic_name__      :       int       						= ids_tensor([self.batch_size, self.seq_length]      ,       self.vocab_size			)

							__magic_name__      :       str       						= None
							if self.use_input_mask:
													# follow test_modeling_tf_ctrl.py
													__magic_name__      :       Optional[Any]       						= random_attention_mask([self.batch_size, self.seq_length]			)

							__magic_name__      :       Any       						= None
							if self.use_token_type_ids:
													__magic_name__      :       Optional[int]       						= ids_tensor([self.batch_size, self.seq_length]      ,       self.type_vocab_size			)

							__magic_name__      :       int       						= None
							__magic_name__      :       Optional[int]       						= None
							__magic_name__      :       Any       						= None
							if self.use_labels:
													__magic_name__      :       Optional[int]       						= ids_tensor([self.batch_size]      ,       self.type_sequence_label_size			)
													__magic_name__      :       Union[str, Any]       						= ids_tensor([self.batch_size, self.seq_length]      ,       self.num_labels			)
													__magic_name__      :       Tuple       						= ids_tensor([self.batch_size]      ,       self.num_choices			)

							__magic_name__      :       Dict       						= 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      ,       )
							__magic_name__      :       Optional[int]       						= 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       __magic_name__(    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				int:
							__magic_name__      :       Any       						= TFDPRContextEncoder(config=lowerCAmelCase__			)
							__magic_name__      :       Any       						= model(lowerCAmelCase__      ,       attention_mask=lowerCAmelCase__      ,       token_type_ids=lowerCAmelCase__			)
							__magic_name__      :       Dict       						= model(lowerCAmelCase__      ,       token_type_ids=lowerCAmelCase__			)
							__magic_name__      :       Dict       						= model(lowerCAmelCase__			)
							self.parent.assertEqual(result.pooler_output.shape      ,       (self.batch_size, self.projection_dim or self.hidden_size)			)
	def       __magic_name__(    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				int:
							__magic_name__      :       Any       						= TFDPRQuestionEncoder(config=lowerCAmelCase__			)
							__magic_name__      :       Any       						= model(lowerCAmelCase__      ,       attention_mask=lowerCAmelCase__      ,       token_type_ids=lowerCAmelCase__			)
							__magic_name__      :       Optional[int]       						= model(lowerCAmelCase__      ,       token_type_ids=lowerCAmelCase__			)
							__magic_name__      :       Tuple       						= model(lowerCAmelCase__			)
							self.parent.assertEqual(result.pooler_output.shape      ,       (self.batch_size, self.projection_dim or self.hidden_size)			)
	def       __magic_name__(    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				List[Any]:
							__magic_name__      :       Any       						= TFDPRReader(config=lowerCAmelCase__			)
							__magic_name__      :       Optional[int]       						= 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       __magic_name__(    self			)							->				int:
							__magic_name__      :       Optional[int]       						= self.prepare_config_and_inputs()
							(
							    __magic_name__
							)      :       Union[str, Any]       						= config_and_inputs
							__magic_name__      :       List[Any]       						= {"""input_ids""": input_ids}
							return config, inputs_dict





@require_tf
class 	snake_case__ (							_lowerCAmelCase						,  _lowerCAmelCase						,  unittest.TestCase				):
	lowercase__						:					Union[str, Any]											=   (
	    (
	        TFDPRContextEncoder,
	        TFDPRQuestionEncoder,
	        TFDPRReader,
	    )
	    if is_tf_available()
	    else ()
	)
	lowercase__						:					Tuple											=   {'''feature-extraction''': TFDPRQuestionEncoder} if is_tf_available() else {}

	lowercase__						:					Optional[int]											=   False
	lowercase__						:					str											=   False
	lowercase__						:					Dict											=   False
	lowercase__						:					int											=   False
	lowercase__						:					List[str]											=   False
	def       __magic_name__(    self			)							->				Optional[Any]:
							__magic_name__      :       Optional[Any]       						= TFDPRModelTester(self			)
							__magic_name__      :       str       						= ConfigTester(self      ,       config_class=lowerCAmelCase__      ,       hidden_size=37			)
	def       __magic_name__(    self			)							->				Dict:
							self.config_tester.run_common_tests()
	def       __magic_name__(    self			)							->				str:
							__magic_name__      :       List[str]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_dpr_context_encoder(*lowerCAmelCase__			)
	def       __magic_name__(    self			)							->				Any:
							__magic_name__      :       int       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_dpr_question_encoder(*lowerCAmelCase__			)
	def       __magic_name__(    self			)							->				List[str]:
							__magic_name__      :       List[Any]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_dpr_reader(*lowerCAmelCase__			)







	@slow
	def       __magic_name__(    self			)							->				Tuple:
							for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__magic_name__      :       Optional[int]       						= TFDPRContextEncoder.from_pretrained(lowerCAmelCase__			)
													self.assertIsNotNone(lowerCAmelCase__			)

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

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

							for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__magic_name__      :       Union[str, Any]       						= TFDPRReader.from_pretrained(lowerCAmelCase__			)
													self.assertIsNotNone(lowerCAmelCase__			)





@require_tf
class 	snake_case__ (							unittest.TestCase				):
	@slow
	def       __magic_name__(    self			)							->				str:
							__magic_name__      :       Any       						= TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base"""			)

							__magic_name__      :       List[str]       						= tf.constant(
							    [[1_01, 75_92, 10_10, 20_03, 20_26, 38_99, 1_01_40, 10_29, 1_02]]			)  # [CLS] hello, is my dog cute? [SEP]
							__magic_name__      :       Optional[int]       						= model(lowerCAmelCase__			)[0]  # embedding shape = (1, 768)
							# compare the actual values for a slice.
							__magic_name__      :       Any       						= tf.constant(
							    [
							        [
							            0.0_3_2_3_6_2_5_3,
							            0.1_2_7_5_3_3_3_5,
							            0.1_6_8_1_8_5_0_9,
							            0.0_0_2_7_9_7_8_6,
							            0.3_8_9_6_9_3_3,
							            0.2_4_2_6_4_9_4_5,
							            0.2_1_7_8_9_7_1,
							            -0.0_2_3_3_5_2_2_7,
							            -0.0_8_4_8_1_9_5_9,
							            -0.1_4_3_2_4_1_1_7,
							        ]
							    ]			)
							self.assertTrue(numpy.allclose(output[:, :10].numpy()      ,       expected_slice.numpy()      ,       atol=1e-4			)			)








import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
		from .tokenization_xlnet import XLNetTokenizer
else:
		__magic_name__:					Any							=     None


__magic_name__:					Dict							=     logging.get_logger(__name__)

__magic_name__:					Any							=     {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}

__magic_name__:					str							=     {
    "vocab_file": {
        "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model",
        "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model",
    },
    "tokenizer_file": {
        "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json",
        "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json",
    },
}

__magic_name__:					Optional[Any]							=     {
    "xlnet-base-cased": None,
    "xlnet-large-cased": None,
}

__magic_name__:					Optional[Any]							=     "▁"

# Segments (not really needed)
__magic_name__:					List[Any]							=     0
__magic_name__:					Dict							=     1
__magic_name__:					List[str]							=     2
__magic_name__:					List[Any]							=     3
__magic_name__:					Optional[int]							=     4





class 	snake_case__ (							_lowerCAmelCase				):
	lowercase__						:					Dict											=   VOCAB_FILES_NAMES
	lowercase__						:					Union[str, Any]											=   PRETRAINED_VOCAB_FILES_MAP
	lowercase__						:					Tuple											=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	lowercase__						:					List[str]											=   '''left'''
	lowercase__						:					List[str]											=   XLNetTokenizer
	def __init__(    self      ,       lowerCAmelCase__=None      ,       lowerCAmelCase__=None      ,       lowerCAmelCase__=False      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=False      ,       lowerCAmelCase__="<s>"      ,       lowerCAmelCase__="</s>"      ,       lowerCAmelCase__="<unk>"      ,       lowerCAmelCase__="<sep>"      ,       lowerCAmelCase__="<pad>"      ,       lowerCAmelCase__="<cls>"      ,       lowerCAmelCase__="<mask>"      ,       lowerCAmelCase__=["<eop>", "<eod>"]      ,       **lowerCAmelCase__      ,       )							->				Tuple:
							# Mask token behave like a normal word, i.e. include the space before it
							__magic_name__      :       Optional[int]       						= AddedToken(lowerCAmelCase__      ,       lstrip=lowerCAmelCase__      ,       rstrip=lowerCAmelCase__			) if isinstance(lowerCAmelCase__      ,       lowerCAmelCase__			) else mask_token

							super().__init__(
							    vocab_file=lowerCAmelCase__      ,       tokenizer_file=lowerCAmelCase__      ,       do_lower_case=lowerCAmelCase__      ,       remove_space=lowerCAmelCase__      ,       keep_accents=lowerCAmelCase__      ,       bos_token=lowerCAmelCase__      ,       eos_token=lowerCAmelCase__      ,       unk_token=lowerCAmelCase__      ,       sep_token=lowerCAmelCase__      ,       pad_token=lowerCAmelCase__      ,       cls_token=lowerCAmelCase__      ,       mask_token=lowerCAmelCase__      ,       additional_special_tokens=lowerCAmelCase__      ,       **lowerCAmelCase__      ,       )

							__magic_name__      :       List[str]       						= 3
							__magic_name__      :       str       						= do_lower_case
							__magic_name__      :       Union[str, Any]       						= remove_space
							__magic_name__      :       str       						= keep_accents
							__magic_name__      :       Tuple       						= vocab_file
							__magic_name__      :       List[Any]       						= False if not self.vocab_file else True
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__ = None			)							->				List[int]:
							__magic_name__      :       Any       						= [self.sep_token_id]
							__magic_name__      :       Any       						= [self.cls_token_id]
							if token_ids_a is None:
													return token_ids_a + sep + cls
							return token_ids_a + sep + token_ids_a + sep + cls
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__ = None			)							->				List[int]:
							__magic_name__      :       List[str]       						= [self.sep_token_id]
							__magic_name__      :       Optional[Any]       						= [2]

							if token_ids_a is None:
													return len(token_ids_a + sep			) * [0] + cls_segment_id
							return len(token_ids_a + sep			) * [0] + len(token_ids_a + sep			) * [1] + cls_segment_id







	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__ = None			)							->				Tuple[str]:
							if not self.can_save_slow_tokenizer:
													raise ValueError(
													    """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
													    """tokenizer."""			)

							if not os.path.isdir(lowerCAmelCase__			):
													logger.error(F'Vocabulary path ({save_directory}) should be a directory'			)
													return
							__magic_name__      :       List[str]       						= os.path.join(
							    lowerCAmelCase__      ,       (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]			)

							if os.path.abspath(self.vocab_file			) != os.path.abspath(lowerCAmelCase__			):
													copyfile(self.vocab_file      ,       lowerCAmelCase__			)

							return (out_vocab_file,)
