




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


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

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

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



def 				_A  (		lowerCAmelCase_	:   List[str]     ):
     """simple docstring"""

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

     return wrapper



def 				_A  (		lowerCAmelCase_	:   str     ):
     """simple docstring"""

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

     return wrapper



def 				_A  (		lowerCAmelCase_	:   str     ):
     """simple docstring"""

     @wraps(lowerCAmelCase_     )
     def wrapper(self	:   Any  ,							lowerCAmelCase_	:   Dict     ):
          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 				_A  (		):
     """simple docstring"""

     lowerCAmelCase__            =					[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(
    UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__       )
@local
class 					__lowerCamelCase			(       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   a (			self	:	int  ,      SCREAMING_SNAKE_CASE__	:	Dict  ) ->			Optional[Any]:
         lowerCAmelCase__            =					"[...]"
         lowerCAmelCase__            =					importlib.import_module(
             datasets.load.metric_module_factory(os.path.join("metrics"  ,      SCREAMING_SNAKE_CASE__  )  ).module_path  )
         lowerCAmelCase__            =					datasets.load.import_main_class(metric_module.__name__  ,      dataset=SCREAMING_SNAKE_CASE__  )
         # check parameters
         lowerCAmelCase__            =					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(SCREAMING_SNAKE_CASE__  ,      metric_module.__name__  ):
              with self.use_local_metrics():
                   try:
                        lowerCAmelCase__            =					doctest.testmod(SCREAMING_SNAKE_CASE__  ,      verbose=SCREAMING_SNAKE_CASE__  ,      raise_on_error=SCREAMING_SNAKE_CASE__  )
                   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   a (			self	:	Optional[Any]  ,      SCREAMING_SNAKE_CASE__	:	Union[str, Any]  ) ->			Optional[Any]:
         lowerCAmelCase__            =					"[...]"
         lowerCAmelCase__            =					importlib.import_module(
             datasets.load.metric_module_factory(os.path.join("metrics"  ,      SCREAMING_SNAKE_CASE__  )  ).module_path  )
         # run doctest
         with self.use_local_metrics():
              lowerCAmelCase__            =					doctest.testmod(SCREAMING_SNAKE_CASE__  ,      verbose=SCREAMING_SNAKE_CASE__  ,      raise_on_error=SCREAMING_SNAKE_CASE__  )
         self.assertEqual(results.failed  ,      0  )
         self.assertGreater(results.attempted  ,      1  )


    @contextmanager
    def   a (			self	:	Dict  ,      SCREAMING_SNAKE_CASE__	:	Union[str, Any]  ,      SCREAMING_SNAKE_CASE__	:	List[str]  ) ->			Optional[Any]:
         if metric_name in self.INTENSIVE_CALLS_PATCHER:
              with self.INTENSIVE_CALLS_PATCHER[metric_name](SCREAMING_SNAKE_CASE__  ):
                   yield
         else:
              yield


    @contextmanager
    def   a (			self	:	List[str]  ) ->			Optional[int]:
         def load_local_metric(SCREAMING_SNAKE_CASE__	:	List[str]  ,      *SCREAMING_SNAKE_CASE__	:	List[str]  ,      **SCREAMING_SNAKE_CASE__	:	Union[str, Any]  ):
              return load_metric(os.path.join("metrics"  ,      SCREAMING_SNAKE_CASE__  )  ,      *SCREAMING_SNAKE_CASE__  ,      **SCREAMING_SNAKE_CASE__  )

         with patch("datasets.load_metric"  ) as mock_load_metric:
              lowerCAmelCase__            =					load_local_metric
              yield


    @classmethod
    def   a (			cls	:	str  ,      SCREAMING_SNAKE_CASE__	:	List[str]  ) ->			Tuple:
         def wrapper(SCREAMING_SNAKE_CASE__	:	int  ):
              lowerCAmelCase__            =					contextmanager(SCREAMING_SNAKE_CASE__  )
              lowerCAmelCase__            =					patcher
              return patcher

         return wrapper






@LocalMetricTest.register_intensive_calls_patcher("bleurt"     )
def 				_A  (		lowerCAmelCase_	:   int     ):
     """simple docstring"""

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

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





     class 					__lowerCamelCase			(       UpperCamelCase__       ):




         """simple docstring"""

         def   a (			self	:	Union[str, Any]  ,      SCREAMING_SNAKE_CASE__	:	List[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:
          lowerCAmelCase__            =					MockedPredictor()
          yield



@LocalMetricTest.register_intensive_calls_patcher("bertscore"     )
def 				_A  (		lowerCAmelCase_	:   List[Any]     ):
     """simple docstring"""

     import torch

     def bert_cos_score_idf(lowerCAmelCase_	:   List[str]  ,							lowerCAmelCase_	:   str  ,							*lowerCAmelCase_	:   Tuple  ,							**lowerCAmelCase_	:   List[str]     ):
          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:
          lowerCAmelCase__            =					bert_cos_score_idf
          yield



@LocalMetricTest.register_intensive_calls_patcher("comet"     )
def 				_A  (		lowerCAmelCase_	:   Union[str, Any]     ):
     """simple docstring"""

     def load_from_checkpoint(lowerCAmelCase_	:   Dict     ):





          class 					__lowerCamelCase			:




              """simple docstring"""

              def   a (			self	:	Any  ,      SCREAMING_SNAKE_CASE__	:	Any  ,      *SCREAMING_SNAKE_CASE__	:	Tuple  ,      **SCREAMING_SNAKE_CASE__	:	str  ) ->			int:
                   assert len(SCREAMING_SNAKE_CASE__  ) == 2
                   lowerCAmelCase__            =					[0.19, 0.92]
                   return scores, sum(SCREAMING_SNAKE_CASE__  ) / len(SCREAMING_SNAKE_CASE__  )






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






def 				_A  (		):
     """simple docstring"""

     lowerCAmelCase__            =					load_metric(os.path.join("metrics"  ,							"seqeval"     )     )
     lowerCAmelCase__            =					"ERROR"
     lowerCAmelCase__            =					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_     )




'''simple docstring'''






import unittest

from diffusers.pipelines.pipeline_utils import is_safetensors_compatible






class    __magic_name__				(						unittest.TestCase							):






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




          '''simple docstring'''
          _UpperCAmelCase  :  Any				       =[
              'safety_checker/pytorch_model.bin',
              'safety_checker/model.safetensors',
              'vae/diffusion_pytorch_model.bin',
              'vae/diffusion_pytorch_model.safetensors',
              'text_encoder/pytorch_model.bin',
              'text_encoder/model.safetensors',
              'unet/diffusion_pytorch_model.bin',
              'unet/diffusion_pytorch_model.safetensors',
          ]
          self.assertTrue(is_safetensors_compatible(snake_case))






       def      lowerCAmelCase						(     self)		->    List[str]:




          '''simple docstring'''
          _UpperCAmelCase  :  Optional[int]				       =[
              'unet/diffusion_pytorch_model.bin',
              'unet/diffusion_pytorch_model.safetensors',
          ]
          self.assertTrue(is_safetensors_compatible(snake_case))






       def      lowerCAmelCase						(     self)		->    Any:




          '''simple docstring'''
          _UpperCAmelCase  :  Union[str, Any]				       =[
              'safety_checker/pytorch_model.bin',
              'safety_checker/model.safetensors',
              'vae/diffusion_pytorch_model.bin',
              'vae/diffusion_pytorch_model.safetensors',
              'text_encoder/pytorch_model.bin',
              'text_encoder/model.safetensors',
              'unet/diffusion_pytorch_model.bin',
              # Removed: 'unet/diffusion_pytorch_model.safetensors',
          ]
          self.assertFalse(is_safetensors_compatible(snake_case))






       def      lowerCAmelCase						(     self)		->    Dict:




          '''simple docstring'''
          _UpperCAmelCase  :  int				       =[
              'text_encoder/pytorch_model.bin',
              'text_encoder/model.safetensors',
          ]
          self.assertTrue(is_safetensors_compatible(snake_case))






       def      lowerCAmelCase						(     self)		->    Any:




          '''simple docstring'''
          _UpperCAmelCase  :  Any				       =[
              'safety_checker/pytorch_model.bin',
              'safety_checker/model.safetensors',
              'vae/diffusion_pytorch_model.bin',
              'vae/diffusion_pytorch_model.safetensors',
              'text_encoder/pytorch_model.bin',
              # Removed: 'text_encoder/model.safetensors',
              'unet/diffusion_pytorch_model.bin',
              'unet/diffusion_pytorch_model.safetensors',
          ]
          self.assertFalse(is_safetensors_compatible(snake_case))






       def      lowerCAmelCase						(     self)		->    List[Any]:




          '''simple docstring'''
          _UpperCAmelCase  :  Union[str, Any]				       =[
              'safety_checker/pytorch_model.fp16.bin',
              'safety_checker/model.fp16.safetensors',
              'vae/diffusion_pytorch_model.fp16.bin',
              'vae/diffusion_pytorch_model.fp16.safetensors',
              'text_encoder/pytorch_model.fp16.bin',
              'text_encoder/model.fp16.safetensors',
              'unet/diffusion_pytorch_model.fp16.bin',
              'unet/diffusion_pytorch_model.fp16.safetensors',
          ]
          _UpperCAmelCase  :  str				       ='fp16'
          self.assertTrue(is_safetensors_compatible(snake_case    ,				variant=snake_case))






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




          '''simple docstring'''
          _UpperCAmelCase  :  Tuple				       =[
              'unet/diffusion_pytorch_model.fp16.bin',
              'unet/diffusion_pytorch_model.fp16.safetensors',
          ]
          _UpperCAmelCase  :  int				       ='fp16'
          self.assertTrue(is_safetensors_compatible(snake_case    ,				variant=snake_case))






       def      lowerCAmelCase						(     self)		->    Optional[int]:




          '''simple docstring'''
          # pass variant but use the non-variant filenames
          _UpperCAmelCase  :  Optional[int]				       =[
              'unet/diffusion_pytorch_model.bin',
              'unet/diffusion_pytorch_model.safetensors',
          ]
          _UpperCAmelCase  :  Optional[Any]				       ='fp16'
          self.assertTrue(is_safetensors_compatible(snake_case    ,				variant=snake_case))






       def      lowerCAmelCase						(     self)		->    int:




          '''simple docstring'''
          _UpperCAmelCase  :  str				       =[
              'safety_checker/pytorch_model.fp16.bin',
              'safety_checker/model.fp16.safetensors',
              'vae/diffusion_pytorch_model.fp16.bin',
              'vae/diffusion_pytorch_model.fp16.safetensors',
              'text_encoder/pytorch_model.fp16.bin',
              'text_encoder/model.fp16.safetensors',
              'unet/diffusion_pytorch_model.fp16.bin',
              # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors',
          ]
          _UpperCAmelCase  :  List[str]				       ='fp16'
          self.assertFalse(is_safetensors_compatible(snake_case    ,				variant=snake_case))






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




          '''simple docstring'''
          _UpperCAmelCase  :  Dict				       =[
              'text_encoder/pytorch_model.fp16.bin',
              'text_encoder/model.fp16.safetensors',
          ]
          _UpperCAmelCase  :  Optional[Any]				       ='fp16'
          self.assertTrue(is_safetensors_compatible(snake_case    ,				variant=snake_case))






       def      lowerCAmelCase						(     self)		->    Any:




          '''simple docstring'''
          # pass variant but use the non-variant filenames
          _UpperCAmelCase  :  Optional[int]				       =[
              'text_encoder/pytorch_model.bin',
              'text_encoder/model.safetensors',
          ]
          _UpperCAmelCase  :  List[Any]				       ='fp16'
          self.assertTrue(is_safetensors_compatible(snake_case    ,				variant=snake_case))






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




          '''simple docstring'''
          _UpperCAmelCase  :  str				       =[
              'safety_checker/pytorch_model.fp16.bin',
              'safety_checker/model.fp16.safetensors',
              'vae/diffusion_pytorch_model.fp16.bin',
              'vae/diffusion_pytorch_model.fp16.safetensors',
              'text_encoder/pytorch_model.fp16.bin',
              # 'text_encoder/model.fp16.safetensors',
              'unet/diffusion_pytorch_model.fp16.bin',
              'unet/diffusion_pytorch_model.fp16.safetensors',
          ]
          _UpperCAmelCase  :  Tuple				       ='fp16'
          self.assertFalse(is_safetensors_compatible(snake_case    ,				variant=snake_case))

