




"""simple docstring"""

import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
a							      =     pytest.mark.integration


a							      =     {'''comet'''}
a							      =     importlib.util.find_spec('''fairseq''') is not None

a							      =     {'''code_eval'''}
a							      =     os.name == '''nt'''

a							      =     {'''bertscore''', '''frugalscore''', '''perplexity'''}
a							      =     importlib.util.find_spec('''transformers''') is not None






def 		_snake_case	(   _snake_case				:   List[Any]				)       ->   Union[str, Any]:






      '''simple docstring'''


      @wraps(_snake_case				)
      def wrapper(self				:   List[str]							,    _snake_case				:   str				):
            if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
                  self.skipTest('"test requires Fairseq"'				)
            else:
                  test_case(self							,    _snake_case				)

      return wrapper






def 		_snake_case	(   _snake_case				:   Any				)       ->   List[str]:






      '''simple docstring'''


      @wraps(_snake_case				)
      def wrapper(self				:   Union[str, Any]							,    _snake_case				:   Optional[int]				):
            if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
                  self.skipTest('"test requires transformers"'				)
            else:
                  test_case(self							,    _snake_case				)

      return wrapper






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






      '''simple docstring'''


      @wraps(_snake_case				)
      def wrapper(self				:   Union[str, Any]							,    _snake_case				:   List[str]				):
            if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
                  self.skipTest('"test not supported on Windows"'				)
            else:
                  test_case(self							,    _snake_case				)

      return wrapper






def 		_snake_case	(   )       ->   Tuple:






      '''simple docstring'''


      _A     =  [metric_dir.split(os.sep				)[-2] for metric_dir in glob.glob('./metrics/*/'				)]
      return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished





@parameterized.named_parameters(get_local_metric_names()				)
@for_all_test_methods(
    __lowerCAmelCase     ,      __lowerCAmelCase     ,      __lowerCAmelCase				)
@local
class 							lowercase_			(	parameterized.TestCase				):



 '''simple docstring'''
 UpperCAmelCase       :	Optional[Any]     =      {}
 UpperCAmelCase       :	Optional[Any]     =      None

 @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'						)
 @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'						)
 def      lowerCAmelCase_				(					self			:			int       ,				_UpperCAmelCase			:			str						):
       _A     =  '[...]'
       _A     =  importlib.import_module(
           datasets.load.metric_module_factory(os.path.join('metrics'       ,				_UpperCAmelCase						)						).module_path						)
       _A     =  datasets.load.import_main_class(metric_module.__name__       ,				dataset=_UpperCAmelCase						)
       # check parameters
       _A     =  inspect.signature(metric._compute						).parameters
       self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()						)						)  # no **kwargs
       # run doctest
       with self.patch_intensive_calls(_UpperCAmelCase       ,				metric_module.__name__						):
             with self.use_local_metrics():
                   try:
                         _A     =  doctest.testmod(_UpperCAmelCase       ,				verbose=_UpperCAmelCase       ,				raise_on_error=_UpperCAmelCase						)
                   except doctest.UnexpectedException as e:
                         raise e.exc_info[1]  # raise the exception that doctest caught
       self.assertEqual(results.failed       ,				0						)
       self.assertGreater(results.attempted       ,				1						)

 @slow
 def      lowerCAmelCase_				(					self			:			Tuple       ,				_UpperCAmelCase			:			Optional[int]						):
       _A     =  '[...]'
       _A     =  importlib.import_module(
           datasets.load.metric_module_factory(os.path.join('metrics'       ,				_UpperCAmelCase						)						).module_path						)
       # run doctest
       with self.use_local_metrics():
             _A     =  doctest.testmod(_UpperCAmelCase       ,				verbose=_UpperCAmelCase       ,				raise_on_error=_UpperCAmelCase						)
       self.assertEqual(results.failed       ,				0						)
       self.assertGreater(results.attempted       ,				1						)

 @contextmanager
 def      lowerCAmelCase_				(					self			:			Optional[int]       ,				_UpperCAmelCase			:			Dict       ,				_UpperCAmelCase			:			List[str]						):
       if metric_name in self.INTENSIVE_CALLS_PATCHER:
             with self.INTENSIVE_CALLS_PATCHER[metric_name](_UpperCAmelCase						):
                   yield
       else:
             yield

 @contextmanager
 def      lowerCAmelCase_				(					self			:			str						):
       def load_local_metric(_UpperCAmelCase			:			Optional[Any]       ,				*_UpperCAmelCase			:			Union[str, Any]       ,				**_UpperCAmelCase			:			Optional[Any]						):
             return load_metric(os.path.join('metrics'       ,				_UpperCAmelCase						)       ,				*_UpperCAmelCase       ,				**_UpperCAmelCase						)

       with patch('datasets.load_metric'						) as mock_load_metric:
             _A     =  load_local_metric
             yield



 @classmethod
 def      lowerCAmelCase_				(					cls			:			Optional[Any]       ,				_UpperCAmelCase			:			str						):
       def wrapper(_UpperCAmelCase			:			str						):
             _A     =  contextmanager(_UpperCAmelCase						)
             _A     =  patcher
             return patcher

       return wrapper






@LocalMetricTest.register_intensive_calls_patcher('bleurt'				)
def 		_snake_case	(   _snake_case				:   int				)       ->   Any:






      '''simple docstring'''


      import tensorflow.compat.va as tf
      from bleurt.score import Predictor

      tf.flags.DEFINE_string('sv'							,    ''							,    ''				)  # handle pytest cli flags





      class 							lowercase_			(	__lowerCAmelCase				):



       '''simple docstring'''

       def      lowerCAmelCase_				(					self			:			Any       ,				_UpperCAmelCase			:			Dict						):
             assert len(input_dict['input_ids']						) == 2
             return np.array([1.03, 1.04]						)

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
      with patch('bleurt.score._create_predictor'				) as mock_create_predictor:
            _A     =  MockedPredictor()
            yield






@LocalMetricTest.register_intensive_calls_patcher('bertscore'				)
def 		_snake_case	(   _snake_case				:   Tuple				)       ->   Tuple:






      '''simple docstring'''


      import torch

      def bert_cos_score_idf(_snake_case				:   Optional[Any]							,    _snake_case				:   Optional[Any]							,    *_snake_case				:   Union[str, Any]							,    **_snake_case				:   Optional[Any]				):
            return torch.tensor([[1.0, 1.0, 1.0]] * len(_snake_case				)				)

      # mock get_model which is supposed to do download a bert model
      # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
      with patch('bert_score.scorer.get_model'				), patch(
          'bert_score.scorer.bert_cos_score_idf'				) as mock_bert_cos_score_idf:
            _A     =  bert_cos_score_idf
            yield






@LocalMetricTest.register_intensive_calls_patcher('comet'				)
def 		_snake_case	(   _snake_case				:   List[str]				)       ->   List[str]:






      '''simple docstring'''


      def load_from_checkpoint(_snake_case				:   str				):





            class 							lowercase_			:



             '''simple docstring'''

             def      lowerCAmelCase_				(					self			:			Optional[int]       ,				_UpperCAmelCase			:			Optional[int]       ,				*_UpperCAmelCase			:			Optional[int]       ,				**_UpperCAmelCase			:			Tuple						):
                   assert len(_UpperCAmelCase						) == 2
                   _A     =  [0.19, 0.92]
                   return scores, sum(_UpperCAmelCase						) / len(_UpperCAmelCase						)



            return Model()

      # mock load_from_checkpoint which is supposed to do download a bert model
      # mock load_from_checkpoint which is supposed to do download a bert model
      with patch('comet.download_model'				) as mock_download_model:
            _A     =  None
            with patch('comet.load_from_checkpoint'				) as mock_load_from_checkpoint:
                  _A     =  load_from_checkpoint
                  yield







def 		_snake_case	(   )       ->   List[str]:






      '''simple docstring'''


      _A     =  load_metric(os.path.join('metrics'							,    'seqeval'				)				)
      _A     =  'ERROR'
      _A     =  F'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}'''
      with pytest.raises(_snake_case							,    match=re.escape(_snake_case				)				):
            metric.compute(predictions=[]							,    references=[]							,    scheme=_snake_case				)







"""simple docstring"""

import argparse
from collections import OrderedDict
from pathlib import Path

import torch

from transformers import (
    VisualBertConfig,
    VisualBertForMultipleChoice,
    VisualBertForPreTraining,
    VisualBertForQuestionAnswering,
    VisualBertForVisualReasoning,
)
from transformers.utils import logging


logging.set_verbosity_info()
a							      =     logging.get_logger(__name__)

a							      =     [
    ('''bert.bert''', '''visual_bert'''),
    ('''bert.cls''', '''cls'''),
    ('''bert.classifier''', '''cls'''),
    ('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''),
    ('''position_embeddings_visual''', '''visual_position_embeddings'''),
    ('''projection''', '''visual_projection'''),
]

a							      =     [
    '''nlvr2_coco_pre_trained.th''',
    '''nlvr2_fine_tuned.th''',
    '''nlvr2_pre_trained.th''',
    '''vcr_coco_pre_train.th''',
    '''vcr_fine_tune.th''',
    '''vcr_pre_train.th''',
    '''vqa_coco_pre_trained.th''',
    '''vqa_fine_tuned.th''',
    '''vqa_pre_trained.th''',
]






def 		_snake_case	(   _snake_case				:   Optional[Any]				)       ->   str:






      '''simple docstring'''


      _A     =  torch.load(_snake_case							,    map_location='cpu'				)
      return sd






def 		_snake_case	(   _snake_case				:   Union[str, Any]							,    _snake_case				:   str							,    _snake_case				:   Tuple=rename_keys_prefix				)       ->   List[str]:






      '''simple docstring'''


      _A     =  OrderedDict()
      _A     =  torch.arange(config.max_position_embeddings				).expand((1, -1)				)
      # detector_d = OrderedDict()
      for key in d:
            if "detector" in key:
                  # detector_d[key.replace('detector.','')] = d[key]
                  continue
            _A     =  key
            for name_pair in rename_keys_prefix:
                  _A     =  new_key.replace(name_pair[0]							,    name_pair[1]				)
            _A     =  d[key]
            if key == "bert.cls.predictions.decoder.weight":
                  # Old bert code didn't have `decoder.bias`, but was added separately
                  _A     =  new_d['cls.predictions.bias']
      return new_d






@torch.no_grad()
def 		_snake_case	(   _snake_case				:   List[str]							,    _snake_case				:   Dict				)       ->   Dict:






      '''simple docstring'''


      assert (
          checkpoint_path.split('/'				)[-1] in ACCEPTABLE_CHECKPOINTS
      ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.'''

      # Get Config
      if "pre" in checkpoint_path:
            _A     =  'pretraining'
            if "vcr" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 5_12}
            elif "vqa_advanced" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 20_48}
            elif "vqa" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 20_48}
            elif "nlvr" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 10_24}
            else:
                  raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.'''				)
      else:
            if "vcr" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 5_12}
                  _A     =  'multichoice'
            elif "vqa_advanced" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 20_48}
                  _A     =  'vqa_advanced'
            elif "vqa" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 20_48, 'num_labels': 31_29}
                  _A     =  'vqa'
            elif "nlvr" in checkpoint_path:
                  _A     =  {
                      'visual_embedding_dim': 10_24,
                      'num_labels': 2,
                  }
                  _A     =  'nlvr'

      _A     =  VisualBertConfig(**_snake_case				)

      # Load State Dict
      _A     =  load_state_dict(_snake_case				)

      _A     =  get_new_dict(_snake_case							,    _snake_case				)

      if model_type == "pretraining":
            _A     =  VisualBertForPreTraining(_snake_case				)
      elif model_type == "vqa":
            _A     =  VisualBertForQuestionAnswering(_snake_case				)
      elif model_type == "nlvr":
            _A     =  VisualBertForVisualReasoning(_snake_case				)
      elif model_type == "multichoice":
            _A     =  VisualBertForMultipleChoice(_snake_case				)

      model.load_state_dict(_snake_case				)
      # Save Checkpoints
      Path(_snake_case				).mkdir(exist_ok=_snake_case				)
      model.save_pretrained(_snake_case				)


if __name__ == "__main__":
       a							      =     argparse.ArgumentParser()
       # Required parameters
       parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''')
       parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''')
       a							      =     parser.parse_args()
       convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)

