
import json
import os
import shutil
import tempfile
from unittest import TestCase

from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow
from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available


if is_torch_available() and is_datasets_available() and is_faiss_available():
    from transformers.models.rag.configuration_rag import RagConfig
    from transformers.models.rag.tokenization_rag import RagTokenizer




@require_faiss
@require_torch
class 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     def  __SCREAMING_SNAKE_CASE      (				self	)	-> str:




           """simple docstring"""







           UpperCamelCase__     : Any											=					tempfile.mkdtemp()
           UpperCamelCase__     : List[str]											=					8

           # DPR tok
           UpperCamelCase__     : str											=					[
               '''[UNK]''',
               '''[CLS]''',
               '''[SEP]''',
               '''[PAD]''',
               '''[MASK]''',
               '''want''',
               '''##want''',
               '''##ed''',
               '''wa''',
               '''un''',
               '''runn''',
               '''##ing''',
               ''',''',
               '''low''',
               '''lowest''',
           ]
           UpperCamelCase__     : Optional[int]											=					os.path.join(self.tmpdirname    ,    '''dpr_tokenizer'''	)
           os.makedirs(__SCREAMING_SNAKE_CASE    ,    exist_ok=__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : Tuple											=					os.path.join(__SCREAMING_SNAKE_CASE    ,    DPR_VOCAB_FILES_NAMES['''vocab_file''']	)
           with open(self.vocab_file    ,    '''w'''    ,    encoding='''utf-8'''	) as vocab_writer:
                 vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]	)	)

           # BART tok
           UpperCamelCase__     : str											=					[
               '''l''',
               '''o''',
               '''w''',
               '''e''',
               '''r''',
               '''s''',
               '''t''',
               '''i''',
               '''d''',
               '''n''',
               '''\u0120''',
               '''\u0120l''',
               '''\u0120n''',
               '''\u0120lo''',
               '''\u0120low''',
               '''er''',
               '''\u0120lowest''',
               '''\u0120newer''',
               '''\u0120wider''',
               '''<unk>''',
           ]
           UpperCamelCase__     : Optional[int]											=					dict(zip(__SCREAMING_SNAKE_CASE    ,    range(len(__SCREAMING_SNAKE_CASE	)	)	)	)
           UpperCamelCase__     : int											=					['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
           UpperCamelCase__     : Optional[Any]											=					{'''unk_token''': '''<unk>'''}

           UpperCamelCase__     : List[Any]											=					os.path.join(self.tmpdirname    ,    '''bart_tokenizer'''	)
           os.makedirs(__SCREAMING_SNAKE_CASE    ,    exist_ok=__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : Tuple											=					os.path.join(__SCREAMING_SNAKE_CASE    ,    BART_VOCAB_FILES_NAMES['''vocab_file''']	)
           UpperCamelCase__     : str											=					os.path.join(__SCREAMING_SNAKE_CASE    ,    BART_VOCAB_FILES_NAMES['''merges_file''']	)
           with open(self.vocab_file    ,    '''w'''    ,    encoding='''utf-8'''	) as fp:
                 fp.write(json.dumps(__SCREAMING_SNAKE_CASE	) + '''\n'''	)
           with open(self.merges_file    ,    '''w'''    ,    encoding='''utf-8'''	) as fp:
                 fp.write('''\n'''.join(__SCREAMING_SNAKE_CASE	)	)






     def  __SCREAMING_SNAKE_CASE      (				self	)	-> DPRQuestionEncoderTokenizer:




           """simple docstring"""







           return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname    ,    '''dpr_tokenizer'''	)	)






     def  __SCREAMING_SNAKE_CASE      (				self	)	-> BartTokenizer:




           """simple docstring"""







           return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname    ,    '''bart_tokenizer'''	)	)






     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Optional[Any]:




           """simple docstring"""







           shutil.rmtree(self.tmpdirname	)






     @require_tokenizers
     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Tuple:




           """simple docstring"""







           UpperCamelCase__     : List[Any]											=					os.path.join(self.tmpdirname    ,    '''rag_tokenizer'''	)
           UpperCamelCase__     : Dict											=					RagConfig(question_encoder=DPRConfig().to_dict()    ,    generator=BartConfig().to_dict()	)
           UpperCamelCase__     : List[str]											=					RagTokenizer(question_encoder=self.get_dpr_tokenizer()    ,    generator=self.get_bart_tokenizer()	)
           rag_config.save_pretrained(__SCREAMING_SNAKE_CASE	)
           rag_tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : List[str]											=					RagTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE    ,    config=__SCREAMING_SNAKE_CASE	)
           self.assertIsInstance(new_rag_tokenizer.question_encoder    ,    __SCREAMING_SNAKE_CASE	)
           self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab()    ,    rag_tokenizer.question_encoder.get_vocab()	)
           self.assertIsInstance(new_rag_tokenizer.generator    ,    __SCREAMING_SNAKE_CASE	)
           self.assertEqual(new_rag_tokenizer.generator.get_vocab()    ,    rag_tokenizer.generator.get_vocab()	)






     @slow
     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Union[str, Any]:




           """simple docstring"""







           UpperCamelCase__     : List[Any]											=					RagTokenizer.from_pretrained('''facebook/rag-token-nq'''	)
           UpperCamelCase__     : Union[str, Any]											=					[
               '''who got the first nobel prize in physics''',
               '''when is the next deadpool movie being released''',
               '''which mode is used for short wave broadcast service''',
               '''who is the owner of reading football club''',
               '''when is the next scandal episode coming out''',
               '''when is the last time the philadelphia won the superbowl''',
               '''what is the most current adobe flash player version''',
               '''how many episodes are there in dragon ball z''',
               '''what is the first step in the evolution of the eye''',
               '''where is gall bladder situated in human body''',
               '''what is the main mineral in lithium batteries''',
               '''who is the president of usa right now''',
               '''where do the greasers live in the outsiders''',
               '''panda is a national animal of which country''',
               '''what is the name of manchester united stadium''',
           ]
           UpperCamelCase__     : Union[str, Any]											=					tokenizer(__SCREAMING_SNAKE_CASE	)
           self.assertIsNotNone(__SCREAMING_SNAKE_CASE	)






     @slow
     def  __SCREAMING_SNAKE_CASE      (				self	)	-> List[str]:




           """simple docstring"""







           UpperCamelCase__     : int											=					RagTokenizer.from_pretrained('''facebook/rag-sequence-nq'''	)
           UpperCamelCase__     : str											=					[
               '''who got the first nobel prize in physics''',
               '''when is the next deadpool movie being released''',
               '''which mode is used for short wave broadcast service''',
               '''who is the owner of reading football club''',
               '''when is the next scandal episode coming out''',
               '''when is the last time the philadelphia won the superbowl''',
               '''what is the most current adobe flash player version''',
               '''how many episodes are there in dragon ball z''',
               '''what is the first step in the evolution of the eye''',
               '''where is gall bladder situated in human body''',
               '''what is the main mineral in lithium batteries''',
               '''who is the president of usa right now''',
               '''where do the greasers live in the outsiders''',
               '''panda is a national animal of which country''',
               '''what is the name of manchester united stadium''',
           ]
           UpperCamelCase__     : str											=					tokenizer(__SCREAMING_SNAKE_CASE	)
           self.assertIsNotNone(__SCREAMING_SNAKE_CASE	)




from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase  =logging.get_logger(__name__)

lowerCamelCase  ={
    "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/config.json",
    "distilbert-base-uncased-distilled-squad": (
        "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json"
    ),
    "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/config.json",
    "distilbert-base-cased-distilled-squad": (
        "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json"
    ),
    "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json",
    "distilbert-base-multilingual-cased": (
        "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json"
    ),
    "distilbert-base-uncased-finetuned-sst-2-english": (
        "https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json"
    ),
}




class 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		 =	'''distilbert'''
     SCREAMING_SNAKE_CASE_		 =	{
         '''hidden_size''': '''dim''',
         '''num_attention_heads''': '''n_heads''',
         '''num_hidden_layers''': '''n_layers''',
     }






     def __init__(				self    ,    __SCREAMING_SNAKE_CASE=3_0_5_2_2    ,    __SCREAMING_SNAKE_CASE=5_1_2    ,    __SCREAMING_SNAKE_CASE=False    ,    __SCREAMING_SNAKE_CASE=6    ,    __SCREAMING_SNAKE_CASE=1_2    ,    __SCREAMING_SNAKE_CASE=7_6_8    ,    __SCREAMING_SNAKE_CASE=4 * 7_6_8    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE="gelu"    ,    __SCREAMING_SNAKE_CASE=0.02    ,    __SCREAMING_SNAKE_CASE=0.1    ,    __SCREAMING_SNAKE_CASE=0.2    ,    __SCREAMING_SNAKE_CASE=0    ,    **__SCREAMING_SNAKE_CASE    ,    )	-> Optional[Any]:




           """simple docstring"""







           UpperCamelCase__     : List[Any]											=					vocab_size
           UpperCamelCase__     : Dict											=					max_position_embeddings
           UpperCamelCase__     : Any											=					sinusoidal_pos_embds
           UpperCamelCase__     : Dict											=					n_layers
           UpperCamelCase__     : List[Any]											=					n_heads
           UpperCamelCase__     : Dict											=					dim
           UpperCamelCase__     : Dict											=					hidden_dim
           UpperCamelCase__     : Optional[int]											=					dropout
           UpperCamelCase__     : Optional[Any]											=					attention_dropout
           UpperCamelCase__     : Tuple											=					activation
           UpperCamelCase__     : Optional[int]											=					initializer_range
           UpperCamelCase__     : Optional[int]											=					qa_dropout
           UpperCamelCase__     : str											=					seq_classif_dropout
           super().__init__(**__SCREAMING_SNAKE_CASE    ,    pad_token_id=__SCREAMING_SNAKE_CASE	)




class 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     @property
     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Mapping[str, Mapping[int, str]]:




           """simple docstring"""







           if self.task == "multiple-choice":
                 UpperCamelCase__     : Union[str, Any]											=					{0: '''batch''', 1: '''choice''', 2: '''sequence'''}
           else:
                 UpperCamelCase__     : int											=					{0: '''batch''', 1: '''sequence'''}
           return OrderedDict(
               [
                   ('''input_ids''', dynamic_axis),
                   ('''attention_mask''', dynamic_axis),
               ]	)


