

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     __snake_case    (				snake_case__  ):
       """simple docstring"""







       def 			a		(		self   )      ->							List[Any]:






              """simple docstring"""


              __snake_case       	=							tempfile.mkdtemp()
              __snake_case       	=							8

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

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


       def 			a		(		self   )      ->							DPRQuestionEncoderTokenizer:






              """simple docstring"""


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


       def 			a		(		self   )      ->							BartTokenizer:






              """simple docstring"""


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


       def 			a		(		self   )      ->							Union[str, Any]:






              """simple docstring"""


              shutil.rmtree(self.tmpdirname   )


       @require_tokenizers
       def 			a		(		self   )      ->							Union[str, Any]:






              """simple docstring"""


              __snake_case       	=							os.path.join(self.tmpdirname      , """rag_tokenizer"""   )
              __snake_case       	=							RagConfig(question_encoder=DPRConfig().to_dict()      , generator=BartConfig().to_dict()   )
              __snake_case       	=							RagTokenizer(question_encoder=self.get_dpr_tokenizer()      , generator=self.get_bart_tokenizer()   )
              rag_config.save_pretrained(_UpperCamelCase   )
              rag_tokenizer.save_pretrained(_UpperCamelCase   )
              __snake_case       	=							RagTokenizer.from_pretrained(_UpperCamelCase      , config=_UpperCamelCase   )
              self.assertIsInstance(new_rag_tokenizer.question_encoder      , _UpperCamelCase   )
              self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab()      , rag_tokenizer.question_encoder.get_vocab()   )
              self.assertIsInstance(new_rag_tokenizer.generator      , _UpperCamelCase   )
              self.assertEqual(new_rag_tokenizer.generator.get_vocab()      , rag_tokenizer.generator.get_vocab()   )


       @slow
       def 			a		(		self   )      ->							Optional[Any]:






              """simple docstring"""


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






       @slow
       def 			a		(		self   )      ->							Any:






              """simple docstring"""


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




from argparse import ArgumentParser

from . import BaseTransformersCLICommand







def 						lowerCamelCase__      ( __A    :Optional[int]		):


       """simple docstring"""




       return DownloadCommand(args.model	,args.cache_dir	,args.force	,args.trust_remote_code		)




class     __snake_case    (				snake_case__  ):
       """simple docstring"""







       @staticmethod
       def 			a		(		_UpperCamelCase   )      ->							Any:






              """simple docstring"""


              __snake_case       	=							parser.add_parser("""download"""   )
              download_parser.add_argument(
                  """--cache-dir"""      , type=_UpperCamelCase      , default=_UpperCamelCase      , help="""Path to location to store the models"""   )
              download_parser.add_argument(
                  """--force"""      , action="""store_true"""      , help="""Force the model to be download even if already in cache-dir"""   )
              download_parser.add_argument(
                  """--trust-remote-code"""      , action="""store_true"""      , help="""Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you've reviewed the code as it will execute on your local machine"""      , )
              download_parser.add_argument("""model"""      , type=_UpperCamelCase      , help="""Name of the model to download"""   )
              download_parser.set_defaults(func=_UpperCamelCase   )


       def __init__(		self      , _UpperCamelCase      , _UpperCamelCase      , _UpperCamelCase      , _UpperCamelCase   )      ->							Any:






              """simple docstring"""


              __snake_case       	=							model
              __snake_case       	=							cache
              __snake_case       	=							force
              __snake_case       	=							trust_remote_code






       def 			a		(		self   )      ->							List[Any]:






              """simple docstring"""


              from ..models.auto import AutoModel, AutoTokenizer

              AutoModel.from_pretrained(
                  self._model      , cache_dir=self._cache      , force_download=self._force      , trust_remote_code=self._trust_remote_code   )
              AutoTokenizer.from_pretrained(
                  self._model      , cache_dir=self._cache      , force_download=self._force      , trust_remote_code=self._trust_remote_code   )

