



'''simple docstring'''



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 _UpperCamelCase						(   UpperCAmelCase_						):





				'''simple docstring'''





				def  __lowerCamelCase   (							self     :     Optional[Any]):







											'''simple docstring'''

											__lowercase						=tempfile.mkdtemp()
											__lowercase						=8

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

											__lowercase						=os.path.join(self.tmpdirname     ,				'bart_tokenizer')
											os.makedirs(lowerCAmelCase__     ,				exist_ok=lowerCAmelCase__)
											__lowercase						=os.path.join(lowerCAmelCase__     ,				BART_VOCAB_FILES_NAMES['vocab_file'])
											__lowercase						=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     :     Union[str, Any]):







											'''simple docstring'''

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

				def  __lowerCamelCase   (							self     :     List[Any]):







											'''simple docstring'''

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

				def  __lowerCamelCase   (							self     :     Optional[int]):







											'''simple docstring'''

											shutil.rmtree(self.tmpdirname)

				@require_tokenizers
				def  __lowerCamelCase   (							self     :     Any):







											'''simple docstring'''

											__lowercase						=os.path.join(self.tmpdirname     ,				'rag_tokenizer')
											__lowercase						=RagConfig(question_encoder=DPRConfig().to_dict()     ,				generator=BartConfig().to_dict())
											__lowercase						=RagTokenizer(question_encoder=self.get_dpr_tokenizer()     ,				generator=self.get_bart_tokenizer())
											rag_config.save_pretrained(lowerCAmelCase__)
											rag_tokenizer.save_pretrained(lowerCAmelCase__)
											__lowercase						=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     :     List[str]):







											'''simple docstring'''

											__lowercase						=RagTokenizer.from_pretrained('facebook/rag-token-nq')
											__lowercase						=[
											    "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",
											]
											__lowercase						=tokenizer(lowerCAmelCase__)
											self.assertIsNotNone(lowerCAmelCase__)

				@slow
				def  __lowerCamelCase   (							self     :     List[str]):







											'''simple docstring'''

											__lowercase						=RagTokenizer.from_pretrained('facebook/rag-sequence-nq')
											__lowercase						=[
											    "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",
											]
											__lowercase						=tokenizer(lowerCAmelCase__)
											self.assertIsNotNone(lowerCAmelCase__)






from collections.abc import Callable



class   __lowercase				:




			"""simple docstring"""







			def __init__( self  :     Tuple   ,						lowerCAmelCase__  :     Callable | None = None):
									# Stores actual heap items.
									SCREAMING_SNAKE_CASE_: list  		=       []
									# Stores indexes of each item for supporting updates and deletion.
									SCREAMING_SNAKE_CASE_: dict  		=       {}
									# Stores current size of heap.
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       0
									# Stores function used to evaluate the score of an item on which basis ordering
									# will be done.
									SCREAMING_SNAKE_CASE_: Any  		=       key or (lambda lowerCAmelCase__: x)



			def        _SCREAMING_SNAKE_CASE			( self  :     Dict   ,						lowerCAmelCase__  :     int):
									return int((i - 1) / 2) if i > 0 else None



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]   ,						lowerCAmelCase__  :     int):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       int(2 * i + 1)
									return left if 0 < left < self.size else None



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]   ,						lowerCAmelCase__  :     int):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       int(2 * i + 2)
									return right if 0 < right < self.size else None



			def        _SCREAMING_SNAKE_CASE			( self  :     str   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     int):
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: str  		=       (
									    self.pos_map[self.arr[j][0]],
									    self.pos_map[self.arr[i][0]],
									)
									# Then swap the items in the list.
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: List[str]  		=       self.arr[j], self.arr[i]



			def        _SCREAMING_SNAKE_CASE			( self  :     str   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     int):
									return self.arr[i][1] < self.arr[j][1]



			def        _SCREAMING_SNAKE_CASE			( self  :     str   ,						lowerCAmelCase__  :     int):
									SCREAMING_SNAKE_CASE_: Any  		=       self._left(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: List[Any]  		=       self._right(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: List[Any]  		=       i

									if left is not None and not self._cmp(lowerCAmelCase__   ,						lowerCAmelCase__):
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       left
									if right is not None and not self._cmp(lowerCAmelCase__   ,						lowerCAmelCase__):
															SCREAMING_SNAKE_CASE_: Tuple  		=       right

									return valid_parent



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]   ,						lowerCAmelCase__  :     int):
									SCREAMING_SNAKE_CASE_: List[Any]  		=       self._parent(lowerCAmelCase__)
									while parent is not None and not self._cmp(lowerCAmelCase__   ,						lowerCAmelCase__):
															self._swap(lowerCAmelCase__   ,						lowerCAmelCase__)
															SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: List[str]  		=       parent, self._parent(lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]   ,						lowerCAmelCase__  :     int):
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       self._get_valid_parent(lowerCAmelCase__)
									while valid_parent != index:
															self._swap(lowerCAmelCase__   ,						lowerCAmelCase__)
															SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Dict  		=       valid_parent, self._get_valid_parent(lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     int):
									if item not in self.pos_map:
															return
									SCREAMING_SNAKE_CASE_: Any  		=       self.pos_map[item]
									SCREAMING_SNAKE_CASE_: int  		=       [item, self.key(lowerCAmelCase__)]
									# Make sure heap is right in both up and down direction.
									# Ideally only one of them will make any change.
									self._heapify_up(lowerCAmelCase__)
									self._heapify_down(lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     List[str]   ,						lowerCAmelCase__  :     int):
									if item not in self.pos_map:
															return
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.pos_map[item]
									del self.pos_map[item]
									SCREAMING_SNAKE_CASE_: List[str]  		=       self.arr[self.size - 1]
									SCREAMING_SNAKE_CASE_: Tuple  		=       index
									self.size -= 1
									# Make sure heap is right in both up and down direction. Ideally only one
									# of them will make any change- so no performance loss in calling both.
									if self.size > index:
															self._heapify_up(lowerCAmelCase__)
															self._heapify_down(lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     int):
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       len(self.arr)
									if arr_len == self.size:
															self.arr.append([item, self.key(lowerCAmelCase__)])
									else:
															SCREAMING_SNAKE_CASE_: str  		=       [item, self.key(lowerCAmelCase__)]
									SCREAMING_SNAKE_CASE_: List[Any]  		=       self.size
									self.size += 1
									self._heapify_up(self.size - 1)



			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									return self.arr[0] if self.size else None




			def        _SCREAMING_SNAKE_CASE			( self  :     Dict):
									SCREAMING_SNAKE_CASE_: Dict  		=       self.get_top()
									if top_item_tuple:
															self.delete_item(top_item_tuple[0])
									return top_item_tuple







def 			A_      (    ):
						pass


if __name__ == "__main__":
						import doctest

						doctest.testmod()






