

"""simple docstring"""




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

import datasets


__UpperCAmelCase =				"\\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"

__UpperCAmelCase =				"\\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"

__UpperCAmelCase =				"\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   lowerCAmelCase						(					__UpperCamelCase							,    __UpperCamelCase      ):
 '''simple docstring'''





 return float((preds == labels).mean()      )
def   lowerCAmelCase						(					__UpperCamelCase							,    __UpperCamelCase      ):
 '''simple docstring'''





 UpperCAmelCase__					:  Tuple					   =					simple_accuracy(__UpperCamelCase							,    __UpperCamelCase      )
 UpperCAmelCase__					:  Optional[Any]					   =					float(fa_score(y_true=__UpperCamelCase							,    y_pred=__UpperCamelCase      )      )
 return {
     "accuracy": acc,
     "f1": fa,
 }
def   lowerCAmelCase						(					__UpperCamelCase							,    __UpperCamelCase      ):
 '''simple docstring'''





 UpperCAmelCase__					:  List[Any]					   =					float(pearsonr(__UpperCamelCase							,    __UpperCamelCase      )[0]      )
 UpperCAmelCase__					:  Optional[int]					   =					float(spearmanr(__UpperCamelCase							,    __UpperCamelCase      )[0]      )
 return {
     "pearson": pearson_corr,
     "spearmanr": spearman_corr,
 }







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

  def    __lowercase       (  self		:			int    ):






   '''simple docstring'''
   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    __lowercase       (  self		:			List[Any]					,A		:			Union[str, Any]					,A		:			List[str]    ):






   '''simple docstring'''
   if self.config_name == "cola":
    return {"matthews_correlation": matthews_corrcoef(A_					,A_    )}
   elif self.config_name == "stsb":
    return pearson_and_spearman(A_					,A_    )
   elif self.config_name in ["mrpc", "qqp"]:
    return acc_and_fa(A_					,A_    )
   elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]:
    return {"accuracy": simple_accuracy(A_					,A_    )}
   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\"]"""    )








"""simple docstring"""




import argparse
import os
import re

import packaging.version


__UpperCAmelCase =				'examples/'
__UpperCAmelCase =				{
    'examples': (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'),
    'init': (re.compile(r'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'),
    'setup': (re.compile(r'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), r'\1version="VERSION",'),
    'doc': (re.compile(r'^(\s*)release\s*=\s*"[^"]+"$', re.MULTILINE), 'release = "VERSION"\n'),
}
__UpperCAmelCase =				{
    'init': 'src/transformers/__init__.py',
    'setup': 'setup.py',
}
__UpperCAmelCase =				'README.md'
def   lowerCAmelCase						(					__UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase      ):
 '''simple docstring'''





 with open(__UpperCamelCase							,    """r"""							,    encoding="""utf-8"""							,    newline="""\n"""      ) as f:
  UpperCAmelCase__					:  Dict					   =					f.read()
 UpperCAmelCase__   ,      UpperCAmelCase__					:  Any					   =					REPLACE_PATTERNS[pattern]
 UpperCAmelCase__					:  List[str]					   =					replace.replace("""VERSION"""							,    __UpperCamelCase      )
 UpperCAmelCase__					:  Tuple					   =					re_pattern.sub(__UpperCamelCase							,    __UpperCamelCase      )
 with open(__UpperCamelCase							,    """w"""							,    encoding="""utf-8"""							,    newline="""\n"""      ) as f:
  f.write(__UpperCamelCase      )
def   lowerCAmelCase						(					__UpperCamelCase      ):
 '''simple docstring'''





 for folder, directories, fnames in os.walk(__UpperCamelCase      ):
  # Removing some of the folders with non-actively maintained examples from the walk
  if "research_projects" in directories:
   directories.remove("""research_projects"""      )
  if "legacy" in directories:
   directories.remove("""legacy"""      )
  for fname in fnames:
   if fname.endswith(""".py"""      ):
    update_version_in_file(os.path.join(__UpperCamelCase							,    __UpperCamelCase      )							,    __UpperCamelCase							,    pattern="""examples"""      )
def   lowerCAmelCase						(					__UpperCamelCase							,    __UpperCamelCase=False      ):
 '''simple docstring'''





 for pattern, fname in REPLACE_FILES.items():
  update_version_in_file(__UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase      )
 if not patch:
  update_version_in_examples(__UpperCamelCase      )
def   lowerCAmelCase						(					):
 '''simple docstring'''





 UpperCAmelCase__					:  Dict					   =					"""🤗 Transformers currently provides the following architectures"""
 UpperCAmelCase__					:  Union[str, Any]					   =					"""1. Want to contribute a new model?"""
 with open(__UpperCamelCase							,    """r"""							,    encoding="""utf-8"""							,    newline="""\n"""      ) as f:
  UpperCAmelCase__					:  str					   =					f.readlines()

 # Find the start of the list.
 UpperCAmelCase__					:  List[Any]					   =					0
 while not lines[start_index].startswith(_start_prompt      ):
  start_index += 1
 start_index += 1

 UpperCAmelCase__					:  int					   =					start_index
 # Update the lines in the model list.
 while not lines[index].startswith(_end_prompt      ):
  if lines[index].startswith("""1."""      ):
   UpperCAmelCase__					:  List[Any]					   =					lines[index].replace(
       """https://huggingface.co/docs/transformers/main/model_doc"""							,    """https://huggingface.co/docs/transformers/model_doc"""							,    )
  index += 1

 with open(__UpperCamelCase							,    """w"""							,    encoding="""utf-8"""							,    newline="""\n"""      ) as f:
  f.writelines(__UpperCamelCase      )
def   lowerCAmelCase						(					):
 '''simple docstring'''





 with open(REPLACE_FILES["""init"""]							,    """r"""      ) as f:
  UpperCAmelCase__					:  Optional[Any]					   =					f.read()
 UpperCAmelCase__					:  int					   =					REPLACE_PATTERNS["""init"""][0].search(__UpperCamelCase      ).groups()[0]
 return packaging.version.parse(__UpperCamelCase      )
def   lowerCAmelCase						(					__UpperCamelCase=False      ):
 '''simple docstring'''





 UpperCAmelCase__					:  List[str]					   =					get_version()
 if patch and default_version.is_devrelease:
  raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!"""      )
 if default_version.is_devrelease:
  UpperCAmelCase__					:  List[str]					   =					default_version.base_version
 elif patch:
  UpperCAmelCase__					:  Any					   =					F"{default_version.major}.{default_version.minor}.{default_version.micro + 1}"
 else:
  UpperCAmelCase__					:  Optional[Any]					   =					F"{default_version.major}.{default_version.minor + 1}.0"

 # Now let's ask nicely if that's the right one.
 UpperCAmelCase__					:  Optional[int]					   =					input(F"Which version are you releasing? [{default_version}]"      )
 if len(__UpperCamelCase      ) == 0:
  UpperCAmelCase__					:  Union[str, Any]					   =					default_version

 print(F"Updating version to {version}."      )
 global_version_update(__UpperCamelCase							,    patch=__UpperCamelCase      )
 if not patch:
  print("""Cleaning main README, don't forget to run `make fix-copies`."""      )
  clean_main_ref_in_model_list()
def   lowerCAmelCase						(					):
 '''simple docstring'''





 UpperCAmelCase__					:  Optional[Any]					   =					get_version()
 UpperCAmelCase__					:  Any					   =					F"{current_version.major}.{current_version.minor + 1}.0.dev0"
 UpperCAmelCase__					:  List[Any]					   =					current_version.base_version

 # Check with the user we got that right.
 UpperCAmelCase__					:  Dict					   =					input(F"Which version are we developing now? [{dev_version}]"      )
 if len(__UpperCamelCase      ) == 0:
  UpperCAmelCase__					:  List[Any]					   =					dev_version

 print(F"Updating version to {version}."      )
 global_version_update(__UpperCamelCase      )
 print("""Cleaning main README, don't forget to run `make fix-copies`."""      )
 clean_main_ref_in_model_list()


if __name__ == "__main__":
      __UpperCAmelCase =				argparse.ArgumentParser()
      parser.add_argument('--post_release', action='store_true', help='Whether this is pre or post release.')
      parser.add_argument('--patch', action='store_true', help='Whether or not this is a patch release.')
      __UpperCAmelCase =				parser.parse_args()
      if not args.post_release:
            pre_release_work(patch=args.patch)
      elif args.patch:
            print('Nothing to do after a patch :-)')
      else:
            post_release_work()





