import datasets

from .evaluate import evaluate


_UpperCAmelCase            =		"""\
@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}
}
"""

_UpperCAmelCase            =		"""
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.
"""

_UpperCAmelCase            =		"""
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  ):


				'''simple docstring'''






				def   lowerCAmelCase_       (						self ):



						"""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   lowerCAmelCase_       (						self		,     lowercase		,     lowercase ):



						"""simple docstring"""





						A_		:    Tuple         =				{prediction['id']: prediction['prediction_text'] for prediction in predictions}
						A_		:    Optional[Any]         =				[
						    {
						        'paragraphs': [
						            {
						                'qas': [
						                    {
						                        'answers': [{'text': answer_text} for answer_text in ref['answers']['text']],
						                        'id': ref['id'],
						                    }
						                    for ref in references
						                ]
						            }
						        ]
						    }
						]
						A_		:    Optional[int]         =				evaluate(dataset=lowercase		,     predictions=lowercase )
						return score







import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_squeezebert import SqueezeBertTokenizer


_UpperCAmelCase            =		logging.get_logger(__name__)

_UpperCAmelCase            =		{"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

_UpperCAmelCase            =		{
    """vocab_file""": {
        """squeezebert/squeezebert-uncased""": (
            """https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt"""
        ),
        """squeezebert/squeezebert-mnli""": """https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt""",
        """squeezebert/squeezebert-mnli-headless""": (
            """https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt"""
        ),
    },
    """tokenizer_file""": {
        """squeezebert/squeezebert-uncased""": (
            """https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json"""
        ),
        """squeezebert/squeezebert-mnli""": (
            """https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json"""
        ),
        """squeezebert/squeezebert-mnli-headless""": (
            """https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json"""
        ),
    },
}

_UpperCAmelCase            =		{
    """squeezebert/squeezebert-uncased""": 512,
    """squeezebert/squeezebert-mnli""": 512,
    """squeezebert/squeezebert-mnli-headless""": 512,
}


_UpperCAmelCase            =		{
    """squeezebert/squeezebert-uncased""": {"""do_lower_case""": True},
    """squeezebert/squeezebert-mnli""": {"""do_lower_case""": True},
    """squeezebert/squeezebert-mnli-headless""": {"""do_lower_case""": True},
}





class UpperCAmelCase						( __A  ):


				'''simple docstring'''






				lowerCamelCase_    = VOCAB_FILES_NAMES
				lowerCamelCase_    = PRETRAINED_VOCAB_FILES_MAP
				lowerCamelCase_    = PRETRAINED_INIT_CONFIGURATION
				lowerCamelCase_    = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				lowerCamelCase_    = SqueezeBertTokenizer
				def __init__(						self		,     lowercase=None		,     lowercase=None		,     lowercase=True		,     lowercase="[UNK]"		,     lowercase="[SEP]"		,     lowercase="[PAD]"		,     lowercase="[CLS]"		,     lowercase="[MASK]"		,     lowercase=True		,     lowercase=None		,     **lowercase		,     ):



						"""simple docstring"""





						super().__init__(
						    lowercase		,     tokenizer_file=lowercase		,     do_lower_case=lowercase		,     unk_token=lowercase		,     sep_token=lowercase		,     pad_token=lowercase		,     cls_token=lowercase		,     mask_token=lowercase		,     tokenize_chinese_chars=lowercase		,     strip_accents=lowercase		,     **lowercase		,     )

						A_		:    int         =				json.loads(self.backend_tokenizer.normalizer.__getstate__() )
						if (
						    normalizer_state.get('lowercase'		,     lowercase ) != do_lower_case
						    or normalizer_state.get('strip_accents'		,     lowercase ) != strip_accents
						    or normalizer_state.get('handle_chinese_chars'		,     lowercase ) != tokenize_chinese_chars
						):
								A_		:    Dict         =				getattr(lowercase		,     normalizer_state.pop('type' ) )
								A_		:    Optional[int]         =				do_lower_case
								A_		:    Optional[Any]         =				strip_accents
								A_		:    str         =				tokenize_chinese_chars
								A_		:    Any         =				normalizer_class(**lowercase )

						A_		:    Tuple         =				do_lower_case
				def   lowerCAmelCase_       (						self		,     lowercase		,     lowercase=None ):



						"""simple docstring"""





						A_		:    str         =				[self.cls_token_id] + token_ids_a + [self.sep_token_id]

						if token_ids_a:
								output += token_ids_a + [self.sep_token_id]

						return output
				def   lowerCAmelCase_       (						self		,     lowercase		,     lowercase = None ):



						"""simple docstring"""





						A_		:    Dict         =				[self.sep_token_id]
						A_		:    Union[str, Any]         =				[self.cls_token_id]
						if token_ids_a is None:
								return len(cls + token_ids_a + sep ) * [0]
						return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]







				def   lowerCAmelCase_       (						self		,     lowercase		,     lowercase = None ):



						"""simple docstring"""





						A_		:    Dict         =				self._tokenizer.model.save(lowercase		,     name=lowercase )
						return tuple(lowercase )






