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   SCREAMING_SNAKE_CASE			(						__SCREAMING_SNAKE_CASE):







		"""simple docstring"""






		def 		UpperCamelCase__       (   self				) ->     List[Any]:
								_lowerCAmelCase										=tempfile.mkdtemp()
								_lowerCAmelCase										=8

								# DPR tok
								_lowerCAmelCase										=[
								    '''[UNK]''',
								    '''[CLS]''',
								    '''[SEP]''',
								    '''[PAD]''',
								    '''[MASK]''',
								    '''want''',
								    '''##want''',
								    '''##ed''',
								    '''wa''',
								    '''un''',
								    '''runn''',
								    '''##ing''',
								    ''',''',
								    '''low''',
								    '''lowest''',
								]
								_lowerCAmelCase										=os.path.join(self.tmpdirname		,						'dpr_tokenizer'				)
								os.makedirs(__snake_case		,						exist_ok=__snake_case				)
								_lowerCAmelCase										=os.path.join(__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
								_lowerCAmelCase										=[
								    '''l''',
								    '''o''',
								    '''w''',
								    '''e''',
								    '''r''',
								    '''s''',
								    '''t''',
								    '''i''',
								    '''d''',
								    '''n''',
								    '''\u0120''',
								    '''\u0120l''',
								    '''\u0120n''',
								    '''\u0120lo''',
								    '''\u0120low''',
								    '''er''',
								    '''\u0120lowest''',
								    '''\u0120newer''',
								    '''\u0120wider''',
								    '''<unk>''',
								]
								_lowerCAmelCase										=dict(zip(__snake_case		,						range(len(__snake_case				)				)				)				)
								_lowerCAmelCase										=['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
								_lowerCAmelCase										={'''unk_token''': '''<unk>'''}

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






		def 		UpperCamelCase__       (   self				) ->     str:
								return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname		,						'dpr_tokenizer'				)				)






		def 		UpperCamelCase__       (   self				) ->     Dict:
								return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname		,						'bart_tokenizer'				)				)






		def 		UpperCamelCase__       (   self				) ->     str:
								shutil.rmtree(self.tmpdirname				)






		@require_tokenizers
		def 		UpperCamelCase__       (   self				) ->     List[Any]:
								_lowerCAmelCase										=os.path.join(self.tmpdirname		,						'rag_tokenizer'				)
								_lowerCAmelCase										=RagConfig(question_encoder=DPRConfig().to_dict()		,						generator=BartConfig().to_dict()				)
								_lowerCAmelCase										=RagTokenizer(question_encoder=self.get_dpr_tokenizer()		,						generator=self.get_bart_tokenizer()				)
								rag_config.save_pretrained(__snake_case				)
								rag_tokenizer.save_pretrained(__snake_case				)
								_lowerCAmelCase										=RagTokenizer.from_pretrained(__snake_case		,						config=__snake_case				)
								self.assertIsInstance(new_rag_tokenizer.question_encoder		,						__snake_case				)
								self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab()		,						rag_tokenizer.question_encoder.get_vocab()				)
								self.assertIsInstance(new_rag_tokenizer.generator		,						__snake_case				)
								self.assertEqual(new_rag_tokenizer.generator.get_vocab()		,						rag_tokenizer.generator.get_vocab()				)






		@slow
		def 		UpperCamelCase__       (   self				) ->     Tuple:
								_lowerCAmelCase										=RagTokenizer.from_pretrained('facebook/rag-token-nq'				)
								_lowerCAmelCase										=[
								    '''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''',
								]
								_lowerCAmelCase										=tokenizer(__snake_case				)
								self.assertIsNotNone(__snake_case				)






		@slow
		def 		UpperCamelCase__       (   self				) ->     str:
								_lowerCAmelCase										=RagTokenizer.from_pretrained('facebook/rag-sequence-nq'				)
								_lowerCAmelCase										=[
								    '''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''',
								]
								_lowerCAmelCase										=tokenizer(__snake_case				)
								self.assertIsNotNone(__snake_case				)






'''simple docstring'''

import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_convbert import ConvBertTokenizer


lowercase_     		= logging.get_logger(__name__)

lowercase_     		= {'''vocab_file''': '''vocab.txt'''}

lowercase_     		= {
    '''vocab_file''': {
        '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt''',
        '''YituTech/conv-bert-medium-small''': (
            '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt'''
        ),
        '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt''',
    }
}

lowercase_     		= {
    '''YituTech/conv-bert-base''': 512,
    '''YituTech/conv-bert-medium-small''': 512,
    '''YituTech/conv-bert-small''': 512,
}


lowercase_     		= {
    '''YituTech/conv-bert-base''': {'''do_lower_case''': True},
    '''YituTech/conv-bert-medium-small''': {'''do_lower_case''': True},
    '''YituTech/conv-bert-small''': {'''do_lower_case''': True},
}
class   SCREAMING_SNAKE_CASE			(						__lowercase):







		"""simple docstring"""
		lowercase   :      Union[str, Any]       =							VOCAB_FILES_NAMES
		lowercase   :      Tuple       =							PRETRAINED_VOCAB_FILES_MAP
		lowercase   :      Optional[int]       =							PRETRAINED_INIT_CONFIGURATION
		lowercase   :      int       =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
		lowercase   :      List[str]       =							ConvBertTokenizer






		def __init__(   self		,						__A=None		,						__A=None		,						__A=True		,						__A="[UNK]"		,						__A="[SEP]"		,						__A="[PAD]"		,						__A="[CLS]"		,						__A="[MASK]"		,						__A=True		,						__A=None		,						**__A		,						) ->     Union[str, Any]:
								super().__init__(
								    __A		,						tokenizer_file=__A		,						do_lower_case=__A		,						unk_token=__A		,						sep_token=__A		,						pad_token=__A		,						cls_token=__A		,						mask_token=__A		,						tokenize_chinese_chars=__A		,						strip_accents=__A		,						**__A		,						)

								_lowerCAmelCase										=json.loads(self.backend_tokenizer.normalizer.__getstate__()				)
								if (
								    normalizer_state.get('lowercase'		,						__A				) != do_lower_case
								    or normalizer_state.get('strip_accents'		,						__A				) != strip_accents
								    or normalizer_state.get('handle_chinese_chars'		,						__A				) != tokenize_chinese_chars
								):
														_lowerCAmelCase										=getattr(__A		,						normalizer_state.pop('type'				)				)
														_lowerCAmelCase										=do_lower_case
														_lowerCAmelCase										=strip_accents
														_lowerCAmelCase										=tokenize_chinese_chars
														_lowerCAmelCase										=normalizer_class(**__A				)

								_lowerCAmelCase										=do_lower_case






		def 		UpperCamelCase__       (   self		,						__A		,						__A=None				) ->     int:
								_lowerCAmelCase										=[self.cls_token_id] + token_ids_a + [self.sep_token_id]

								if token_ids_a:
														output += token_ids_a + [self.sep_token_id]

								return output






		def 		UpperCamelCase__       (   self		,						__A		,						__A = None				) ->     List[int]:
								_lowerCAmelCase										=[self.sep_token_id]
								_lowerCAmelCase										=[self.cls_token_id]
								if token_ids_a is None:
														return len(cls + token_ids_a + sep				) * [0]
								return len(cls + token_ids_a + sep				) * [0] + len(token_ids_a + sep				) * [1]






		def 		UpperCamelCase__       (   self		,						__A		,						__A = None				) ->     Tuple[str]:
								_lowerCAmelCase										=self._tokenizer.model.save(__A		,						name=__A				)
								return tuple(__A				)





