

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


lowerCAmelCase__       = {"comet"}
lowerCAmelCase__       = importlib.util.find_spec("fairseq") is not None

lowerCAmelCase__       = {"code_eval"}
lowerCAmelCase__       = os.name == "nt"

lowerCAmelCase__       = {"bertscore", "frugalscore", "perplexity"}
lowerCAmelCase__       = importlib.util.find_spec("transformers") is not None
def      _lowerCAmelCase(	__A			):
  @wraps(__A			)
  def wrapper(self   ,       __A			):
    if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
      self.skipTest("\"test requires Fairseq\""			)
    else:
      test_case(self   ,       __A			)

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

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

  return wrapper
def      _lowerCAmelCase(	):
  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(
    _snake_case	,						_snake_case	,						_snake_case    )
@local
class 						__magic_name__    (       parameterized.TestCase    ):
 UpperCAmelCase							    =						{}
 UpperCAmelCase							    =						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]			,						lowerCAmelCase__		: Tuple    )    ->      Dict:
   UpperCAmelCase					      =  "[...]"
   UpperCAmelCase					      =  importlib.import_module(
       datasets.load.metric_module_factory(os.path.join("metrics"			,						lowerCAmelCase__    )    ).module_path    )
   UpperCAmelCase					      =  datasets.load.import_main_class(metric_module.__name__			,						dataset=lowerCAmelCase__    )
   # 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(lowerCAmelCase__			,						metric_module.__name__    ):
     with self.use_local_metrics():
       try:
         UpperCAmelCase					      =  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		: str			,						lowerCAmelCase__		: Optional[int]    )    ->      str:
   UpperCAmelCase					      =  "[...]"
   UpperCAmelCase					      =  importlib.import_module(
       datasets.load.metric_module_factory(os.path.join("metrics"			,						lowerCAmelCase__    )    ).module_path    )
   # run doctest
   with self.use_local_metrics():
     UpperCAmelCase					      =  doctest.testmod(lowerCAmelCase__			,						verbose=lowerCAmelCase__			,						raise_on_error=lowerCAmelCase__    )
   self.assertEqual(results.failed			,						0    )
   self.assertGreater(results.attempted			,						1    )


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


 @contextmanager
 def _UpperCamelCase	(						self		: List[str]    )    ->      int:
   def load_local_metric(lowerCAmelCase__		: Tuple			,						*lowerCAmelCase__		: str			,						**lowerCAmelCase__		: Dict    ):
     return load_metric(os.path.join("metrics"			,						lowerCAmelCase__    )			,						*lowerCAmelCase__			,						**lowerCAmelCase__    )

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


 @classmethod
 def _UpperCamelCase	(						cls		: List[Any]			,						lowerCAmelCase__		: Any    )    ->      str:
   def wrapper(lowerCAmelCase__		: List[Any]    ):
     UpperCAmelCase					      =  contextmanager(lowerCAmelCase__    )
     UpperCAmelCase					      =  patcher
     return patcher

   return wrapper

@LocalMetricTest.register_intensive_calls_patcher("bleurt"			)
def      _lowerCAmelCase(	__A			):
  import tensorflow.compat.va as tf
  from bleurt.score import Predictor

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






  class 						__magic_name__    (       _snake_case    ):


   def _UpperCamelCase	(						self		: Tuple			,						lowerCAmelCase__		: Any    )    ->      int:
     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(	__A			):
  import torch

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

  # 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(	__A			):
  def load_from_checkpoint(__A			):






    class 						__magic_name__    :


     def _UpperCamelCase	(						self		: Optional[Any]			,						lowerCAmelCase__		: Optional[int]			,						*lowerCAmelCase__		: Dict			,						**lowerCAmelCase__		: str    )    ->      Dict:
       assert len(lowerCAmelCase__    ) == 2
       UpperCAmelCase					      =  [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:
    UpperCAmelCase					      =  None
    with patch("comet.load_from_checkpoint"			) as mock_load_from_checkpoint:
      UpperCAmelCase					      =  load_from_checkpoint
      yield





def      _lowerCAmelCase(	):
  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(__A   ,       match=re.escape(__A			)			):
    metric.compute(predictions=[]   ,       references=[]   ,       scheme=__A			)






import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / "utils"))

from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


lowerCAmelCase__       = get_tests_dir("fixtures")






class 						__magic_name__    (       unittest.TestCase    ):


 def _UpperCamelCase	(						self		: Tuple    )    ->      Union[str, Any]:
   # A mock response for an HTTP head request to emulate server down
   UpperCAmelCase					      =  mock.Mock()
   UpperCAmelCase					      =  5_0_0
   UpperCAmelCase					      =  {}
   UpperCAmelCase					      =  HTTPError
   UpperCAmelCase					      =  {}

   # Download this model to make sure it's in the cache.
   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2"    )
   # Under the mock environment we get a 500 error when trying to reach the model.
   with mock.patch("requests.Session.request"			,						return_value=lowerCAmelCase__    ) as mock_head:
     UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2"    )
     # This check we did call the fake head request
     mock_head.assert_called()


 def _UpperCamelCase	(						self		: List[Any]    )    ->      Dict:
   # This test is for deprecated behavior and can be removed in v5
   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained(
       "https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json"    )






@is_staging_test
class 						__magic_name__    (       unittest.TestCase    ):


 @classmethod
 def _UpperCamelCase	(						cls		: List[str]    )    ->      List[Any]:
   UpperCAmelCase					      =  TOKEN
   HfFolder.save_token(lowerCAmelCase__    )


 @classmethod
 def _UpperCamelCase	(						cls		: Optional[int]    )    ->      Union[str, Any]:
   try:
     delete_repo(token=cls._token			,						repo_id="test-feature-extractor"    )
   except HTTPError:
     pass

   try:
     delete_repo(token=cls._token			,						repo_id="valid_org/test-feature-extractor-org"    )
   except HTTPError:
     pass

   try:
     delete_repo(token=cls._token			,						repo_id="test-dynamic-feature-extractor"    )
   except HTTPError:
     pass


 def _UpperCamelCase	(						self		: Any    )    ->      Any:
   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained(lowerCAmelCase__    )
   feature_extractor.push_to_hub("test-feature-extractor"			,						use_auth_token=self._token    )

   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor"    )
   for k, v in feature_extractor.__dict__.items():
     self.assertEqual(lowerCAmelCase__			,						getattr(lowerCAmelCase__			,						lowerCAmelCase__    )    )

   # Reset repo
   delete_repo(token=self._token			,						repo_id="test-feature-extractor"    )

   # Push to hub via save_pretrained
   with tempfile.TemporaryDirectory() as tmp_dir:
     feature_extractor.save_pretrained(
         lowerCAmelCase__			,						repo_id="test-feature-extractor"			,						push_to_hub=lowerCAmelCase__			,						use_auth_token=self._token    )

   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor"    )
   for k, v in feature_extractor.__dict__.items():
     self.assertEqual(lowerCAmelCase__			,						getattr(lowerCAmelCase__			,						lowerCAmelCase__    )    )


 def _UpperCamelCase	(						self		: List[Any]    )    ->      Tuple:
   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained(lowerCAmelCase__    )
   feature_extractor.push_to_hub("valid_org/test-feature-extractor"			,						use_auth_token=self._token    )

   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor"    )
   for k, v in feature_extractor.__dict__.items():
     self.assertEqual(lowerCAmelCase__			,						getattr(lowerCAmelCase__			,						lowerCAmelCase__    )    )

   # Reset repo
   delete_repo(token=self._token			,						repo_id="valid_org/test-feature-extractor"    )

   # Push to hub via save_pretrained
   with tempfile.TemporaryDirectory() as tmp_dir:
     feature_extractor.save_pretrained(
         lowerCAmelCase__			,						repo_id="valid_org/test-feature-extractor-org"			,						push_to_hub=lowerCAmelCase__			,						use_auth_token=self._token    )

   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor-org"    )
   for k, v in feature_extractor.__dict__.items():
     self.assertEqual(lowerCAmelCase__			,						getattr(lowerCAmelCase__			,						lowerCAmelCase__    )    )


 def _UpperCamelCase	(						self		: Dict    )    ->      List[str]:
   CustomFeatureExtractor.register_for_auto_class()
   UpperCAmelCase					      =  CustomFeatureExtractor.from_pretrained(lowerCAmelCase__    )

   feature_extractor.push_to_hub("test-dynamic-feature-extractor"			,						use_auth_token=self._token    )

   # This has added the proper auto_map field to the config
   self.assertDictEqual(
       feature_extractor.auto_map			,						{"AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor"}			,						)

   UpperCAmelCase					      =  AutoFeatureExtractor.from_pretrained(
       f"{USER}/test-dynamic-feature-extractor"			,						trust_remote_code=lowerCAmelCase__    )
   # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
   self.assertEqual(new_feature_extractor.__class__.__name__			,						"CustomFeatureExtractor"    )



