






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

					'''simple docstring'''

					def __init__(     self :		List[str]						,   __a :		int						,   __a :		Optional[Any]=13						,   __a :		List[str]=7						,   __a :		List[str]=True						,   __a :		Dict=True						,   __a :		int=True						,   __a :		Optional[int]=True						,   __a :		List[Any]=99						,   __a :		Optional[int]=32						,   __a :		Union[str, Any]=2						,   __a :		Optional[int]=4						,   __a :		Dict=37						,   __a :		Optional[int]="gelu"						,   __a :		Any=0.1						,   __a :		Any=0.1						,   __a :		Union[str, Any]=512						,   __a :		Any=16						,   __a :		Optional[Any]=2						,   __a :		Any=0.02						,   __a :		Tuple=3						,   __a :		int=4						,   __a :		Dict=None						,   __a :		str=0						,   )	->     List[Any]:


												"""simple docstring"""

												__lowercase					:							str			=   parent
												__lowercase					:							str			=   batch_size
												__lowercase					:							Tuple			=   seq_length
												__lowercase					:							Tuple			=   is_training
												__lowercase					:							Any			=   use_input_mask
												__lowercase					:							Any			=   use_token_type_ids
												__lowercase					:							Dict			=   use_labels
												__lowercase					:							Tuple			=   vocab_size
												__lowercase					:							Dict			=   hidden_size
												__lowercase					:							Optional[Any]			=   num_hidden_layers
												__lowercase					:							Union[str, Any]			=   num_attention_heads
												__lowercase					:							Optional[Any]			=   intermediate_size
												__lowercase					:							List[Any]			=   hidden_act
												__lowercase					:							Tuple			=   hidden_dropout_prob
												__lowercase					:							Any			=   attention_probs_dropout_prob
												__lowercase					:							int			=   max_position_embeddings
												__lowercase					:							int			=   type_vocab_size
												__lowercase					:							Optional[int]			=   type_sequence_label_size
												__lowercase					:							List[Any]			=   initializer_range
												__lowercase					:							Tuple			=   num_labels
												__lowercase					:							Tuple			=   num_choices
												__lowercase					:							int			=   scope
												__lowercase					:							List[str]			=   projection_dim



					def 					lowerCAmelCase (     self :		List[str]							)	->     List[Any]:


												"""simple docstring"""

												__lowercase					:							List[str]			=   ids_tensor([self.batch_size, self.seq_length]						,   self.vocab_size							)

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

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

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

												__lowercase					:							Any			=   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					:							Optional[Any]			=   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 					lowerCAmelCase (     self :		str						,   __a :		Union[str, Any]						,   __a :		Any						,   __a :		List[str]						,   __a :		Optional[int]						,   __a :		List[str]						,   __a :		Any						,   __a :		Union[str, Any]							)	->     int:


												"""simple docstring"""

												__lowercase					:							str			=   TFDPRContextEncoder(config=__a							)
												__lowercase					:							Union[str, Any]			=   model(__a						,   attention_mask=__a						,   token_type_ids=__a							)
												__lowercase					:							Dict			=   model(__a						,   token_type_ids=__a							)
												__lowercase					:							Optional[Any]			=   model(__a							)
												self.parent.assertEqual(result.pooler_output.shape						,   (self.batch_size, self.projection_dim or self.hidden_size)							)



					def 					lowerCAmelCase (     self :		str						,   __a :		Union[str, Any]						,   __a :		Tuple						,   __a :		Optional[Any]						,   __a :		Tuple						,   __a :		Optional[int]						,   __a :		List[str]						,   __a :		Tuple							)	->     str:


												"""simple docstring"""

												__lowercase					:							Union[str, Any]			=   TFDPRQuestionEncoder(config=__a							)
												__lowercase					:							Any			=   model(__a						,   attention_mask=__a						,   token_type_ids=__a							)
												__lowercase					:							str			=   model(__a						,   token_type_ids=__a							)
												__lowercase					:							List[str]			=   model(__a							)
												self.parent.assertEqual(result.pooler_output.shape						,   (self.batch_size, self.projection_dim or self.hidden_size)							)



					def 					lowerCAmelCase (     self :		List[str]						,   __a :		Any						,   __a :		Dict						,   __a :		Tuple						,   __a :		Dict						,   __a :		Optional[int]						,   __a :		List[str]						,   __a :		int							)	->     Optional[Any]:


												"""simple docstring"""

												__lowercase					:							List[str]			=   TFDPRReader(config=__a							)
												__lowercase					:							Any			=   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 					lowerCAmelCase (     self :		Dict							)	->     Union[str, Any]:


												"""simple docstring"""

												__lowercase					:							Union[str, Any]			=   self.prepare_config_and_inputs()
												(
												    (
												    __lowercase
												)	,	(
												    __lowercase
												)	,	(
												    __lowercase
												)	,	(
												    __lowercase
												)	,	(
												    __lowercase
												)	,	(
												    __lowercase
												)	,	(
												    __lowercase
												)	,	
												)					:							List[str]			=   config_and_inputs
												__lowercase					:							Optional[Any]			=   {"""input_ids""": input_ids}
												return config, inputs_dict







@require_tf
class 						lowerCAmelCase   (       __a					,				__a					,				unittest.TestCase	):

					'''simple docstring'''

					_A  :	str     =					(
					    (
					        TFDPRContextEncoder,
					        TFDPRQuestionEncoder,
					        TFDPRReader,
					    )
					    if is_tf_available()
					    else ()
					)
					_A  :	Dict     =					{'''feature-extraction''': TFDPRQuestionEncoder} if is_tf_available() else {}

					_A  :	int     =					False
					_A  :	int     =					False
					_A  :	Optional[Any]     =					False
					_A  :	List[str]     =					False
					_A  :	Tuple     =					False



					def 					lowerCAmelCase (     self :		Union[str, Any]							)	->     Union[str, Any]:


												"""simple docstring"""

												__lowercase					:							List[Any]			=   TFDPRModelTester(self							)
												__lowercase					:							Tuple			=   ConfigTester(self						,   config_class=__a						,   hidden_size=37							)



					def 					lowerCAmelCase (     self :		List[str]							)	->     List[Any]:


												"""simple docstring"""

												self.config_tester.run_common_tests()



					def 					lowerCAmelCase (     self :		str							)	->     Optional[Any]:


												"""simple docstring"""

												__lowercase					:							Optional[Any]			=   self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_dpr_context_encoder(*__a							)



					def 					lowerCAmelCase (     self :		Optional[int]							)	->     Optional[int]:


												"""simple docstring"""

												__lowercase					:							Any			=   self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_dpr_question_encoder(*__a							)



					def 					lowerCAmelCase (     self :		Tuple							)	->     Union[str, Any]:


												"""simple docstring"""

												__lowercase					:							Tuple			=   self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_dpr_reader(*__a							)



					@slow
					def 					lowerCAmelCase (     self :		str							)	->     Optional[int]:


												"""simple docstring"""

												for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			__lowercase					:							Optional[Any]			=   TFDPRContextEncoder.from_pretrained(__a							)
																			self.assertIsNotNone(__a							)

												for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			__lowercase					:							Optional[int]			=   TFDPRContextEncoder.from_pretrained(__a							)
																			self.assertIsNotNone(__a							)

												for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			__lowercase					:							Optional[int]			=   TFDPRQuestionEncoder.from_pretrained(__a							)
																			self.assertIsNotNone(__a							)

												for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			__lowercase					:							List[Any]			=   TFDPRReader.from_pretrained(__a							)
																			self.assertIsNotNone(__a							)







@require_tf
class 						lowerCAmelCase   (       unittest.TestCase	):

					'''simple docstring'''

					@slow
					def 					lowerCAmelCase (     self :		Any							)	->     Dict:


												"""simple docstring"""

												__lowercase					:							Union[str, Any]			=   TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base"""							)

												__lowercase					:							List[str]			=   tf.constant(
												    [[101, 7592, 1010, 2003, 2026, 3899, 10140, 1029, 102]]							)  # [CLS] hello, is my dog cute? [SEP]
												__lowercase					:							List[str]			=   model(__a							)[0]  # embedding shape = (1, 768)
												# compare the actual values for a slice.
												__lowercase					:							Any			=   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							)							)







lowerCamelCase       :       Optional[Any]        =				'''ABCDEFGHIJKLMNOPQRSTUVWXYZ'''
def 					snake_case_						(   ):
							__lowercase					:							List[str]			=   input("""Enter message: """					)
							__lowercase					:							int			=   input("""Enter key [alphanumeric]: """					)
							__lowercase					:							Optional[Any]			=   input("""Encrypt/Decrypt [e/d]: """					)

							if mode.lower().startswith("""e"""					):
														__lowercase					:							Optional[int]			=   """encrypt"""
														__lowercase					:							Dict			=   encrypt_message(lowerCAmelCase_				,				lowerCAmelCase_					)
							elif mode.lower().startswith("""d"""					):
														__lowercase					:							Union[str, Any]			=   """decrypt"""
														__lowercase					:							Optional[int]			=   decrypt_message(lowerCAmelCase_				,				lowerCAmelCase_					)

							print(F"\n{mode.title()}ed message:"					)
							print(lowerCAmelCase_					)
def 					snake_case_						(   lowerCAmelCase_				:  str				,				lowerCAmelCase_				:  str					):
							return translate_message(lowerCAmelCase_				,				lowerCAmelCase_				,				"""encrypt"""					)
def 					snake_case_						(   lowerCAmelCase_				:  str				,				lowerCAmelCase_				:  str					):
							return translate_message(lowerCAmelCase_				,				lowerCAmelCase_				,				"""decrypt"""					)
def 					snake_case_						(   lowerCAmelCase_				:  str				,				lowerCAmelCase_				:  str				,				lowerCAmelCase_				:  str					):
							__lowercase					:							Union[str, Any]			=   []
							__lowercase					:							Tuple			=   0
							__lowercase					:							Dict			=   key.upper()

							for symbol in message:
														__lowercase					:							Optional[Any]			=   LETTERS.find(symbol.upper()					)
														if num != -1:
																					if mode == "encrypt":
																												num += LETTERS.find(key[key_index]					)
																					elif mode == "decrypt":
																												num -= LETTERS.find(key[key_index]					)

																					num %= len(lowerCAmelCase_					)

																					if symbol.isupper():
																												translated.append(LETTERS[num]					)
																					elif symbol.islower():
																												translated.append(LETTERS[num].lower()					)

																					key_index += 1
																					if key_index == len(lowerCAmelCase_					):
																												__lowercase					:							str			=   0
														else:
																					translated.append(lowerCAmelCase_					)
							return "".join(lowerCAmelCase_					)


if __name__ == "__main__":
	main()