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  __lowerCAmelCase					(SCREAMING_SNAKE_CASE      )->						Optional[int]:




      """simple docstring"""

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

      return wrapper






def  __lowerCAmelCase					(SCREAMING_SNAKE_CASE      )->						List[Any]:




      """simple docstring"""

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

      return wrapper






def  __lowerCAmelCase					(SCREAMING_SNAKE_CASE      )->						List[str]:




      """simple docstring"""

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

      return wrapper






def  __lowerCAmelCase					()->						int:




      """simple docstring"""

      snake_case_ =   [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 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 		UpperCamelCase__  (			self	,   _UpperCAmelCase      ):
       snake_case_ =   '''[...]'''
       snake_case_ =   importlib.import_module(
           datasets.load.metric_module_factory(os.path.join('''metrics'''	,   _UpperCAmelCase      )      ).module_path      )
       snake_case_ =   datasets.load.import_main_class(metric_module.__name__	,   dataset=_UpperCAmelCase      )
       # check parameters
       snake_case_ =   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:
                         snake_case_ =   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 		UpperCamelCase__  (			self	,   _UpperCAmelCase      ):
       snake_case_ =   '''[...]'''
       snake_case_ =   importlib.import_module(
           datasets.load.metric_module_factory(os.path.join('''metrics'''	,   _UpperCAmelCase      )      ).module_path      )
       # run doctest
       with self.use_local_metrics():
             snake_case_ =   doctest.testmod(_UpperCAmelCase	,   verbose=_UpperCAmelCase	,   raise_on_error=_UpperCAmelCase      )
       self.assertEqual(results.failed	,   0      )
       self.assertGreater(results.attempted	,   1      )



 @contextmanager
 def 		UpperCamelCase__  (			self	,   _UpperCAmelCase	,   _UpperCAmelCase      ):
       if metric_name in self.INTENSIVE_CALLS_PATCHER:
             with self.INTENSIVE_CALLS_PATCHER[metric_name](_UpperCAmelCase      ):
                   yield
       else:
             yield



 @contextmanager
 def 		UpperCamelCase__  (			self      ):
       def load_local_metric(_UpperCAmelCase	,   *_UpperCAmelCase	,   **_UpperCAmelCase      ):
             return load_metric(os.path.join('''metrics'''	,   _UpperCAmelCase      )	,   *_UpperCAmelCase	,   **_UpperCAmelCase      )

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





 @classmethod
 def 		UpperCamelCase__  (			cls	,   _UpperCAmelCase      ):
       def wrapper(_UpperCAmelCase      ):
             snake_case_ =   contextmanager(_UpperCAmelCase      )
             snake_case_ =   patcher
             return patcher

       return wrapper






@LocalMetricTest.register_intensive_calls_patcher('''bleurt'''      )
def  __lowerCAmelCase					(SCREAMING_SNAKE_CASE      )->						Tuple:




      """simple docstring"""

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

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







      class lowerCAmelCase_		(				lowerCamelCase__ ):

       '''simple docstring'''

       def 		UpperCamelCase__  (			self	,   _UpperCAmelCase      ):
             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_ =   MockedPredictor()
            yield






@LocalMetricTest.register_intensive_calls_patcher('''bertscore'''      )
def  __lowerCAmelCase					(SCREAMING_SNAKE_CASE      )->						int:




      """simple docstring"""

      import torch

      def bert_cos_score_idf(SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      *SCREAMING_SNAKE_CASE      ,      **SCREAMING_SNAKE_CASE      ):
            return torch.tensor([[1.0, 1.0, 1.0]] * len(SCREAMING_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_ =   bert_cos_score_idf
            yield






@LocalMetricTest.register_intensive_calls_patcher('''comet'''      )
def  __lowerCAmelCase					(SCREAMING_SNAKE_CASE      )->						Optional[int]:




      """simple docstring"""

      def load_from_checkpoint(SCREAMING_SNAKE_CASE      ):







            class lowerCAmelCase_		:

             '''simple docstring'''

             def 		UpperCamelCase__  (			self	,   _UpperCAmelCase	,   *_UpperCAmelCase	,   **_UpperCAmelCase      ):
                   assert len(_UpperCAmelCase      ) == 2
                   snake_case_ =   [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:
            snake_case_ =   None
            with patch('''comet.load_from_checkpoint'''      ) as mock_load_from_checkpoint:
                  snake_case_ =   load_from_checkpoint
                  yield






def  __lowerCAmelCase					()->						str:




      """simple docstring"""

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



import unittest

import numpy as np

from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
   import onnxruntime as ort







class lowerCAmelCase_		(				lowerCamelCase__      ,		unittest.TestCase ):

 '''simple docstring'''

 pass







@nightly
@require_onnxruntime
@require_torch_gpu
class lowerCAmelCase_		(				unittest.TestCase ):

 '''simple docstring'''

 @property
 def 		UpperCamelCase__  (			self      ):
       return (
           "CUDAExecutionProvider",
           {
               "gpu_mem_limit": "15000000000",  # 15GB
               "arena_extend_strategy": "kSameAsRequested",
           },
       )



 @property
 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   ort.SessionOptions()
       snake_case_ =   False
       return options



 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/in_paint/overture-creations-5sI6fQgYIuo.png'''      )
       snake_case_ =   load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png'''      )
       snake_case_ =   OnnxStableDiffusionInpaintPipeline.from_pretrained(
           '''runwayml/stable-diffusion-inpainting'''	,   revision='''onnx'''	,   safety_checker=_UpperCAmelCase	,   feature_extractor=_UpperCAmelCase	,   provider=self.gpu_provider	,   sess_options=self.gpu_options	,   )
       pipe.set_progress_bar_config(disable=_UpperCAmelCase      )

       snake_case_ =   '''A red cat sitting on a park bench'''

       snake_case_ =   np.random.RandomState(0      )
       snake_case_ =   pipe(
           prompt=_UpperCAmelCase	,   image=_UpperCAmelCase	,   mask_image=_UpperCAmelCase	,   guidance_scale=7.5	,   num_inference_steps=10	,   generator=_UpperCAmelCase	,   output_type='''np'''	,   )
       snake_case_ =   output.images
       snake_case_ =   images[0, 2_55:2_58, 2_55:2_58, -1]

       assert images.shape == (1, 5_12, 5_12, 3)
       snake_case_ =   np.array([0.2_514, 0.3_007, 0.3_517, 0.1_790, 0.2_382, 0.3_167, 0.1_944, 0.2_273, 0.2_464]      )

       assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1E-3





 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/in_paint/overture-creations-5sI6fQgYIuo.png'''      )
       snake_case_ =   load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png'''      )
       snake_case_ =   LMSDiscreteScheduler.from_pretrained(
           '''runwayml/stable-diffusion-inpainting'''	,   subfolder='''scheduler'''	,   revision='''onnx'''      )
       snake_case_ =   OnnxStableDiffusionInpaintPipeline.from_pretrained(
           '''runwayml/stable-diffusion-inpainting'''	,   revision='''onnx'''	,   scheduler=_UpperCAmelCase	,   safety_checker=_UpperCAmelCase	,   feature_extractor=_UpperCAmelCase	,   provider=self.gpu_provider	,   sess_options=self.gpu_options	,   )
       pipe.set_progress_bar_config(disable=_UpperCAmelCase      )

       snake_case_ =   '''A red cat sitting on a park bench'''

       snake_case_ =   np.random.RandomState(0      )
       snake_case_ =   pipe(
           prompt=_UpperCAmelCase	,   image=_UpperCAmelCase	,   mask_image=_UpperCAmelCase	,   guidance_scale=7.5	,   num_inference_steps=20	,   generator=_UpperCAmelCase	,   output_type='''np'''	,   )
       snake_case_ =   output.images
       snake_case_ =   images[0, 2_55:2_58, 2_55:2_58, -1]

       assert images.shape == (1, 5_12, 5_12, 3)
       snake_case_ =   np.array([0.0_086, 0.0_077, 0.0_083, 0.0_093, 0.0_107, 0.0_139, 0.0_094, 0.0_097, 0.0_125]      )

       assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1E-3