



"""simple docstring"""
from scipy.stats import spearmanr

import datasets


_UpperCAmelCase     =			"""
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
"""

_UpperCAmelCase     =			"""
Args:
    predictions (`List[float]`): Predicted labels, as returned by a model.
    references (`List[float]`): Ground truth labels.
    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
            only the spearmanr score. Defaults to `False`.
Returns:
    spearmanr (`float`): Spearman correlation coefficient.
    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
    Example 1:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
        >>> print(results)
        {'spearmanr': -0.7}

    Example 2:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results['spearmanr'])
        -0.7
        >>> print(round(results['spearmanr_pvalue'], 2))
        0.19
"""

_UpperCAmelCase     =			r"""\
@book{kokoska2000crc,
  title={CRC standard probability and statistics tables and formulae},
  author={Kokoska, Stephen and Zwillinger, Daniel},
  year={2000},
  publisher={Crc Press}
}
@article{2020SciPy-NMeth,
  author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
            Haberland, Matt and Reddy, Tyler and Cournapeau, David and
            Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
            Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
            Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
            Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
            Kern, Robert and Larson, Eric and Carey, C J and
            Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and
            {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
            Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
            Harris, Charles R. and Archibald, Anne M. and
            Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and
            {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
  title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
            Computing in Python}},
  journal = {Nature Methods},
  year    = {2020},
  volume  = {17},
  pages   = {261--272},
  adsurl  = {https://rdcu.be/b08Wh},
  doi     = {10.1038/s41592-019-0686-2},
}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,      _KWARGS_DESCRIPTION       )
class 					a	(  datasets.Metric       ):



  def 	lowerCamelCase__       (						self :					str		)     ->					List[Any]:


     '''simple docstring'''




     return datasets.MetricInfo(
         description=_DESCRIPTION       ,		citation=_CITATION       ,		inputs_description=_KWARGS_DESCRIPTION       ,		features=datasets.Features(
             {
                 """predictions""": datasets.Value("""float"""		),
                 """references""": datasets.Value("""float"""		),
             }		)       ,		reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html"""]       ,		)





  def 	lowerCamelCase__       (						self :					List[Any]       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					List[Any]       ,		lowerCAmelCase :					Dict=False		)     ->					Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Dict     			=spearmanr(lowerCAmelCase       ,		lowerCAmelCase		)
     if return_pvalue:
        return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
     else:
        return {"spearmanr": results[0]}








"""simple docstring"""
from collections import Counter
from pathlib import Path
from typing import Optional, Tuple

import yaml
class 					a	(  yaml.SafeLoader       ):



  def 	lowerCamelCase__       (						self :					int       ,		lowerCAmelCase :					List[str]		)     ->					Optional[Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Any     			=[self.constructed_objects[key_node] for key_node, _ in node.value]
     SCREAMING_SNAKE_CASE_: Any     			=[tuple(lowerCAmelCase		) if isinstance(lowerCAmelCase       ,		lowerCAmelCase		) else key for key in keys]
     SCREAMING_SNAKE_CASE_: Dict     			=Counter(lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: List[str]     			=[key for key in counter if counter[key] > 1]
     if duplicate_keys:
        raise TypeError(f'''Got duplicate yaml keys: {duplicate_keys}'''		)





  def 	lowerCamelCase__       (						self :					Tuple       ,		lowerCAmelCase :					str       ,		lowerCAmelCase :					Optional[int]=False		)     ->					int:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Tuple     			=super().construct_mapping(lowerCAmelCase       ,		deep=lowerCAmelCase		)
     self._check_no_duplicates_on_constructed_node(lowerCAmelCase		)
     return mapping







def      __magic_name__				(							lowercase ):
   SCREAMING_SNAKE_CASE_: Dict     			=list(readme_content.splitlines() )
   if full_content and full_content[0] == "---" and "---" in full_content[1:]:
      SCREAMING_SNAKE_CASE_: Union[str, Any]     			=full_content[1:].index("""---""" ) + 1
      SCREAMING_SNAKE_CASE_: List[str]     			="""\n""".join(full_content[1:sep_idx] )
      return yamlblock, "\n".join(full_content[sep_idx + 1 :] )

   return None, "\n".join(lowercase )
class 					a	(  UpperCAmelCase__       ):
  # class attributes
  UpperCamelCase	:				Tuple     						=					{'train_eval_index'}  # train-eval-index in the YAML metadata



  @classmethod
  def 	lowerCamelCase__       (						cls :					List[Any]       ,		lowerCAmelCase :					Path		)     ->					"DatasetMetadata":


     '''simple docstring'''




     with open(lowerCAmelCase       ,		encoding="""utf-8"""		) as readme_file:
        SCREAMING_SNAKE_CASE_			,		SCREAMING_SNAKE_CASE_: Union[str, Any]     			=_split_yaml_from_readme(readme_file.read()		)
     if yaml_string is not None:
        return cls.from_yaml_string(lowerCAmelCase		)
     else:
        return cls()



  def 	lowerCamelCase__       (						self :					Any       ,		lowerCAmelCase :					Path		)     ->					List[str]:


     '''simple docstring'''




     if path.exists():
        with open(lowerCAmelCase       ,		encoding="""utf-8"""		) as readme_file:
           SCREAMING_SNAKE_CASE_: str     			=readme_file.read()
     else:
        SCREAMING_SNAKE_CASE_: str     			=None
     SCREAMING_SNAKE_CASE_: Tuple     			=self._to_readme(lowerCAmelCase		)
     with open(lowerCAmelCase       ,		"""w"""       ,		encoding="""utf-8"""		) as readme_file:
        readme_file.write(lowerCAmelCase		)



  def 	lowerCamelCase__       (						self :					Optional[Any]       ,		lowerCAmelCase :					Optional[str] = None		)     ->					str:


     '''simple docstring'''




     if readme_content is not None:
        SCREAMING_SNAKE_CASE_			,		SCREAMING_SNAKE_CASE_: List[str]     			=_split_yaml_from_readme(lowerCAmelCase		)
        SCREAMING_SNAKE_CASE_: List[str]     			="""---\n""" + self.to_yaml_string() + """---\n""" + content
     else:
        SCREAMING_SNAKE_CASE_: List[Any]     			="""---\n""" + self.to_yaml_string() + """---\n"""
     return full_content



  @classmethod
  def 	lowerCamelCase__       (						cls :					Optional[int]       ,		lowerCAmelCase :					str		)     ->					"DatasetMetadata":


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: int     			=yaml.load(lowerCAmelCase       ,		Loader=_NoDuplicateSafeLoader		) or {}

     # Convert the YAML keys to DatasetMetadata fields
     SCREAMING_SNAKE_CASE_: List[Any]     			={
         (key.replace("""-"""       ,		"""_"""		) if key.replace("""-"""       ,		"""_"""		) in cls._FIELDS_WITH_DASHES else key): value
         for key, value in metadata_dict.items()
     }
     return cls(**lowerCAmelCase		)





  def 	lowerCamelCase__       (						self :					Dict		)     ->					str:


     '''simple docstring'''




     return yaml.safe_dump(
         {
             (key.replace("""_"""       ,		"""-"""		) if key in self._FIELDS_WITH_DASHES else key): value
             for key, value in self.items()
         }       ,		sort_keys=lowerCAmelCase       ,		allow_unicode=lowerCAmelCase       ,		encoding="""utf-8"""       ,		).decode("""utf-8"""		)







_UpperCAmelCase     =			{
    """image-classification""": [],
    """translation""": [],
    """image-segmentation""": [],
    """fill-mask""": [],
    """automatic-speech-recognition""": [],
    """token-classification""": [],
    """sentence-similarity""": [],
    """audio-classification""": [],
    """question-answering""": [],
    """summarization""": [],
    """zero-shot-classification""": [],
    """table-to-text""": [],
    """feature-extraction""": [],
    """other""": [],
    """multiple-choice""": [],
    """text-classification""": [],
    """text-to-image""": [],
    """text2text-generation""": [],
    """zero-shot-image-classification""": [],
    """tabular-classification""": [],
    """tabular-regression""": [],
    """image-to-image""": [],
    """tabular-to-text""": [],
    """unconditional-image-generation""": [],
    """text-retrieval""": [],
    """text-to-speech""": [],
    """object-detection""": [],
    """audio-to-audio""": [],
    """text-generation""": [],
    """conversational""": [],
    """table-question-answering""": [],
    """visual-question-answering""": [],
    """image-to-text""": [],
    """reinforcement-learning""": [],
    """voice-activity-detection""": [],
    """time-series-forecasting""": [],
    """document-question-answering""": [],
}


if __name__ == "__main__":
   from argparse import ArgumentParser

   _UpperCAmelCase     =			ArgumentParser(usage="""Validate the yaml metadata block of a README.md file.""")
   ap.add_argument("""readme_filepath""")
   _UpperCAmelCase     =			ap.parse_args()

   _UpperCAmelCase     =			Path(args.readme_filepath)
   _UpperCAmelCase     =			DatasetMetadata.from_readme(readme_filepath)
   print(dataset_metadata)
   dataset_metadata.to_readme(readme_filepath)



