





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   A							(						__lowercase    ):



      def 						lowerCAmelCase__     (						self:    Optional[int]							)    ->     str:
         '''simple docstring'''

         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:    Optional[Any]							)    ->     DPRQuestionEncoderTokenizer:
         '''simple docstring'''

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



      def 						lowerCAmelCase__     (						self:    List[str]							)    ->     BartTokenizer:
         '''simple docstring'''

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



      def 						lowerCAmelCase__     (						self:    str							)    ->     List[str]:
         '''simple docstring'''

         shutil.rmtree(self.tmpdirname							)



      @require_tokenizers
      def 						lowerCAmelCase__     (						self:    str							)    ->     int:
         '''simple docstring'''

         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:    Any							)    ->     Dict:
         '''simple docstring'''

         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:    Tuple							)    ->     Any:
         '''simple docstring'''

         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							)






"""simple docstring"""




import datasets

from .evaluate import evaluate


lowerCAmelCase__				=					'\\n@inproceedings{Rajpurkar2016SQuAD10,\n  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n  booktitle={EMNLP},\n  year={2016}\n}\n'

lowerCAmelCase__				=					'\nThis metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).\n\nStanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by\ncrowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,\nfrom the corresponding reading passage, or the question might be unanswerable.\n'

lowerCAmelCase__				=					'\nComputes SQuAD scores (F1 and EM).\nArgs:\n    predictions: List of question-answers dictionaries with the following key-values:\n        - \'id\': id of the question-answer pair as given in the references (see below)\n        - \'prediction_text\': the text of the answer\n    references: List of question-answers dictionaries with the following key-values:\n        - \'id\': id of the question-answer pair (see above),\n        - \'answers\': a Dict in the SQuAD dataset format\n            {\n                \'text\': list of possible texts for the answer, as a list of strings\n                \'answer_start\': list of start positions for the answer, as a list of ints\n            }\n            Note that answer_start values are not taken into account to compute the metric.\nReturns:\n    \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n    \'f1\': The F-score of predicted tokens versus the gold answer\nExamples:\n\n    >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\'}]\n    >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}]\n    >>> squad_metric = datasets.load_metric("squad")\n    >>> results = squad_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'exact_match\': 100.0, \'f1\': 100.0}\n'





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,      _KWARGS_DESCRIPTION )
class 			snake_case  (				datasets.Metric ):

							def _lowercase       (self     ):

									"""simple docstring"""







									return datasets.MetricInfo(
									    description=_DESCRIPTION							,							citation=_CITATION							,							inputs_description=_KWARGS_DESCRIPTION							,							features=datasets.Features(
									        {
									            '''predictions''': {'''id''': datasets.Value('''string'''     ), '''prediction_text''': datasets.Value('''string'''     )},
									            '''references''': {
									                '''id''': datasets.Value('''string'''     ),
									                '''answers''': datasets.features.Sequence(
									                    {
									                        '''text''': datasets.Value('''string'''     ),
									                        '''answer_start''': datasets.Value('''int32'''     ),
									                    }     ),
									            },
									        }     )							,							codebase_urls=['''https://rajpurkar.github.io/SQuAD-explorer/''']							,							reference_urls=['''https://rajpurkar.github.io/SQuAD-explorer/''']							,							)







							def _lowercase       (self							,							SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_     ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_    			=			{prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions}
									SCREAMING_SNAKE_CASE_    			=			[
									    {
									        '''paragraphs''': [
									            {
									                '''qas''': [
									                    {
									                        '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']],
									                        '''id''': ref['''id'''],
									                    }
									                    for ref in references
									                ]
									            }
									        ]
									    }
									]
									SCREAMING_SNAKE_CASE_    			=			evaluate(dataset=SCREAMING_SNAKE_CASE_							,							predictions=SCREAMING_SNAKE_CASE_     )
									return score