





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       (  _a							):






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      tempfile.mkdtemp()
														UpperCamelCase__					  =      8

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

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






							def 					_lowerCamelCase		(    self	):
														return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname	,			"""dpr_tokenizer"""	)	)






							def 					_lowerCamelCase		(    self	):
														return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname	,			"""bart_tokenizer"""	)	)






							def 					_lowerCamelCase		(    self	):
														shutil.rmtree(self.tmpdirname	)






							@require_tokenizers
							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      os.path.join(self.tmpdirname	,			"""rag_tokenizer"""	)
														UpperCamelCase__					  =      RagConfig(question_encoder=DPRConfig().to_dict()	,			generator=BartConfig().to_dict()	)
														UpperCamelCase__					  =      RagTokenizer(question_encoder=self.get_dpr_tokenizer()	,			generator=self.get_bart_tokenizer()	)
														rag_config.save_pretrained(__lowerCAmelCase	)
														rag_tokenizer.save_pretrained(__lowerCAmelCase	)
														UpperCamelCase__					  =      RagTokenizer.from_pretrained(__lowerCAmelCase	,			config=__lowerCAmelCase	)
														self.assertIsInstance(new_rag_tokenizer.question_encoder	,			__lowerCAmelCase	)
														self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab()	,			rag_tokenizer.question_encoder.get_vocab()	)
														self.assertIsInstance(new_rag_tokenizer.generator	,			__lowerCAmelCase	)
														self.assertEqual(new_rag_tokenizer.generator.get_vocab()	,			rag_tokenizer.generator.get_vocab()	)






							@slow
							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      RagTokenizer.from_pretrained("""facebook/rag-token-nq"""	)
														UpperCamelCase__					  =      [
														    """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__					  =      tokenizer(__lowerCAmelCase	)
														self.assertIsNotNone(__lowerCAmelCase	)







							@slow
							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      RagTokenizer.from_pretrained("""facebook/rag-sequence-nq"""	)
														UpperCamelCase__					  =      [
														    """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__					  =      tokenizer(__lowerCAmelCase	)
														self.assertIsNotNone(__lowerCAmelCase	)











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_big_bird import BigBirdTokenizer
else:
					UpperCamelCase__           =			None

UpperCamelCase__           =			logging.get_logger(__name__)
UpperCamelCase__           =			{"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}

UpperCamelCase__           =			{
    "vocab_file": {
        "google/bigbird-roberta-base": "https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model",
        "google/bigbird-roberta-large": (
            "https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model"
        ),
        "google/bigbird-base-trivia-itc": (
            "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model"
        ),
    },
    "tokenizer_file": {
        "google/bigbird-roberta-base": (
            "https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json"
        ),
        "google/bigbird-roberta-large": (
            "https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json"
        ),
        "google/bigbird-base-trivia-itc": (
            "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json"
        ),
    },
}

UpperCamelCase__           =			{
    "google/bigbird-roberta-base": 4_096,
    "google/bigbird-roberta-large": 4_096,
    "google/bigbird-base-trivia-itc": 4_096,
}


UpperCamelCase__           =			"▁"

class 							__SCREAMING_SNAKE_CASE       (  _a							):
							snake_case  :   Optional[Any]      =							VOCAB_FILES_NAMES
							snake_case  :   List[str]      =							PRETRAINED_VOCAB_FILES_MAP
							snake_case  :   List[str]      =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							snake_case  :   int      =							BigBirdTokenizer
							snake_case  :   List[Any]      =							["""input_ids""", """attention_mask"""]
							snake_case  :   List[int]      =							[]






							def __init__(    self	,			__lowerCAmelCase=None	,			__lowerCAmelCase=None	,			__lowerCAmelCase="<unk>"	,			__lowerCAmelCase="<s>"	,			__lowerCAmelCase="</s>"	,			__lowerCAmelCase="<pad>"	,			__lowerCAmelCase="[SEP]"	,			__lowerCAmelCase="[MASK]"	,			__lowerCAmelCase="[CLS]"	,			**__lowerCAmelCase	,			):
														UpperCamelCase__					  =      AddedToken(__lowerCAmelCase	,			lstrip=__lowerCAmelCase	,			rstrip=__lowerCAmelCase	) if isinstance(__lowerCAmelCase	,			__lowerCAmelCase	) else bos_token
														UpperCamelCase__					  =      AddedToken(__lowerCAmelCase	,			lstrip=__lowerCAmelCase	,			rstrip=__lowerCAmelCase	) if isinstance(__lowerCAmelCase	,			__lowerCAmelCase	) else eos_token
														UpperCamelCase__					  =      AddedToken(__lowerCAmelCase	,			lstrip=__lowerCAmelCase	,			rstrip=__lowerCAmelCase	) if isinstance(__lowerCAmelCase	,			__lowerCAmelCase	) else unk_token
														UpperCamelCase__					  =      AddedToken(__lowerCAmelCase	,			lstrip=__lowerCAmelCase	,			rstrip=__lowerCAmelCase	) if isinstance(__lowerCAmelCase	,			__lowerCAmelCase	) else pad_token
														UpperCamelCase__					  =      AddedToken(__lowerCAmelCase	,			lstrip=__lowerCAmelCase	,			rstrip=__lowerCAmelCase	) if isinstance(__lowerCAmelCase	,			__lowerCAmelCase	) else cls_token
														UpperCamelCase__					  =      AddedToken(__lowerCAmelCase	,			lstrip=__lowerCAmelCase	,			rstrip=__lowerCAmelCase	) if isinstance(__lowerCAmelCase	,			__lowerCAmelCase	) else sep_token

														# Mask token behave like a normal word, i.e. include the space before it
														UpperCamelCase__					  =      AddedToken(__lowerCAmelCase	,			lstrip=__lowerCAmelCase	,			rstrip=__lowerCAmelCase	) if isinstance(__lowerCAmelCase	,			__lowerCAmelCase	) else mask_token

														super().__init__(
														    __lowerCAmelCase	,			tokenizer_file=__lowerCAmelCase	,			bos_token=__lowerCAmelCase	,			eos_token=__lowerCAmelCase	,			unk_token=__lowerCAmelCase	,			sep_token=__lowerCAmelCase	,			pad_token=__lowerCAmelCase	,			cls_token=__lowerCAmelCase	,			mask_token=__lowerCAmelCase	,			**__lowerCAmelCase	,			)

														UpperCamelCase__					  =      vocab_file
														UpperCamelCase__					  =      False if not self.vocab_file else True






							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase	,			__lowerCAmelCase = None	):
														UpperCamelCase__					  =      [self.sep_token_id]
														UpperCamelCase__					  =      [self.cls_token_id]
														if token_ids_a is None:
																					return cls + token_ids_a + sep
														return cls + token_ids_a + sep + token_ids_a + sep






							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase	,			__lowerCAmelCase = None	,			__lowerCAmelCase = False	):

														if already_has_special_tokens:
																					if token_ids_a is not None:
																												raise ValueError(
																												    """You should not supply a second sequence if the provided sequence of """
																												    """ids is already formatted with special tokens for the model."""	)
																					return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]

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






							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase	,			__lowerCAmelCase = None	):
														UpperCamelCase__					  =      [self.sep_token_id]
														UpperCamelCase__					  =      [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 					_lowerCamelCase		(    self	,			__lowerCAmelCase	,			__lowerCAmelCase = None	):
														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
														UpperCamelCase__					  =      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,)




