






"""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      SCREAMING_SNAKE_CASE  (				_SCREAMING_SNAKE_CASE						):





	"""simple docstring"""




	def    lowerCamelCase(self							):
		A_		:						Tuple	    =   tempfile.mkdtemp()
		A_		:						Tuple	    =   8

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

		A_		:						Tuple	    =   os.path.join(self.tmpdirname     ,     """bart_tokenizer"""							)
		os.makedirs(lowerCAmelCase_     ,     exist_ok=lowerCAmelCase_							)
		A_		:						int	    =   os.path.join(lowerCAmelCase_     ,     BART_VOCAB_FILES_NAMES["""vocab_file"""]							)
		A_		:						Union[str, Any]	    =   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							):
		return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname     ,     """dpr_tokenizer"""							)							)





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





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





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





	@slow
	def    lowerCamelCase(self							):
		A_		:						List[str]	    =   RagTokenizer.from_pretrained("""facebook/rag-sequence-nq"""							)
		A_		:						Optional[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""",
		]
		A_		:						Dict	    =   tokenizer(lowerCAmelCase_							)
		self.assertIsNotNone(lowerCAmelCase_							)









"""simple docstring"""
import unittest

from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
							from PIL import Image
else:



							class      SCREAMING_SNAKE_CASE  :





								"""simple docstring"""




								@staticmethod
								def    lowerCamelCase(*lowerCAmelCase_     ,     **lowerCAmelCase_							):
									pass



@is_pipeline_test
@require_torch
@require_vision
class      SCREAMING_SNAKE_CASE  (				unittest.TestCase						):





	"""simple docstring"""




	_A       :				List[Any]    =				MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING





	def    lowerCamelCase(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_							):
		A_		:						Union[str, Any]	    =   pipeline("""visual-question-answering"""     ,     model="""hf-internal-testing/tiny-vilt-random-vqa"""							)
		A_		:						Union[str, Any]	    =   [
		    {
		        """image""": Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							),
		        """question""": """How many cats are there?""",
		    },
		    {
		        """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""",
		        """question""": """How many cats are there?""",
		    },
		]
		return vqa_pipeline, examples





	def    lowerCamelCase(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_							):
		A_		:						str	    =   vqa_pipeline(lowerCAmelCase_     ,     top_k=1							)
		self.assertEqual(
		    lowerCAmelCase_     ,     [
		        [{"""score""": ANY(lowerCAmelCase_							), """answer""": ANY(lowerCAmelCase_							)}],
		        [{"""score""": ANY(lowerCAmelCase_							), """answer""": ANY(lowerCAmelCase_							)}],
		    ]     ,     )





	@require_torch
	def    lowerCamelCase(self							):
		A_		:						Tuple	    =   pipeline("""visual-question-answering"""     ,     model="""hf-internal-testing/tiny-vilt-random-vqa"""							)
		A_		:						Any	    =   """./tests/fixtures/tests_samples/COCO/000000039769.png"""
		A_		:						Any	    =   """How many cats are there?"""

		A_		:						Optional[int]	    =   vqa_pipeline(image=lowerCAmelCase_     ,     question="""How many cats are there?"""     ,     top_k=2							)
		self.assertEqual(
		    lowerCAmelCase_     ,     [{"""score""": ANY(lowerCAmelCase_							), """answer""": ANY(lowerCAmelCase_							)}, {"""score""": ANY(lowerCAmelCase_							), """answer""": ANY(lowerCAmelCase_							)}]							)

		A_		:						Any	    =   vqa_pipeline({"""image""": image, """question""": question}     ,     top_k=2							)
		self.assertEqual(
		    lowerCAmelCase_     ,     [{"""score""": ANY(lowerCAmelCase_							), """answer""": ANY(lowerCAmelCase_							)}, {"""score""": ANY(lowerCAmelCase_							), """answer""": ANY(lowerCAmelCase_							)}]							)





	@slow
	@require_torch
	def    lowerCamelCase(self							):
		A_		:						int	    =   pipeline("""visual-question-answering"""     ,     model="""dandelin/vilt-b32-finetuned-vqa"""							)
		A_		:						Tuple	    =   """./tests/fixtures/tests_samples/COCO/000000039769.png"""
		A_		:						int	    =   """How many cats are there?"""

		A_		:						List[Any]	    =   vqa_pipeline(image=lowerCAmelCase_     ,     question=lowerCAmelCase_     ,     top_k=2							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase_     ,     decimals=4							)     ,     [{"""score""": 0.8799, """answer""": """2"""}, {"""score""": 0.296, """answer""": """1"""}]							)

		A_		:						Any	    =   vqa_pipeline({"""image""": image, """question""": question}     ,     top_k=2							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase_     ,     decimals=4							)     ,     [{"""score""": 0.8799, """answer""": """2"""}, {"""score""": 0.296, """answer""": """1"""}]							)

		A_		:						Tuple	    =   vqa_pipeline(
		    [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]     ,     top_k=2							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase_     ,     decimals=4							)     ,     [[{"""score""": 0.8799, """answer""": """2"""}, {"""score""": 0.296, """answer""": """1"""}]] * 2     ,     )





	@require_tf
	@unittest.skip("""Visual question answering not implemented in TF"""							)
	def    lowerCamelCase(self							):
		pass

