
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
_snake_case      = pytest.mark.integration


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

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

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

def  __lowerCamelCase					( _lowercase			)       ->      int:
     @wraps(lowerCAmelCase__			)
     def wrapper(self						,     _lowercase			):
          if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
               self.skipTest('\"test requires Fairseq\"'			)
          else:
               test_case(self						,     lowerCAmelCase__			)

     return wrapper

def  __lowerCamelCase					( _lowercase			)       ->      str:
     @wraps(lowerCAmelCase__			)
     def wrapper(self						,     _lowercase			):
          if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
               self.skipTest('\"test requires transformers\"'			)
          else:
               test_case(self						,     lowerCAmelCase__			)

     return wrapper

def  __lowerCamelCase					( _lowercase			)       ->      int:
     @wraps(lowerCAmelCase__			)
     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						,     lowerCAmelCase__			)

     return wrapper

def  __lowerCamelCase					( )       ->      Optional[int]:
     UpperCamelCase						    =					[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(
    __A			,	__A			,	__A							)
@local
class       _lowerCAmelCase  (		parameterized.TestCase							):

 """simple docstring"""
 SCREAMING_SNAKE_CASE_				:					Tuple       						={}
 SCREAMING_SNAKE_CASE_				:					Tuple       						=None

 @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'   )
 @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'   )
 def      __lowerCAmelCase  (						self			:			Optional[Any]					, SCREAMING_SNAKE_CASE__			:			Any   ):






      """simple docstring"""



      UpperCamelCase						    =					'[...]'
      UpperCamelCase						    =					importlib.import_module(
          datasets.load.metric_module_factory(os.path.join('metrics'					, __A   )   ).module_path   )
      UpperCamelCase						    =					datasets.load.import_main_class(metric_module.__name__					, dataset=__A   )
      # check parameters
      UpperCamelCase						    =					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(__A					, metric_module.__name__   ):
           with self.use_local_metrics():
                try:
                     UpperCamelCase						    =					doctest.testmod(__A					, verbose=__A					, raise_on_error=__A   )
                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			:			int					, SCREAMING_SNAKE_CASE__			:			List[Any]   ):






      """simple docstring"""



      UpperCamelCase						    =					'[...]'
      UpperCamelCase						    =					importlib.import_module(
          datasets.load.metric_module_factory(os.path.join('metrics'					, __A   )   ).module_path   )
      # run doctest
      with self.use_local_metrics():
           UpperCamelCase						    =					doctest.testmod(__A					, verbose=__A					, raise_on_error=__A   )
      self.assertEqual(results.failed					, 0   )
      self.assertGreater(results.attempted					, 1   )

 @contextmanager
 def      __lowerCAmelCase  (						self			:			List[str]					, SCREAMING_SNAKE_CASE__			:			int					, SCREAMING_SNAKE_CASE__			:			Dict   ):






      """simple docstring"""



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

 @contextmanager
 def      __lowerCAmelCase  (						self			:			str   ):






      """simple docstring"""



      def load_local_metric(SCREAMING_SNAKE_CASE__			:			List[Any]					, *SCREAMING_SNAKE_CASE__			:			Union[str, Any]					, **SCREAMING_SNAKE_CASE__			:			List[str]   ):
           return load_metric(os.path.join('metrics'					, __A   )					, *__A					, **__A   )

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






 @classmethod
 def      __lowerCAmelCase  (						cls			:			List[Any]					, SCREAMING_SNAKE_CASE__			:			int   ):






      """simple docstring"""



      def wrapper(SCREAMING_SNAKE_CASE__			:			Optional[Any]   ):
           UpperCamelCase						    =					contextmanager(__A   )
           UpperCamelCase						    =					patcher
           return patcher

      return wrapper




@LocalMetricTest.register_intensive_calls_patcher('bleurt'			)
def  __lowerCamelCase					( _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       _lowerCAmelCase  (		__A							):

      """simple docstring"""

      def      __lowerCAmelCase  (						self			:			Any					, SCREAMING_SNAKE_CASE__			:			List[Any]   ):






           """simple docstring"""



           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:
          UpperCamelCase						    =					MockedPredictor()
          yield

@LocalMetricTest.register_intensive_calls_patcher('bertscore'			)
def  __lowerCamelCase					( _lowercase			)       ->      Optional[int]:
     import torch

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

     # 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:
          UpperCamelCase						    =					bert_cos_score_idf
          yield

@LocalMetricTest.register_intensive_calls_patcher('comet'			)
def  __lowerCamelCase					( _lowercase			)       ->      Any:
     def load_from_checkpoint(_lowercase			):
          class       _lowerCAmelCase  :

           """simple docstring"""

           def      __lowerCAmelCase  (						self			:			List[str]					, SCREAMING_SNAKE_CASE__			:			Union[str, Any]					, *SCREAMING_SNAKE_CASE__			:			Dict					, **SCREAMING_SNAKE_CASE__			:			Tuple   ):






                """simple docstring"""



                assert len(__A   ) == 2
                UpperCamelCase						    =					[0.19, 0.92]
                return scores, sum(__A   ) / len(__A   )




          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:
          UpperCamelCase						    =					None
          with patch('comet.load_from_checkpoint'			) as mock_load_from_checkpoint:
               UpperCamelCase						    =					load_from_checkpoint
               yield







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






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
  import torch

if is_vision_available():
  from PIL import Image

  from transformers import ViTImageProcessor


class     __UpperCAmelCase							(       unittest.TestCase							):


     """simple docstring"""


     def __init__(	self  ,       __A  ,       __A=13  ,       __A=3  ,       __A=224  ,       __A=30  ,       __A=400  ,       __A=True  ,       __A=None  ,       __A=True  ,       __A=[0.5, 0.5, 0.5]  ,       __A=[0.5, 0.5, 0.5]  ,       ):
        __a					=  size if size is not None else {"""height""": 18, """width""": 18}
        __a					=  parent
        __a					=  batch_size
        __a					=  num_channels
        __a					=  image_size
        __a					=  min_resolution
        __a					=  max_resolution
        __a					=  do_resize
        __a					=  size
        __a					=  do_normalize
        __a					=  image_mean
        __a					=  image_std


     def 	snake_case_  (	self    ):
        return {
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_normalize": self.do_normalize,
            "do_resize": self.do_resize,
            "size": self.size,
        }







@require_torch
@require_vision
class     __UpperCAmelCase							(       __A ,					unittest.TestCase							):


     """simple docstring"""
     _lowerCamelCase   =      ViTImageProcessor if is_vision_available() else None


     def 	snake_case_  (	self    ):
        __a					=  EfficientFormerImageProcessorTester(self    )


     @property
     def 	snake_case_  (	self    ):
        return self.image_proc_tester.prepare_image_processor_dict()


     def 	snake_case_  (	self    ):
        __a					=  self.image_processing_class(**self.image_processor_dict    )
        self.assertTrue(hasattr(__A  ,       """image_mean"""    )    )
        self.assertTrue(hasattr(__A  ,       """image_std"""    )    )
        self.assertTrue(hasattr(__A  ,       """do_normalize"""    )    )
        self.assertTrue(hasattr(__A  ,       """do_resize"""    )    )
        self.assertTrue(hasattr(__A  ,       """size"""    )    )


     def 	snake_case_  (	self    ):
        pass


     def 	snake_case_  (	self    ):
        # Initialize image_processor
        __a					=  self.image_processing_class(**self.image_processor_dict    )
        # create random PIL images
        __a					=  prepare_image_inputs(self.image_proc_tester  ,       equal_resolution=__A    )
        for image in image_inputs:
           self.assertIsInstance(__A  ,       Image.Image    )

        # Test not batched input
        __a					=  image_processor(image_inputs[0]  ,       return_tensors="""pt"""    ).pixel_values
        self.assertEqual(
            encoded_images.shape  ,       (
                1,
                self.image_proc_tester.num_channels,
                self.image_proc_tester.size["""height"""],
                self.image_proc_tester.size["""width"""],
            )  ,       )

        # Test batched
        __a					=  image_processor(__A  ,       return_tensors="""pt"""    ).pixel_values
        self.assertEqual(
            encoded_images.shape  ,       (
                self.image_proc_tester.batch_size,
                self.image_proc_tester.num_channels,
                self.image_proc_tester.size["""height"""],
                self.image_proc_tester.size["""width"""],
            )  ,       )


     def 	snake_case_  (	self    ):
        # Initialize image_processor
        __a					=  self.image_processing_class(**self.image_processor_dict    )
        # create random numpy tensors
        __a					=  prepare_image_inputs(self.image_proc_tester  ,       equal_resolution=__A  ,       numpify=__A    )
        for image in image_inputs:
           self.assertIsInstance(__A  ,       np.ndarray    )

        # Test not batched input
        __a					=  image_processor(image_inputs[0]  ,       return_tensors="""pt"""    ).pixel_values
        self.assertEqual(
            encoded_images.shape  ,       (
                1,
                self.image_proc_tester.num_channels,
                self.image_proc_tester.size["""height"""],
                self.image_proc_tester.size["""width"""],
            )  ,       )

        # Test batched
        __a					=  image_processor(__A  ,       return_tensors="""pt"""    ).pixel_values
        self.assertEqual(
            encoded_images.shape  ,       (
                self.image_proc_tester.batch_size,
                self.image_proc_tester.num_channels,
                self.image_proc_tester.size["""height"""],
                self.image_proc_tester.size["""width"""],
            )  ,       )


     def 	snake_case_  (	self    ):
        # Initialize image_processor
        __a					=  self.image_processing_class(**self.image_processor_dict    )
        # create random PyTorch tensors
        __a					=  prepare_image_inputs(self.image_proc_tester  ,       equal_resolution=__A  ,       torchify=__A    )
        for image in image_inputs:
           self.assertIsInstance(__A  ,       torch.Tensor    )

        # Test not batched input
        __a					=  image_processor(image_inputs[0]  ,       return_tensors="""pt"""    ).pixel_values
        self.assertEqual(
            encoded_images.shape  ,       (
                1,
                self.image_proc_tester.num_channels,
                self.image_proc_tester.size["""height"""],
                self.image_proc_tester.size["""width"""],
            )  ,       )

        # Test batched
        __a					=  image_processor(__A  ,       return_tensors="""pt"""    ).pixel_values
        self.assertEqual(
            encoded_images.shape  ,       (
                self.image_proc_tester.batch_size,
                self.image_proc_tester.num_channels,
                self.image_proc_tester.size["""height"""],
                self.image_proc_tester.size["""width"""],
            )  ,       )



