



"""simple docstring"""






import datasets

from .evaluate import evaluate


snake_case   					=				'''\
@article{hendrycks2021cuad,
      title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},
      author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},
      journal={arXiv preprint arXiv:2103.06268},
      year={2021}
}
'''

snake_case   					=				'''
This metric wrap the official scoring script for version 1 of the Contract
Understanding Atticus Dataset (CUAD).
Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510
commercial legal contracts that have been manually labeled to identify 41 categories of important
clauses that lawyers look for when reviewing contracts in connection with corporate transactions.
'''

snake_case   					=				'''
Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).
Args:
    predictions: List of question-answers dictionaries with the following key-values:
        - \'id\': id of the question-answer pair as given in the references (see below)
        - \'prediction_text\': list of possible texts for the answer, as a list of strings
        depending on a threshold on the confidence probability of each prediction.
    references: List of question-answers dictionaries with the following key-values:
        - \'id\': id of the question-answer pair (see above),
        - \'answers\': a Dict in the CUAD dataset format
            {
                \'text\': list of possible texts for the answer, as a list of strings
                \'answer_start\': list of start positions for the answer, as a list of ints
            }
            Note that answer_start values are not taken into account to compute the metric.
Returns:
    \'exact_match\': Exact match (the normalized answer exactly match the gold answer)
    \'f1\': The F-score of predicted tokens versus the gold answer
    \'aupr\': Area Under the Precision-Recall curve
    \'prec_at_80_recall\': Precision at 80% recall
    \'prec_at_90_recall\': Precision at 90% recall
Examples:
    >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]
    >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]
    >>> cuad_metric = datasets.load_metric("cuad")
    >>> results = cuad_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}
'''



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



   def    __UpperCAmelCase    (       self    :	List[Any]				):



     """simple docstring"""
     return datasets.MetricInfo(
         description=_DESCRIPTION							,       citation=_CITATION							,       inputs_description=_KWARGS_DESCRIPTION							,       features=datasets.Features(
             {
                 '''predictions''': {
                     '''id''': datasets.Value('''string'''				),
                     '''prediction_text''': datasets.features.Sequence(datasets.Value('''string'''				)				),
                 },
                 '''references''': {
                     '''id''': datasets.Value('''string'''				),
                     '''answers''': datasets.features.Sequence(
                         {
                             '''text''': datasets.Value('''string'''				),
                             '''answer_start''': datasets.Value('''int32'''				),
                         }				),
                 },
             }				)							,       codebase_urls=['''https://www.atticusprojectai.org/cuad''']							,       reference_urls=['''https://www.atticusprojectai.org/cuad''']							,       )





   def    __UpperCAmelCase    (       self    :	List[str]							,       __lowerCamelCase    :	Union[str, Any]							,       __lowerCamelCase    :	List[str]				):



     """simple docstring"""
     _snake_case   	=      {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions}
     _snake_case   	=      [
         {
             '''paragraphs''': [
                 {
                     '''qas''': [
                         {
                             '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']],
                             '''id''': ref['''id'''],
                         }
                         for ref in references
                     ]
                 }
             ]
         }
     ]
     _snake_case   	=      evaluate(dataset=__lowerCamelCase							,       predictions=__lowerCamelCase				)
     return score










"""simple docstring"""






from collections import Counter
from pathlib import Path
from typing import Optional, Tuple

import yaml



class     UpperCAmelCase    (	yaml.SafeLoader  ):



   def    __UpperCAmelCase    (       self    :	Tuple							,       __lowerCamelCase    :	List[str]				):



     """simple docstring"""
     _snake_case   	=      [self.constructed_objects[key_node] for key_node, _ in node.value]
     _snake_case   	=      [tuple(__lowerCamelCase				) if isinstance(__lowerCamelCase							,       __lowerCamelCase				) else key for key in keys]
     _snake_case   	=      Counter(__lowerCamelCase				)
     _snake_case   	=      [key for key in counter if counter[key] > 1]
     if duplicate_keys:
       raise TypeError(f"""Got duplicate yaml keys: {duplicate_keys}"""				)





   def    __UpperCAmelCase    (       self    :	str							,       __lowerCamelCase    :	Any							,       __lowerCamelCase    :	Optional[Any]=False				):



     """simple docstring"""
     _snake_case   	=      super().construct_mapping(__lowerCamelCase							,       deep=__lowerCamelCase				)
     self._check_no_duplicates_on_constructed_node(__lowerCamelCase				)
     return mapping




def 			snake_case		(		lowerCAmelCase_	)						->				Tuple[Optional[str], str]:
  _snake_case   	=      list(readme_content.splitlines()	)
  if full_content and full_content[0] == "---" and "---" in full_content[1:]:
    _snake_case   	=      full_content[1:].index('''---'''	) + 1
    _snake_case   	=      '''\n'''.join(full_content[1:sep_idx]	)
    return yamlblock, "\n".join(full_content[sep_idx + 1 :]	)

  return None, "\n".join(lowerCAmelCase_	)



class     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE  ):
   # class attributes
   A__		:	int           =  {'''train_eval_index'''}  # train-eval-index in the YAML metadata



   @classmethod
   def    __UpperCAmelCase    (       cls    :	str							,       __lowerCamelCase    :	Path				):



     """simple docstring"""
     with open(__lowerCamelCase							,       encoding='''utf-8'''				) as readme_file:
       _snake_case	,     _snake_case   	=      _split_yaml_from_readme(readme_file.read()				)
     if yaml_string is not None:
       return cls.from_yaml_string(__lowerCamelCase				)
     else:
       return cls()



   def    __UpperCAmelCase    (       self    :	List[Any]							,       __lowerCamelCase    :	Path				):



     """simple docstring"""
     if path.exists():
       with open(__lowerCamelCase							,       encoding='''utf-8'''				) as readme_file:
         _snake_case   	=      readme_file.read()
     else:
       _snake_case   	=      None
     _snake_case   	=      self._to_readme(__lowerCamelCase				)
     with open(__lowerCamelCase							,       '''w'''							,       encoding='''utf-8'''				) as readme_file:
       readme_file.write(__lowerCamelCase				)



   def    __UpperCAmelCase    (       self    :	Union[str, Any]							,       __lowerCamelCase    :	Optional[str] = None				):



     """simple docstring"""
     if readme_content is not None:
       _snake_case	,     _snake_case   	=      _split_yaml_from_readme(__lowerCamelCase				)
       _snake_case   	=      '''---\n''' + self.to_yaml_string() + '''---\n''' + content
     else:
       _snake_case   	=      '''---\n''' + self.to_yaml_string() + '''---\n'''
     return full_content



   @classmethod
   def    __UpperCAmelCase    (       cls    :	Tuple							,       __lowerCamelCase    :	str				):



     """simple docstring"""
     _snake_case   	=      yaml.load(__lowerCamelCase							,       Loader=_NoDuplicateSafeLoader				) or {}

     # Convert the YAML keys to DatasetMetadata fields
     _snake_case   	=      {
         (key.replace('''-'''							,       '''_'''				) if key.replace('''-'''							,       '''_'''				) in cls._FIELDS_WITH_DASHES else key): value
         for key, value in metadata_dict.items()
     }
     return cls(**__lowerCamelCase				)





   def    __UpperCAmelCase    (       self    :	Dict				):



     """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'''				)

snake_case   					=				{
    '''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

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

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





