




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
lowerCamelCase	:	Union[str, Any]				=   pytest.mark.integration


lowerCamelCase	:	Optional[int]				=   {"comet"}
lowerCamelCase	:	Optional[Any]				=   importlib.util.find_spec('fairseq') is not None

lowerCamelCase	:	List[str]				=   {"code_eval"}
lowerCamelCase	:	List[Any]				=   os.name == "nt"

lowerCamelCase	:	Dict				=   {"bertscore", "frugalscore", "perplexity"}
lowerCamelCase	:	List[Any]				=   importlib.util.find_spec('transformers') is not None




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       List[Any]:



			@wraps(lowercase					)
			def wrapper(self						,lowercase					):
						if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
									self.skipTest("""\"test requires Fairseq\""""					)
						else:
									test_case(self						,lowercase					)

			return wrapper




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Dict:



			@wraps(lowercase					)
			def wrapper(self						,lowercase					):
						if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
									self.skipTest("""\"test requires transformers\""""					)
						else:
									test_case(self						,lowercase					)

			return wrapper




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Dict:



			@wraps(lowercase					)
			def wrapper(self						,lowercase					):
						if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
									self.skipTest("""\"test not supported on Windows\""""					)
						else:
									test_case(self						,lowercase					)

			return wrapper




def 						SCREAMING_SNAKE_CASE__ (   )  ->       Any:
			snake_case				:    Optional[Any]           =	[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"""





						_snake_case												=						{}
						_snake_case												=						None

						@pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning"""     )
						@pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning"""     )
						def      UpperCAmelCase				(				self    ,				A     )		->    int:
									snake_case				:    int           =	'''[...]'''
									snake_case				:    Any           =	importlib.import_module(
									    datasets.load.metric_module_factory(os.path.join("""metrics"""    ,				lowerCamelCase__     )     ).module_path     )
									snake_case				:    int           =	datasets.load.import_main_class(metric_module.__name__    ,				dataset=lowerCamelCase__     )
									# check parameters
									snake_case				:    Optional[int]           =	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(lowerCamelCase__    ,				metric_module.__name__     ):
												with self.use_local_metrics():
															try:
																		snake_case				:    str           =	doctest.testmod(lowerCamelCase__    ,				verbose=lowerCamelCase__    ,				raise_on_error=lowerCamelCase__     )
															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      UpperCAmelCase				(				self    ,				A     )		->    List[str]:
									snake_case				:    str           =	'''[...]'''
									snake_case				:    Tuple           =	importlib.import_module(
									    datasets.load.metric_module_factory(os.path.join("""metrics"""    ,				lowerCamelCase__     )     ).module_path     )
									# run doctest
									with self.use_local_metrics():
												snake_case				:    Optional[int]           =	doctest.testmod(lowerCamelCase__    ,				verbose=lowerCamelCase__    ,				raise_on_error=lowerCamelCase__     )
									self.assertEqual(results.failed    ,				0     )
									self.assertGreater(results.attempted    ,				1     )

						@contextmanager
						def      UpperCAmelCase				(				self    ,				A    ,				A     )		->    Tuple:






									if metric_name in self.INTENSIVE_CALLS_PATCHER:
												with self.INTENSIVE_CALLS_PATCHER[metric_name](lowerCamelCase__     ):
															yield
									else:
												yield

						@contextmanager
						def      UpperCAmelCase				(				self     )		->    str:






									def load_local_metric(A    ,				*A    ,				**A     ):
												return load_metric(os.path.join("""metrics"""    ,				lowerCamelCase__     )    ,				*lowerCamelCase__    ,				**lowerCamelCase__     )

									with patch("""datasets.load_metric"""     ) as mock_load_metric:
												snake_case				:    List[Any]           =	load_local_metric
												yield

						@classmethod
						def      UpperCAmelCase				(				cls    ,				A     )		->    Any:






									def wrapper(A     ):
												snake_case				:    Tuple           =	contextmanager(lowerCamelCase__     )
												snake_case				:    List[Any]           =	patcher
												return patcher

									return wrapper




@LocalMetricTest.register_intensive_calls_patcher("""bleurt"""					)
def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Union[str, Any]:
			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      UpperCAmelCase				(				self    ,				A     )		->    Union[str, Any]:
												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:
						snake_case				:    Union[str, Any]           =	MockedPredictor()
						yield




@LocalMetricTest.register_intensive_calls_patcher("""bertscore"""					)
def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       List[Any]:
			import torch

			def bert_cos_score_idf(lowercase						,lowercase						,*lowercase						,**lowercase					):
						return torch.tensor([[1.0, 1.0, 1.0]] * len(lowercase					)					)

			# 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:
						snake_case				:    Optional[Any]           =	bert_cos_score_idf
						yield




@LocalMetricTest.register_intensive_calls_patcher("""comet"""					)
def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Any:



			def load_from_checkpoint(lowercase					):




						class 						__lowercase		:




												"""simple docstring"""





												def      UpperCAmelCase				(				self    ,				A    ,				*A    ,				**A     )		->    List[str]:
															assert len(lowerCamelCase__     ) == 2
															snake_case				:    List[str]           =	[0.19, 0.92]
															return scores, sum(lowerCamelCase__     ) / len(lowerCamelCase__     )




						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:
						snake_case				:    str           =	None
						with patch("""comet.load_from_checkpoint"""					) as mock_load_from_checkpoint:
									snake_case				:    List[str]           =	load_from_checkpoint
									yield




def 						SCREAMING_SNAKE_CASE__ (   )  ->       Tuple:
			snake_case				:    List[Any]           =	load_metric(os.path.join("""metrics"""						,"""seqeval"""					)					)
			snake_case				:    Optional[Any]           =	'''ERROR'''
			snake_case				:    str           =	f"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
			with pytest.raises(lowercase						,match=re.escape(lowercase					)					):
						metric.compute(predictions=[]						,references=[]						,scheme=lowercase					)











from argparse import ArgumentParser, Namespace

from ..utils import logging
from . import BaseTransformersCLICommand




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       List[str]:
   return ConvertCommand(
       args.model_type						,args.tf_checkpoint						,args.pytorch_dump_output						,args.config						,args.finetuning_task_name					)


lowerCamelCase	:	Tuple				=   '\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n'




class 						__lowercase		(UpperCamelCase__							):




      """simple docstring"""





      @staticmethod
      def      UpperCAmelCase				(				A     )		->    List[str]:
         snake_case				:    Union[str, Any]           =	parser.add_parser(
             """convert"""    ,				help="""CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints."""    ,				)
         train_parser.add_argument("""--model_type"""    ,				type=A    ,				required=A    ,				help="""Model's type."""     )
         train_parser.add_argument(
             """--tf_checkpoint"""    ,				type=A    ,				required=A    ,				help="""TensorFlow checkpoint path or folder."""     )
         train_parser.add_argument(
             """--pytorch_dump_output"""    ,				type=A    ,				required=A    ,				help="""Path to the PyTorch saved model output."""     )
         train_parser.add_argument("""--config"""    ,				type=A    ,				default=""""""    ,				help="""Configuration file path or folder."""     )
         train_parser.add_argument(
             """--finetuning_task_name"""    ,				type=A    ,				default=A    ,				help="""Optional fine-tuning task name if the TF model was a finetuned model."""    ,				)
         train_parser.set_defaults(func=A     )

      def __init__(				self    ,				A    ,				A    ,				A    ,				A    ,				A    ,				*A    ,				)		->    List[Any]:
         snake_case				:    Any           =	logging.get_logger("""transformers-cli/converting"""     )

         self._logger.info(f"""Loading model {model_type}"""     )
         snake_case				:    int           =	model_type
         snake_case				:    Any           =	tf_checkpoint
         snake_case				:    int           =	pytorch_dump_output
         snake_case				:    List[str]           =	config
         snake_case				:    Tuple           =	finetuning_task_name

      def      UpperCAmelCase				(				self     )		->    int:
         if self._model_type == "albert":
            try:
               from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import (
                   convert_tf_checkpoint_to_pytorch,
               )
            except ImportError:
               raise ImportError(A     )

            convert_tf_checkpoint_to_pytorch(self._tf_checkpoint    ,				self._config    ,				self._pytorch_dump_output     )
         elif self._model_type == "bert":
            try:
               from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import (
                   convert_tf_checkpoint_to_pytorch,
               )
            except ImportError:
               raise ImportError(A     )

            convert_tf_checkpoint_to_pytorch(self._tf_checkpoint    ,				self._config    ,				self._pytorch_dump_output     )
         elif self._model_type == "funnel":
            try:
               from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import (
                   convert_tf_checkpoint_to_pytorch,
               )
            except ImportError:
               raise ImportError(A     )

            convert_tf_checkpoint_to_pytorch(self._tf_checkpoint    ,				self._config    ,				self._pytorch_dump_output     )
         elif self._model_type == "t5":
            try:
               from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
            except ImportError:
               raise ImportError(A     )

            convert_tf_checkpoint_to_pytorch(self._tf_checkpoint    ,				self._config    ,				self._pytorch_dump_output     )
         elif self._model_type == "gpt":
            from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import (
                convert_openai_checkpoint_to_pytorch,
            )

            convert_openai_checkpoint_to_pytorch(self._tf_checkpoint    ,				self._config    ,				self._pytorch_dump_output     )
         elif self._model_type == "transfo_xl":
            try:
               from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import (
                   convert_transfo_xl_checkpoint_to_pytorch,
               )
            except ImportError:
               raise ImportError(A     )

            if "ckpt" in self._tf_checkpoint.lower():
               snake_case				:    List[Any]           =	self._tf_checkpoint
               snake_case				:    Tuple           =	""""""
            else:
               snake_case				:    Tuple           =	self._tf_checkpoint
               snake_case				:    Tuple           =	""""""
            convert_transfo_xl_checkpoint_to_pytorch(
                A    ,				self._config    ,				self._pytorch_dump_output    ,				A     )
         elif self._model_type == "gpt2":
            try:
               from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import (
                   convert_gpta_checkpoint_to_pytorch,
               )
            except ImportError:
               raise ImportError(A     )

            convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint    ,				self._config    ,				self._pytorch_dump_output     )
         elif self._model_type == "xlnet":
            try:
               from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import (
                   convert_xlnet_checkpoint_to_pytorch,
               )
            except ImportError:
               raise ImportError(A     )

            convert_xlnet_checkpoint_to_pytorch(
                self._tf_checkpoint    ,				self._config    ,				self._pytorch_dump_output    ,				self._finetuning_task_name     )
         elif self._model_type == "xlm":
            from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import (
                convert_xlm_checkpoint_to_pytorch,
            )

            convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint    ,				self._pytorch_dump_output     )
         elif self._model_type == "lxmert":
            from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import (
                convert_lxmert_checkpoint_to_pytorch,
            )

            convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint    ,				self._pytorch_dump_output     )
         elif self._model_type == "rembert":
            from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import (
                convert_rembert_tf_checkpoint_to_pytorch,
            )

            convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint    ,				self._config    ,				self._pytorch_dump_output     )
         else:
            raise ValueError(
                """--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]"""     )





