

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



   def 	__magic_name__   (							self							:					int						):
     UpperCAmelCase	:							Optional[Any]						=			tempfile.mkdtemp()
     UpperCAmelCase	:							Dict						=			8

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

     UpperCAmelCase	:							int						=			os.path.join(self.tmpdirname,		'''bart_tokenizer'''						)
     os.makedirs(__A,		exist_ok=__A						)
     UpperCAmelCase	:							int						=			os.path.join(__A,		BART_VOCAB_FILES_NAMES['''vocab_file''']						)
     UpperCAmelCase	:							List[str]						=			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 	__magic_name__   (							self							:					int						):
     return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname,		'''dpr_tokenizer'''						)						)



   def 	__magic_name__   (							self							:					Optional[Any]						):
     return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname,		'''bart_tokenizer'''						)						)



   def 	__magic_name__   (							self							:					int						):
     shutil.rmtree(self.tmpdirname						)



   @require_tokenizers
   def 	__magic_name__   (							self							:					Any						):
     UpperCAmelCase	:							Dict						=			os.path.join(self.tmpdirname,		'''rag_tokenizer'''						)
     UpperCAmelCase	:							Tuple						=			RagConfig(question_encoder=DPRConfig().to_dict(),		generator=BartConfig().to_dict()						)
     UpperCAmelCase	:							List[str]						=			RagTokenizer(question_encoder=self.get_dpr_tokenizer(),		generator=self.get_bart_tokenizer()						)
     rag_config.save_pretrained(__A						)
     rag_tokenizer.save_pretrained(__A						)
     UpperCAmelCase	:							List[Any]						=			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 	__magic_name__   (							self							:					int						):
     UpperCAmelCase	:							int						=			RagTokenizer.from_pretrained('''facebook/rag-token-nq'''						)
     UpperCAmelCase	:							Optional[int]						=			[
         '''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	:							Optional[Any]						=			tokenizer(__A						)
     self.assertIsNotNone(__A						)





   @slow
   def 	__magic_name__   (							self							:					int						):
     UpperCAmelCase	:							Any						=			RagTokenizer.from_pretrained('''facebook/rag-sequence-nq'''						)
     UpperCAmelCase	:							List[Any]						=			[
         '''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	:							Optional[int]						=			tokenizer(__A						)
     self.assertIsNotNone(__A						)








import logging
import os

from .state import PartialState





class  __UpperCAmelCase					(	logging.LoggerAdapter						):



   @staticmethod
   def 	__magic_name__   (							__A							:					str						):
     UpperCAmelCase	:							Dict						=			PartialState()
     return not main_process_only or (main_process_only and state.is_main_process)





   def 	__magic_name__   (							self							:					Union[str, Any],		__A							:					Union[str, Any],		__A							:					Union[str, Any],		*__A							:					Optional[int],		**__A							:					Tuple						):
     if PartialState._shared_state == {}:
       raise RuntimeError(
           '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.'''						)
     UpperCAmelCase	:							List[str]						=			kwargs.pop('''main_process_only''',		__A						)
     UpperCAmelCase	:							int						=			kwargs.pop('''in_order''',		__A						)

     if self.isEnabledFor(__A						):
       if self._should_log(__A						):
         UpperCAmelCase			,						UpperCAmelCase	:							Dict						=			self.process(__A,		__A						)
         self.logger.log(__A,		__A,		*__A,		**__A						)

       elif in_order:
         UpperCAmelCase	:							Dict						=			PartialState()
         for i in range(state.num_processes						):
           if i == state.process_index:
             UpperCAmelCase			,						UpperCAmelCase	:							Optional[int]						=			self.process(__A,		__A						)
             self.logger.log(__A,		__A,		*__A,		**__A						)
           state.wait_for_everyone()






def       a__					(		UpperCAmelCase							:      str    ,			UpperCAmelCase							:      str = None      )  ->						Dict:
  if log_level is None:
    UpperCAmelCase	:							Union[str, Any]						=			os.environ.get('''ACCELERATE_LOG_LEVEL'''    ,			UpperCAmelCase      )
  UpperCAmelCase	:							Tuple						=			logging.getLogger(UpperCAmelCase      )
  if log_level is not None:
    logger.setLevel(log_level.upper()      )
    logger.root.setLevel(log_level.upper()      )
  return MultiProcessAdapter(UpperCAmelCase    ,			{}      )





