




"""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       UpperCAmelCase__ (snake_case__							:      List[Any]					):
  """simple docstring"""

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

  return wrapper


def       UpperCAmelCase__ (snake_case__							:      Any					):
  """simple docstring"""

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

  return wrapper


def       UpperCAmelCase__ (snake_case__							:      str					):
  """simple docstring"""

  @wraps(snake_case__					)
  def wrapper(self							:      Dict	,     snake_case__							:      Optional[Any]					):
    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       UpperCAmelCase__ ():
  """simple docstring"""

  _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(
    __a ,    __a ,    __a				)
@local
class       lowercase(  parameterized.TestCase				):







 '''simple docstring'''





 lowercase__				      =      {}
 lowercase__				      =      None


 @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning"""	)
 @pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning"""	)
 def 				UpperCamelCase_     (       self:	List[str],   a_:	List[str]	):




   '''simple docstring'''



   _snake_case							:	Any			=						"""[...]"""
   _snake_case							:	str			=						importlib.import_module(
       datasets.load.metric_module_factory(os.path.join("""metrics""",   a_	)	).module_path	)
   _snake_case							:	List[str]			=						datasets.load.import_main_class(metric_module.__name__,   dataset=a_	)
   # check parameters
   _snake_case							:	str			=						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:
         _snake_case							:	int			=						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 				UpperCamelCase_     (       self:	Optional[int],   a_:	List[Any]	):




   '''simple docstring'''



   _snake_case							:	Tuple			=						"""[...]"""
   _snake_case							:	str			=						importlib.import_module(
       datasets.load.metric_module_factory(os.path.join("""metrics""",   a_	)	).module_path	)
   # run doctest
   with self.use_local_metrics():
     _snake_case							:	int			=						doctest.testmod(a_,   verbose=a_,   raise_on_error=a_	)
   self.assertEqual(results.failed,   0	)
   self.assertGreater(results.attempted,   1	)


 @contextmanager
 def 				UpperCamelCase_     (       self:	List[Any],   a_:	Tuple,   a_:	Dict	):




   '''simple docstring'''



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


 @contextmanager
 def 				UpperCamelCase_     (       self:	str	):




   '''simple docstring'''



   def load_local_metric(a_:	Any,   *a_:	List[Any],   **a_:	Optional[Any]	):
     return load_metric(os.path.join("""metrics""",   a_	),   *a_,   **a_	)

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


 @classmethod
 def 				UpperCamelCase_     (       cls:	List[str],   a_:	Union[str, Any]	):




   '''simple docstring'''



   def wrapper(a_:	int	):
     _snake_case							:	str			=						contextmanager(a_	)
     _snake_case							:	Union[str, Any]			=						patcher
     return patcher

   return wrapper







@LocalMetricTest.register_intensive_calls_patcher("""bleurt"""					)
def       UpperCAmelCase__ (snake_case__							:      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(  __a				):







   '''simple docstring'''





   def 				UpperCamelCase_     (       self:	int,   a_:	Union[str, 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:
    _snake_case							:	Union[str, Any]			=						MockedPredictor()
    yield


@LocalMetricTest.register_intensive_calls_patcher("""bertscore"""					)
def       UpperCAmelCase__ (snake_case__							:      Optional[Any]					):
  """simple docstring"""

  import torch

  def bert_cos_score_idf(snake_case__							:      Optional[Any]	,     snake_case__							:      List[Any]	,     *snake_case__							:      List[str]	,     **snake_case__							:      int					):
    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:
    _snake_case							:	Union[str, Any]			=						bert_cos_score_idf
    yield


@LocalMetricTest.register_intensive_calls_patcher("""comet"""					)
def       UpperCAmelCase__ (snake_case__							:      Optional[int]					):
  """simple docstring"""

  def load_from_checkpoint(snake_case__							:      Dict					):






    class       lowercase:







     '''simple docstring'''





     def 				UpperCamelCase_     (       self:	Optional[int],   a_:	Union[str, Any],   *a_:	Optional[Any],   **a_:	Dict	):




       '''simple docstring'''



       assert len(a_	) == 2
       _snake_case							:	Optional[int]			=						[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:
    _snake_case							:	Any			=						None
    with patch("""comet.load_from_checkpoint"""					) as mock_load_from_checkpoint:
      _snake_case							:	Union[str, Any]			=						load_from_checkpoint
      yield






def       UpperCAmelCase__ ():
  """simple docstring"""

  _snake_case							:	Dict			=						load_metric(os.path.join("""metrics"""	,     """seqeval"""					)					)
  _snake_case							:	List[str]			=						"""ERROR"""
  _snake_case							:	int			=						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 os
import sys
import unittest


A_      			=       os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
A_      			=       os.path.join(git_repo_path, '''src''', '''diffusers''')






class       lowercase(  unittest.TestCase				):







 '''simple docstring'''





 def 				UpperCamelCase_     (       self:	Tuple	):




   '''simple docstring'''



   _snake_case							:	Optional[int]			=						find_backend("""    if not is_torch_available():"""	)
   self.assertEqual(a_,   """torch"""	)

   # backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
   # self.assertEqual(backend_with_underscore, "tensorflow_text")

   _snake_case							:	Any			=						find_backend("""    if not (is_torch_available() and is_transformers_available()):"""	)
   self.assertEqual(a_,   """torch_and_transformers"""	)

   # double_backend_with_underscore = find_backend(
   #    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
   # )
   # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

   _snake_case							:	Union[str, Any]			=						find_backend(
       """    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):"""	)
   self.assertEqual(a_,   """torch_and_transformers_and_onnx"""	)


 def 				UpperCamelCase_     (       self:	List[Any]	):




   '''simple docstring'''



   _snake_case							:	Dict			=						read_init()
   # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
   self.assertIn("""torch""",   a_	)
   self.assertIn("""torch_and_transformers""",   a_	)
   self.assertIn("""flax_and_transformers""",   a_	)
   self.assertIn("""torch_and_transformers_and_onnx""",   a_	)

   # Likewise, we can't assert on the exact content of a key
   self.assertIn("""UNet2DModel""",   objects["""torch"""]	)
   self.assertIn("""FlaxUNet2DConditionModel""",   objects["""flax"""]	)
   self.assertIn("""StableDiffusionPipeline""",   objects["""torch_and_transformers"""]	)
   self.assertIn("""FlaxStableDiffusionPipeline""",   objects["""flax_and_transformers"""]	)
   self.assertIn("""LMSDiscreteScheduler""",   objects["""torch_and_scipy"""]	)
   self.assertIn("""OnnxStableDiffusionPipeline""",   objects["""torch_and_transformers_and_onnx"""]	)


 def 				UpperCamelCase_     (       self:	List[str]	):




   '''simple docstring'''



   _snake_case							:	Optional[Any]			=						create_dummy_object("""CONSTANT""",   """'torch'"""	)
   self.assertEqual(a_,   """\nCONSTANT = None\n"""	)

   _snake_case							:	Optional[int]			=						create_dummy_object("""function""",   """'torch'"""	)
   self.assertEqual(
       a_,   """\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"""	)

   _snake_case							:	List[Any]			=						"""
class FakeClass(metaclass=DummyObject):
    _backends = 'torch'

    def __init__(self, *args, **kwargs):
        requires_backends(self, 'torch')

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, 'torch')

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, 'torch')
"""
   _snake_case							:	Union[str, Any]			=						create_dummy_object("""FakeClass""",   """'torch'"""	)
   self.assertEqual(a_,   a_	)


 def 				UpperCamelCase_     (       self:	Union[str, Any]	):




   '''simple docstring'''



   _snake_case							:	Union[str, Any]			=						"""# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, [\"torch\"])


class FakeClass(metaclass=DummyObject):
    _backends = [\"torch\"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, [\"torch\"])

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, [\"torch\"])

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, [\"torch\"])
"""
   _snake_case							:	List[Any]			=						create_dummy_files({"""torch""": ["""CONSTANT""", """function""", """FakeClass"""]}	)
   self.assertEqual(dummy_files["""torch"""],   a_	)


