

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  A						:







         """simple docstring"""





         @staticmethod
         def 						snake_case__     (      *lowercase_ :       Tuple,**lowercase_ :       List[str]		)->    Optional[Any]:





             '''simple docstring'''







             pass


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







    """simple docstring"""





    lowerCamelCase			=							MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING


    def 						snake_case__     (      self :       Dict,lowercase_ :       Union[str, Any],lowercase_ :       Optional[Any],lowercase_ :       Tuple		)->    int:





        '''simple docstring'''







        A__          =   pipeline('visual-question-answering',model='hf-internal-testing/tiny-vilt-random-vqa'		)
        A__          =   [
            {
                '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 						snake_case__     (      self :       Optional[Any],lowercase_ :       List[str],lowercase_ :       Dict		)->    Tuple:





        '''simple docstring'''







        A__          =   vqa_pipeline(lowercase_,top_k=1		)
        self.assertEqual(
            lowercase_,[
                [{'score': ANY(lowercase_		), 'answer': ANY(lowercase_		)}],
                [{'score': ANY(lowercase_		), 'answer': ANY(lowercase_		)}],
            ],)


    @require_torch
    def 						snake_case__     (      self :       List[str]		)->    Optional[int]:





        '''simple docstring'''







        A__          =   pipeline('visual-question-answering',model='hf-internal-testing/tiny-vilt-random-vqa'		)
        A__          =   './tests/fixtures/tests_samples/COCO/000000039769.png'
        A__          =   'How many cats are there?'

        A__          =   vqa_pipeline(image=lowercase_,question='How many cats are there?',top_k=2		)
        self.assertEqual(
            lowercase_,[{'score': ANY(lowercase_		), 'answer': ANY(lowercase_		)}, {'score': ANY(lowercase_		), 'answer': ANY(lowercase_		)}]		)

        A__          =   vqa_pipeline({'image': image, 'question': question},top_k=2		)
        self.assertEqual(
            lowercase_,[{'score': ANY(lowercase_		), 'answer': ANY(lowercase_		)}, {'score': ANY(lowercase_		), 'answer': ANY(lowercase_		)}]		)


    @slow
    @require_torch
    def 						snake_case__     (      self :       Dict		)->    Optional[int]:





        '''simple docstring'''







        A__          =   pipeline('visual-question-answering',model='dandelin/vilt-b32-finetuned-vqa'		)
        A__          =   './tests/fixtures/tests_samples/COCO/000000039769.png'
        A__          =   'How many cats are there?'

        A__          =   vqa_pipeline(image=lowercase_,question=lowercase_,top_k=2		)
        self.assertEqual(
            nested_simplify(lowercase_,decimals=4		),[{'score': 0.8_799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}]		)

        A__          =   vqa_pipeline({'image': image, 'question': question},top_k=2		)
        self.assertEqual(
            nested_simplify(lowercase_,decimals=4		),[{'score': 0.8_799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}]		)

        A__          =   vqa_pipeline(
            [{'image': image, 'question': question}, {'image': image, 'question': question}],top_k=2		)
        self.assertEqual(
            nested_simplify(lowercase_,decimals=4		),[[{'score': 0.8_799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}]] * 2,)


    @require_tf
    @unittest.skip('Visual question answering not implemented in TF'		)
    def 						snake_case__     (      self :       str		)->    Optional[Any]:





        '''simple docstring'''







        pass







import argparse

import pytorch_lightning as pl
import torch
from torch import nn

from transformers import LongformerForQuestionAnswering, LongformerModel

class 		__lowerCAmelCase	(	pl.LightningModule ):
							def __init__(						self						:Union[str, Any]		,      __magic_name__						:Optional[int]				):







								'''simple docstring'''







								super().__init__()
								a										=							model
								a										=							2
								a										=							nn.Linear(self.model.config.hidden_size		,      self.num_labels				)





							def       lowerCamelCase__							(						self						:Dict				):







								'''simple docstring'''







								pass







def 		__A		(	__lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase    )      ->       Optional[int]:
	# load longformer model from model identifier
	a										=							LongformerModel.from_pretrained(__lowerCamelCase    )
	a										=							LightningModel(__lowerCamelCase    )

	a										=							torch.load(__lowerCamelCase							,			map_location=torch.device("""cpu"""    )    )
	lightning_model.load_state_dict(ckpt["""state_dict"""]    )

	# init longformer question answering model
	a										=							LongformerForQuestionAnswering.from_pretrained(__lowerCamelCase    )

	# transfer weights
	longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict()    )
	longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict()    )
	longformer_for_qa.eval()

	# save model
	longformer_for_qa.save_pretrained(__lowerCamelCase    )

	print(f'Conversion successful. Model saved under {pytorch_dump_folder_path}'    )


if __name__ == "__main__":
		__UpperCamelCase					:       List[Any]    					=      argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    "--longformer_model",
		    default=None,
		    type=str,
		    required=True,
		    help="model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.",
		)
		parser.add_argument(
		    "--longformer_question_answering_ckpt_path",
		    default=None,
		    type=str,
		    required=True,
		    help="Path the official PyTorch Lightning Checkpoint.",
		)
		parser.add_argument(
		    "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
		)
		__UpperCamelCase					:       List[Any]    					=      parser.parse_args()
		convert_longformer_qa_checkpoint_to_pytorch(
		    args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path
		)

