






import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


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

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


UpperCamelCase        =				get_tests_dir("fixtures")
UpperCamelCase        =				get_tests_dir("fixtures/dummy_feature_extractor_config.json")
UpperCamelCase        =				get_tests_dir("fixtures/dummy-config.json")

class        lowerCAmelCase_				(      unittest.TestCase	):







				"""simple docstring"""




				def 				__a   ( self     :Optional[int]     ):
					UpperCamelCase__ :Optional[int]						=      0







				def 				__a   ( self     :str     ):
					UpperCamelCase__ :Optional[Any]						=      AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h"""     )
					self.assertIsInstance(lowerCamelCase__  ,     lowerCamelCase__     )







				def 				__a   ( self     :Dict     ):
					UpperCamelCase__ :Dict						=      AutoFeatureExtractor.from_pretrained(lowerCamelCase__     )
					self.assertIsInstance(lowerCamelCase__  ,     lowerCamelCase__     )







				def 				__a   ( self     :Optional[int]     ):
					with tempfile.TemporaryDirectory() as tmpdirname:
						UpperCamelCase__ :List[str]						=      WavaVecaConfig()

						# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
						UpperCamelCase__ :Tuple						=      AutoFeatureExtractor.from_pretrained(lowerCamelCase__     ).to_dict()

						config_dict.pop("""feature_extractor_type"""     )
						UpperCamelCase__ :Union[str, Any]						=      WavaVecaFeatureExtractor(**lowerCamelCase__     )

						# save in new folder
						model_config.save_pretrained(lowerCamelCase__     )
						config.save_pretrained(lowerCamelCase__     )

						UpperCamelCase__ :Optional[Any]						=      AutoFeatureExtractor.from_pretrained(lowerCamelCase__     )

						# make sure private variable is not incorrectly saved
						UpperCamelCase__ :Tuple						=      json.loads(config.to_json_string()     )
						self.assertTrue("""_processor_class""" not in dict_as_saved     )

					self.assertIsInstance(lowerCamelCase__  ,     lowerCamelCase__     )







				def 				__a   ( self     :Union[str, Any]     ):
					UpperCamelCase__ :Dict						=      AutoFeatureExtractor.from_pretrained(lowerCamelCase__     )
					self.assertIsInstance(lowerCamelCase__  ,     lowerCamelCase__     )







				def 				__a   ( self     :Dict     ):
					with self.assertRaisesRegex(
					    lowerCamelCase__  ,     """bert-base is not a local folder and is not a valid model identifier"""     ):
						UpperCamelCase__ :Dict						=      AutoFeatureExtractor.from_pretrained("""bert-base"""     )







				def 				__a   ( self     :List[Any]     ):
					with self.assertRaisesRegex(
					    lowerCamelCase__  ,     r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""     ):
						UpperCamelCase__ :Optional[int]						=      AutoFeatureExtractor.from_pretrained(lowerCamelCase__  ,     revision="""aaaaaa"""     )







				def 				__a   ( self     :int     ):
					with self.assertRaisesRegex(
					    lowerCamelCase__  ,     """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."""  ,     ):
						UpperCamelCase__ :List[Any]						=      AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model"""     )







				def 				__a   ( self     :Optional[int]     ):
					# If remote code is not set, we will time out when asking whether to load the model.
					with self.assertRaises(lowerCamelCase__     ):
						UpperCamelCase__ :List[Any]						=      AutoFeatureExtractor.from_pretrained(
						    """hf-internal-testing/test_dynamic_feature_extractor"""     )
					# If remote code is disabled, we can't load this config.
					with self.assertRaises(lowerCamelCase__     ):
						UpperCamelCase__ :Optional[Any]						=      AutoFeatureExtractor.from_pretrained(
						    """hf-internal-testing/test_dynamic_feature_extractor"""  ,     trust_remote_code=lowerCamelCase__     )

					UpperCamelCase__ :str						=      AutoFeatureExtractor.from_pretrained(
					    """hf-internal-testing/test_dynamic_feature_extractor"""  ,     trust_remote_code=lowerCamelCase__     )
					self.assertEqual(feature_extractor.__class__.__name__  ,     """NewFeatureExtractor"""     )

					# Test feature extractor can be reloaded.
					with tempfile.TemporaryDirectory() as tmp_dir:
						feature_extractor.save_pretrained(lowerCamelCase__     )
						UpperCamelCase__ :Any						=      AutoFeatureExtractor.from_pretrained(lowerCamelCase__  ,     trust_remote_code=lowerCamelCase__     )
					self.assertEqual(reloaded_feature_extractor.__class__.__name__  ,     """NewFeatureExtractor"""     )







				def 				__a   ( self     :Dict     ):
					try:
						AutoConfig.register("""custom"""  ,     lowerCamelCase__     )
						AutoFeatureExtractor.register(lowerCamelCase__  ,     lowerCamelCase__     )
						# Trying to register something existing in the Transformers library will raise an error
						with self.assertRaises(lowerCamelCase__     ):
							AutoFeatureExtractor.register(lowerCamelCase__  ,     lowerCamelCase__     )

						# Now that the config is registered, it can be used as any other config with the auto-API
						UpperCamelCase__ :Any						=      CustomFeatureExtractor.from_pretrained(lowerCamelCase__     )
						with tempfile.TemporaryDirectory() as tmp_dir:
							feature_extractor.save_pretrained(lowerCamelCase__     )
							UpperCamelCase__ :List[Any]						=      AutoFeatureExtractor.from_pretrained(lowerCamelCase__     )
							self.assertIsInstance(lowerCamelCase__  ,     lowerCamelCase__     )

					finally:
						if "custom" in CONFIG_MAPPING._extra_content:
							del CONFIG_MAPPING._extra_content["custom"]
						if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
							del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]







				def 				__a   ( self     :Optional[int]     ):

					class        lowerCAmelCase_				(      lowercase	):







									"""simple docstring"""




									_snake_case				:   Optional[int]        =			True

					try:
						AutoConfig.register("""custom"""  ,     lowerCamelCase__     )
						AutoFeatureExtractor.register(lowerCamelCase__  ,     lowerCamelCase__     )
						# If remote code is not set, the default is to use local
						UpperCamelCase__ :Optional[Any]						=      AutoFeatureExtractor.from_pretrained(
						    """hf-internal-testing/test_dynamic_feature_extractor"""     )
						self.assertEqual(feature_extractor.__class__.__name__  ,     """NewFeatureExtractor"""     )
						self.assertTrue(feature_extractor.is_local     )

						# If remote code is disabled, we load the local one.
						UpperCamelCase__ :str						=      AutoFeatureExtractor.from_pretrained(
						    """hf-internal-testing/test_dynamic_feature_extractor"""  ,     trust_remote_code=lowerCamelCase__     )
						self.assertEqual(feature_extractor.__class__.__name__  ,     """NewFeatureExtractor"""     )
						self.assertTrue(feature_extractor.is_local     )

						# If remote is enabled, we load from the Hub
						UpperCamelCase__ :Optional[int]						=      AutoFeatureExtractor.from_pretrained(
						    """hf-internal-testing/test_dynamic_feature_extractor"""  ,     trust_remote_code=lowerCamelCase__     )
						self.assertEqual(feature_extractor.__class__.__name__  ,     """NewFeatureExtractor"""     )
						self.assertTrue(not hasattr(lowerCamelCase__  ,     """is_local"""     )     )

					finally:
						if "custom" in CONFIG_MAPPING._extra_content:
							del CONFIG_MAPPING._extra_content["custom"]
						if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
							del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]



"""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	:  List[str]            =     pytest.mark.integration


A	:  Optional[Any]            =     {"comet"}
A	:  int            =     importlib.util.find_spec("fairseq") is not None

A	:  Union[str, Any]            =     {"code_eval"}
A	:  Dict            =     os.name == "nt"

A	:  Dict            =     {"bertscore", "frugalscore", "perplexity"}
A	:  Any            =     importlib.util.find_spec("transformers") is not None


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




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

			return wrapper


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




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

			return wrapper


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




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

			return wrapper


def _lowerCamelCase      (						):

			'''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(
    lowerCAmelCase__			,lowerCAmelCase__			,lowerCAmelCase__						)
@local
class     _UpperCamelCase    (  parameterized.TestCase						):
							'''simple docstring'''







							__UpperCAmelCase		:       Any							 ={}
							__UpperCAmelCase		:       List[str]							 =None

							@pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning"      )
							@pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning"      )
							def      snake_case							(	self       ,  __a      ):
										__lowerCAmelCase							       =     "[...]"
										__lowerCAmelCase							       =     importlib.import_module(
										    datasets.load.metric_module_factory(os.path.join("metrics"       ,  __a      )      ).module_path      )
										__lowerCAmelCase							       =     datasets.load.import_main_class(metric_module.__name__       ,  dataset=__a      )
										# 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(__a       ,  metric_module.__name__      ):
													with self.use_local_metrics():
																try:
																			__lowerCAmelCase							       =     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      snake_case							(	self       ,  __a      ):
										__lowerCAmelCase							       =     "[...]"
										__lowerCAmelCase							       =     importlib.import_module(
										    datasets.load.metric_module_factory(os.path.join("metrics"       ,  __a      )      ).module_path      )
										# run doctest
										with self.use_local_metrics():
													__lowerCAmelCase							       =     doctest.testmod(__a       ,  verbose=__a       ,  raise_on_error=__a      )
										self.assertEqual(results.failed       ,  0      )
										self.assertGreater(results.attempted       ,  1      )

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

							@contextmanager
							def      snake_case							(	self      ):
										def load_local_metric(__a       ,  *__a       ,  **__a      ):
													return load_metric(os.path.join("metrics"       ,  __a      )       ,  *__a       ,  **__a      )

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



							@classmethod
							def      snake_case							(	cls       ,  __a      ):
										def wrapper(__a      ):
													__lowerCAmelCase							       =     contextmanager(__a      )
													__lowerCAmelCase							       =     patcher
													return patcher

										return wrapper


@LocalMetricTest.register_intensive_calls_patcher("bleurt" )
def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




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

			tf.flags.DEFINE_string("sv"       ,					""       ,					"" )  # handle pytest cli flags
			class     _UpperCamelCase    (  lowerCAmelCase__						):
										'''simple docstring'''







										def      snake_case							(	self       ,  __a      ):
													assert len(input_dict["input_ids"]      ) == 2
													return np.array([1.0_3, 1.0_4]      )

    # 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 _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			import torch

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

			# 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 _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			def load_from_checkpoint(_UpperCamelCase ):
						class     _UpperCamelCase    :
													'''simple docstring'''







													def      snake_case							(	self       ,  __a       ,  *__a       ,  **__a      ):
																assert len(__a      ) == 2
																__lowerCAmelCase							       =     [0.1_9, 0.9_2]
																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:
						__lowerCAmelCase							       =     None
						with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint:
									__lowerCAmelCase							       =     load_from_checkpoint
									yield


def _lowerCamelCase      (						):

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




