






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

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
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


A_       :List[Any]       =						get_tests_dir('''fixtures/dummy-config.json''')




class 				__A     (			unittest.TestCase ):





				"""simple docstring"""







				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					str       		=0


				def       __lowercase							( self    ):




									"""simple docstring"""

									self.assertIsNotNone(transformers.models.auto.__spec__    )
									self.assertIsNotNone(importlib.util.find_spec('transformers.models.auto'    )    )


				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Tuple       		=AutoConfig.from_pretrained('bert-base-uncased'    )
									self.assertIsInstance(lowerCamelCase__							,  lowerCamelCase__    )


				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Optional[Any]       		=AutoConfig.from_pretrained(lowerCamelCase__    )
									self.assertIsInstance(lowerCamelCase__							,  lowerCamelCase__    )


				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Dict       		=AutoConfig.from_pretrained(lowerCamelCase__    )
									self.assertIsInstance(lowerCamelCase__							,  lowerCamelCase__    )


				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					List[str]       		=AutoConfig.for_model('roberta'    )
									self.assertIsInstance(lowerCamelCase__							,  lowerCamelCase__    )


				def       __lowercase							( self    ):




									"""simple docstring"""

									with tempfile.TemporaryDirectory() as tmp_dir:
														# This model name contains bert and roberta, but roberta ends up being picked.
														__UpperCamelCase      :					Tuple       		=os.path.join(lowerCamelCase__							,  'fake-roberta'    )
														os.makedirs(lowerCamelCase__							,  exist_ok=lowerCamelCase__    )
														with open(os.path.join(lowerCamelCase__							,  'config.json'    )							,  'w'    ) as f:
																			f.write(json.dumps({}    )    )
														__UpperCamelCase      :					Union[str, Any]       		=AutoConfig.from_pretrained(lowerCamelCase__    )
														self.assertEqual(type(lowerCamelCase__    )							,  lowerCamelCase__    )


				def       __lowercase							( self    ):




									"""simple docstring"""

									try:
														AutoConfig.register('custom'							,  lowerCamelCase__    )
														# Wrong model type will raise an error
														with self.assertRaises(lowerCamelCase__    ):
																			AutoConfig.register('model'							,  lowerCamelCase__    )
														# Trying to register something existing in the Transformers library will raise an error
														with self.assertRaises(lowerCamelCase__    ):
																			AutoConfig.register('bert'							,  lowerCamelCase__    )

														# Now that the config is registered, it can be used as any other config with the auto-API
														__UpperCamelCase      :					int       		=CustomConfig()
														with tempfile.TemporaryDirectory() as tmp_dir:
																			config.save_pretrained(lowerCamelCase__    )
																			__UpperCamelCase      :					Dict       		=AutoConfig.from_pretrained(lowerCamelCase__    )
																			self.assertIsInstance(lowerCamelCase__							,  lowerCamelCase__    )

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


				def       __lowercase							( self    ):




									"""simple docstring"""

									with self.assertRaisesRegex(
									    lowerCamelCase__							,  'bert-base is not a local folder and is not a valid model identifier'    ):
														__UpperCamelCase      :					int       		=AutoConfig.from_pretrained('bert-base'    )


				def       __lowercase							( self    ):




									"""simple docstring"""

									with self.assertRaisesRegex(
									    lowerCamelCase__							,  R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'    ):
														__UpperCamelCase      :					Tuple       		=AutoConfig.from_pretrained(lowerCamelCase__							,  revision='aaaaaa'    )


				def       __lowercase							( self    ):




									"""simple docstring"""

									with self.assertRaisesRegex(
									    lowerCamelCase__							,  'hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.'							,  ):
														__UpperCamelCase      :					Dict       		=AutoConfig.from_pretrained('hf-internal-testing/no-config-test-repo'    )


				def       __lowercase							( self    ):




									"""simple docstring"""

									with self.assertRaises(lowerCamelCase__    ):
														__UpperCamelCase      :					Tuple       		=AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'    )
									# If remote code is disabled, we can't load this config.
									with self.assertRaises(lowerCamelCase__    ):
														__UpperCamelCase      :					Tuple       		=AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'							,  trust_remote_code=lowerCamelCase__    )

									__UpperCamelCase      :					Tuple       		=AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'							,  trust_remote_code=lowerCamelCase__    )
									self.assertEqual(config.__class__.__name__							,  'NewModelConfig'    )

									# Test config can be reloaded.
									with tempfile.TemporaryDirectory() as tmp_dir:
														config.save_pretrained(lowerCamelCase__    )
														__UpperCamelCase      :					List[str]       		=AutoConfig.from_pretrained(lowerCamelCase__							,  trust_remote_code=lowerCamelCase__    )
									self.assertEqual(reloaded_config.__class__.__name__							,  'NewModelConfig'    )







				def       __lowercase							( self    ):




									"""simple docstring"""

									class 				__A     (			a ):





													"""simple docstring"""







													UpperCamelCase__ :      Optional[Any]			 ="""new-model"""

									try:
														AutoConfig.register('new-model'							,  lowerCamelCase__    )
														# If remote code is not set, the default is to use local
														__UpperCamelCase      :					str       		=AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'    )
														self.assertEqual(config.__class__.__name__							,  'NewModelConfigLocal'    )

														# If remote code is disabled, we load the local one.
														__UpperCamelCase      :					Dict       		=AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'							,  trust_remote_code=lowerCamelCase__    )
														self.assertEqual(config.__class__.__name__							,  'NewModelConfigLocal'    )

														# If remote is enabled, we load from the Hub
														__UpperCamelCase      :					List[str]       		=AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'							,  trust_remote_code=lowerCamelCase__    )
														self.assertEqual(config.__class__.__name__							,  'NewModelConfig'    )

									finally:
														if "new-model" in CONFIG_MAPPING._extra_content:
																			del CONFIG_MAPPING._extra_content["new-model"]








"""simple docstring"""





from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import fa_score, matthews_corrcoef

import datasets


SCREAMING_SNAKE_CASE__					=   "\\n@inproceedings{wang2019glue,\n  title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n  author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n  note={In the Proceedings of ICLR.},\n  year={2019}\n}\n"

SCREAMING_SNAKE_CASE__					=   "\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n"

SCREAMING_SNAKE_CASE__					=   "\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n    predictions: list of predictions to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n    \"accuracy\": Accuracy\n    \"f1\": F1 score\n    \"pearson\": Pearson Correlation\n    \"spearmanr\": Spearman Correlation\n    \"matthews_correlation\": Matthew Correlation\nExamples:\n\n    >>> glue_metric = datasets.load_metric('glue', 'sst2')  # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"]\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'mrpc')  # 'mrpc' or 'qqp'\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0, 'f1': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'stsb')\n    >>> references = [0., 1., 2., 3., 4., 5.]\n    >>> predictions = [0., 1., 2., 3., 4., 5.]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)})\n    {'pearson': 1.0, 'spearmanr': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'cola')\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'matthews_correlation': 1.0}\n"


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						Tuple							,						SCREAMING_SNAKE_CASE     :						List[Any]			):







      '''simple docstring'''




      return float((preds == labels).mean()			)


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						Optional[Any]							,						SCREAMING_SNAKE_CASE     :						Any			):







      '''simple docstring'''




      lowerCAmelCase  						=       simple_accuracy(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)
      lowerCAmelCase  						=       float(fa_score(y_true=SCREAMING_SNAKE_CASE							,						y_pred=SCREAMING_SNAKE_CASE			)			)
      return {
          "accuracy": acc,
          "f1": fa,
      }


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						List[str]							,						SCREAMING_SNAKE_CASE     :						Tuple			):







      '''simple docstring'''




      lowerCAmelCase  						=       float(pearsonr(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)[0]			)
      lowerCAmelCase  						=       float(spearmanr(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)[0]			)
      return {
          "pearson": pearson_corr,
          "spearmanr": spearman_corr,
      }






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,  _KWARGS_DESCRIPTION					)
class 		lowercase					(					datasets.Metric					):





      def     _snake_case			(       self )		->     List[str]:
            if self.config_name not in [
                "sst2",
                "mnli",
                "mnli_mismatched",
                "mnli_matched",
                "cola",
                "stsb",
                "mrpc",
                "qqp",
                "qnli",
                "rte",
                "wnli",
                "hans",
            ]:
                  raise KeyError(
                      """You should supply a configuration name selected in """
                      """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """
                      """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" )
            return datasets.MetricInfo(
                description=_DESCRIPTION      ,						citation=_CITATION      ,						inputs_description=_KWARGS_DESCRIPTION      ,						features=datasets.Features(
                    {
                        """predictions""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ),
                        """references""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ),
                    } )      ,						codebase_urls=[]      ,						reference_urls=[]      ,						format="""numpy"""      ,						)





      def     _snake_case			(       self      ,						lowercase      ,						lowercase )		->     Any:
            if self.config_name == "cola":
                  return {"matthews_correlation": matthews_corrcoef(lowercase      ,						lowercase )}
            elif self.config_name == "stsb":
                  return pearson_and_spearman(lowercase      ,						lowercase )
            elif self.config_name in ["mrpc", "qqp"]:
                  return acc_and_fa(lowercase      ,						lowercase )
            elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]:
                  return {"accuracy": simple_accuracy(lowercase      ,						lowercase )}
            else:
                  raise KeyError(
                      """You should supply a configuration name selected in """
                      """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """
                      """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" )






