





import numpy as np
import torch
from torch.utils.data import Dataset

from utils import logger






class        _a(    __A    ):







		def __init__(    self ,						__snake_case ,						__snake_case				)      ->      Optional[Any]:


							'''simple docstring'''

							_snake_case       :					Any				       =   params

							_snake_case       :					str				       =   np.array(__snake_case				)
							_snake_case       :					Tuple				       =   np.array([len(__snake_case				) for t in data]				)

							self.check()
							self.remove_long_sequences()
							self.remove_empty_sequences()
							self.remove_unknown_sequences()
							self.check()
							self.print_statistics()







		def __getitem__(    self ,						__snake_case				)      ->      Union[str, Any]:


							'''simple docstring'''

							return (self.token_ids[index], self.lengths[index])







		def __len__(    self				)      ->      Optional[int]:


							'''simple docstring'''

							return len(self.lengths				)







		def        lowercase       (    self				)      ->      int:


							'''simple docstring'''

							assert len(self.token_ids				) == len(self.lengths				)
							assert all(self.lengths[i] == len(self.token_ids[i]				) for i in range(len(self.lengths				)				)				)







		def        lowercase       (    self				)      ->      Optional[Any]:


							'''simple docstring'''

							_snake_case       :					Optional[Any]				       =   self.params.max_model_input_size
							_snake_case       :					Dict				       =   self.lengths > max_len
							logger.info(f"""Splitting {sum(__snake_case				)} too long sequences."""				)

							def divide_chunks(__snake_case ,						__snake_case				):
												return [l[i : i + n] for i in range(0 ,						len(__snake_case				) ,						__snake_case				)]

							_snake_case       :					Union[str, Any]				       =   []
							_snake_case       :					Dict				       =   []
							if self.params.mlm:
												_snake_case       , _snake_case       :					Optional[int]				       =   self.params.special_tok_ids["cls_token"], self.params.special_tok_ids["sep_token"]
							else:
												_snake_case       , _snake_case       :					Dict				       =   self.params.special_tok_ids["bos_token"], self.params.special_tok_ids["eos_token"]

							for seq_, len_ in zip(self.token_ids ,						self.lengths				):
												assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_
												if len_ <= max_len:
																	new_tok_ids.append(seq_				)
																	new_lengths.append(len_				)
												else:
																	_snake_case       :					Union[str, Any]				       =   []
																	for sub_s in divide_chunks(seq_ ,						max_len - 2				):
																						if sub_s[0] != cls_id:
																											_snake_case       :					List[Any]				       =   np.insert(__snake_case ,						0 ,						__snake_case				)
																						if sub_s[-1] != sep_id:
																											_snake_case       :					Optional[Any]				       =   np.insert(__snake_case ,						len(__snake_case				) ,						__snake_case				)
																						assert len(__snake_case				) <= max_len
																						assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s
																						sub_seqs.append(__snake_case				)

																	new_tok_ids.extend(__snake_case				)
																	new_lengths.extend([len(__snake_case				) for l in sub_seqs]				)

							_snake_case       :					Any				       =   np.array(__snake_case				)
							_snake_case       :					Any				       =   np.array(__snake_case				)







		def        lowercase       (    self				)      ->      Union[str, Any]:


							'''simple docstring'''

							_snake_case       :					Any				       =   len(self				)
							_snake_case       :					List[Any]				       =   self.lengths > 1_1
							_snake_case       :					Tuple				       =   self.token_ids[indices]
							_snake_case       :					Any				       =   self.lengths[indices]
							_snake_case       :					Tuple				       =   len(self				)
							logger.info(f"""Remove {init_size - new_size} too short (<=11 tokens) sequences."""				)







		def        lowercase       (    self				)      ->      List[str]:


							'''simple docstring'''

							if "unk_token" not in self.params.special_tok_ids:
												return
							else:
												_snake_case       :					Tuple				       =   self.params.special_tok_ids["unk_token"]
							_snake_case       :					Optional[Any]				       =   len(self				)
							_snake_case       :					List[str]				       =   np.array([np.count_nonzero(a == unk_token_id				) for a in self.token_ids]				)
							_snake_case       :					Tuple				       =   (unk_occs / self.lengths) < 0.5
							_snake_case       :					Optional[int]				       =   self.token_ids[indices]
							_snake_case       :					int				       =   self.lengths[indices]
							_snake_case       :					Optional[int]				       =   len(self				)
							logger.info(f"""Remove {init_size - new_size} sequences with a high level of unknown tokens (50%)."""				)







		def        lowercase       (    self				)      ->      Dict:


							'''simple docstring'''

							if not self.params.is_master:
												return
							logger.info(f"""{len(self				)} sequences"""				)
							# data_len = sum(self.lengths)
							# nb_unique_tokens = len(Counter(list(chain(*self.token_ids))))
							# logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)')

							# unk_idx = self.params.special_tok_ids['unk_token']
							# nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids])
							# logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)')







		def        lowercase       (    self ,						__snake_case				)      ->      str:


							'''simple docstring'''

							_snake_case       :					Optional[int]				       =   [t[0] for t in batch]
							_snake_case       :					Dict				       =   [t[1] for t in batch]
							assert len(__snake_case				) == len(__snake_case				)

							# Max for paddings
							_snake_case       :					List[str]				       =   max(__snake_case				)

							# Pad token ids
							if self.params.mlm:
												_snake_case       :					Any				       =   self.params.special_tok_ids["pad_token"]
							else:
												_snake_case       :					Optional[Any]				       =   self.params.special_tok_ids["unk_token"]
							_snake_case       :					Tuple				       =   [list(t.astype(__snake_case				)				) + [pad_idx] * (max_seq_len_ - len(__snake_case				)) for t in token_ids]
							assert len(tk_				) == len(__snake_case				)
							assert all(len(__snake_case				) == max_seq_len_ for t in tk_				)

							_snake_case       :					int				       =   torch.tensor(tk_				)  # (bs, max_seq_len_)
							_snake_case       :					Optional[Any]				       =   torch.tensor(__snake_case				)  # (bs)
							return tk_t, lg_t






import datasets

from .evaluate import evaluate


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

__lowerCAmelCase :Union[str, Any]     =    '\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n'

__lowerCAmelCase :Optional[Any]     =    '\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n    predictions: List of question-answers dictionaries with the following key-values:\n        - \'id\': id of the question-answer pair as given in the references (see below)\n        - \'prediction_text\': list of possible texts for the answer, as a list of strings\n        depending on a threshold on the confidence probability of each prediction.\n    references: List of question-answers dictionaries with the following key-values:\n        - \'id\': id of the question-answer pair (see above),\n        - \'answers\': a Dict in the CUAD dataset format\n            {\n                \'text\': list of possible texts for the answer, as a list of strings\n                \'answer_start\': list of start positions for the answer, as a list of ints\n            }\n            Note that answer_start values are not taken into account to compute the metric.\nReturns:\n    \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n    \'f1\': The F-score of predicted tokens versus the gold answer\n    \'aupr\': Area Under the Precision-Recall curve\n    \'prec_at_80_recall\': Precision at 80% recall\n    \'prec_at_90_recall\': Precision at 90% recall\nExamples:\n    >>> 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\'}]\n    >>> 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\'}]\n    >>> cuad_metric = datasets.load_metric("cuad")\n    >>> results = cuad_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}\n'






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







		def        lowercase       (    self				)      ->      Optional[int]:


							'''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        lowercase       (    self ,						__snake_case ,						__snake_case				)      ->      Union[str, Any]:


							'''simple docstring'''

							_snake_case       :					str				       =   {prediction["id"]: prediction["prediction_text"] for prediction in predictions}
							_snake_case       :					Union[str, Any]				       =   [
							    {
							        "paragraphs": [
							            {
							                "qas": [
							                    {
							                        "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]],
							                        "id": ref["id"],
							                    }
							                    for ref in references
							                ]
							            }
							        ]
							    }
							]
							_snake_case       :					Union[str, Any]				       =   evaluate(dataset=__snake_case ,						predictions=__snake_case				)
							return score