
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        lowercase	(      UpperCamelCase__	):




       def 				A__   (       self):
            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(__A     ,exist_ok=__A)
            lowercase					=		os.path.join(__A     ,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(__A     ,range(len(__A))))
            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(__A     ,exist_ok=__A)
            lowercase					=		os.path.join(__A     ,BART_VOCAB_FILES_NAMES['''vocab_file'''])
            lowercase					=		os.path.join(__A     ,BART_VOCAB_FILES_NAMES['''merges_file'''])
            with open(self.vocab_file     ,'''w'''     ,encoding='''utf-8''') as fp:
                 fp.write(json.dumps(__A) + '''\n''')
            with open(self.merges_file     ,'''w'''     ,encoding='''utf-8''') as fp:
                 fp.write('''\n'''.join(__A))




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




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




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




       @require_tokenizers
       def 				A__   (       self):
            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(__A)
            rag_tokenizer.save_pretrained(__A)
            lowercase					=		RagTokenizer.from_pretrained(__A     ,config=__A)
            self.assertIsInstance(new_rag_tokenizer.question_encoder     ,__A)
            self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab()     ,rag_tokenizer.question_encoder.get_vocab())
            self.assertIsInstance(new_rag_tokenizer.generator     ,__A)
            self.assertEqual(new_rag_tokenizer.generator.get_vocab()     ,rag_tokenizer.generator.get_vocab())




       @slow
       def 				A__   (       self):
            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(__A)
            self.assertIsNotNone(__A)





       @slow
       def 				A__   (       self):
            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(__A)
            self.assertIsNotNone(__A)






import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
							import torch_xla.core.xla_model as xm
							import torch_xla.debug.metrics as met







class        lowercase	(      SCREAMING_SNAKE_CASE__	):




							def __init__(       self     ,*A__     ,A__=None     ,A__=None     ,**A__):
												super().__init__(*A__     ,**A__)
												lowercase					=		eval_examples
												lowercase					=		post_process_function




							def 				A__   (       self     ,A__ = None     ,A__=None     ,A__ = None     ,A__ = "eval"     ,**A__     ,):
												lowercase					=		gen_kwargs.copy()
												lowercase					=		(
												    gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''') is not None else self.args.generation_max_length
												)
												lowercase					=		(
												    gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''') is not None else self.args.generation_num_beams
												)
												lowercase					=		gen_kwargs

												lowercase					=		self.eval_dataset if eval_dataset is None else eval_dataset
												lowercase					=		self.get_eval_dataloader(A__)
												lowercase					=		self.eval_examples if eval_examples is None else eval_examples

												# Temporarily disable metric computation, we will do it in the loop here.
												lowercase					=		self.compute_metrics
												lowercase					=		None
												lowercase					=		time.time()
												lowercase					=		self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
												try:
																	lowercase					=		eval_loop(
																	    A__     ,description='''Evaluation'''     ,prediction_loss_only=True if compute_metrics is None else None     ,ignore_keys=A__     ,metric_key_prefix=A__     ,)
												finally:
																	lowercase					=		compute_metrics
												lowercase					=		self.args.eval_batch_size * self.args.world_size
												if f'{metric_key_prefix}_jit_compilation_time' in output.metrics:
																	start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time']
												output.metrics.update(
												    speed_metrics(
												        A__     ,A__     ,num_samples=output.num_samples     ,num_steps=math.ceil(output.num_samples / total_batch_size)     ,))

												if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
																	# Only the main node write the results by default
																	lowercase					=		self.post_process_function(A__     ,A__     ,A__)
																	lowercase					=		self.compute_metrics(A__)

																	# Prefix all keys with metric_key_prefix + '_'
																	for key in list(metrics.keys()):
																						if not key.startswith(f'{metric_key_prefix}_'):
																											lowercase					=		metrics.pop(A__)

																	metrics.update(output.metrics)
												else:
																	lowercase					=		output.metrics

												if self.args.should_log:
																	# Only the main node log the results by default
																	self.log(A__)

												if self.args.tpu_metrics_debug or self.args.debug:
																	# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
																	xm.master_print(met.metrics_report())

												lowercase					=		self.callback_handler.on_evaluate(self.args     ,self.state     ,self.control     ,A__)
												return metrics





							def 				A__   (       self     ,A__     ,A__     ,A__=None     ,A__ = "test"     ,**A__):
												lowercase					=		gen_kwargs.copy()

												lowercase					=		self.get_test_dataloader(A__)

												# Temporarily disable metric computation, we will do it in the loop here.
												lowercase					=		self.compute_metrics
												lowercase					=		None
												lowercase					=		time.time()
												lowercase					=		self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
												try:
																	lowercase					=		eval_loop(
																	    A__     ,description='''Prediction'''     ,prediction_loss_only=True if compute_metrics is None else None     ,ignore_keys=A__     ,metric_key_prefix=A__     ,)
												finally:
																	lowercase					=		compute_metrics

												lowercase					=		self.args.eval_batch_size * self.args.world_size
												if f'{metric_key_prefix}_jit_compilation_time' in output.metrics:
																	start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time']
												output.metrics.update(
												    speed_metrics(
												        A__     ,A__     ,num_samples=output.num_samples     ,num_steps=math.ceil(output.num_samples / total_batch_size)     ,))
												if self.post_process_function is None or self.compute_metrics is None:
																	return output

												lowercase					=		self.post_process_function(A__     ,A__     ,A__     ,'''predict''')
												lowercase					=		self.compute_metrics(A__)

												# Prefix all keys with metric_key_prefix + '_'
												for key in list(metrics.keys()):
																	if not key.startswith(f'{metric_key_prefix}_'):
																						lowercase					=		metrics.pop(A__)
												metrics.update(output.metrics)
												return PredictionOutput(predictions=predictions.predictions     ,label_ids=predictions.label_ids     ,metrics=A__)




