






import json
from typing import TYPE_CHECKING, List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging


if TYPE_CHECKING:
		from transformers.pipelines.conversational import Conversation


UpperCamelCase 				=	logging.get_logger(__name__)

UpperCamelCase 				=	{"tokenizer_file": "tokenizer.json"}

UpperCamelCase 				=	{
    "tokenizer_file": {
        "bigscience/tokenizer": "https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json",
        "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json",
        "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json",
        "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json",
        "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json",
        "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json",
        "bigscience/bloom": "https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json",
    },
}



class       __UpperCAmelCase		(lowercase__    ):
			__snake_case				:      str 						=							VOCAB_FILES_NAMES
			__snake_case				:      Any 						=							PRETRAINED_VOCAB_FILES_MAP
			__snake_case				:      int 						=							["input_ids", "attention_mask"]
			__snake_case				:      str 						=							None







			def __init__(	self:  Optional[int]      ,	UpperCAmelCase_:  int=None      ,	UpperCAmelCase_:  str=None      ,	UpperCAmelCase_:  List[Any]=None      ,	UpperCAmelCase_:  Any="<unk>"      ,	UpperCAmelCase_:  Optional[int]="<s>"      ,	UpperCAmelCase_:  List[Any]="</s>"      ,	UpperCAmelCase_:  str="<pad>"      ,	UpperCAmelCase_:  List[Any]=False      ,	UpperCAmelCase_:  Optional[Any]=False      ,	**UpperCAmelCase_:  int      ,	):







									'''simple docstring'''




									super().__init__(
									    __lowerCamelCase      ,	__lowerCamelCase      ,	tokenizer_file=__lowerCamelCase      ,	unk_token=__lowerCamelCase      ,	bos_token=__lowerCamelCase      ,	eos_token=__lowerCamelCase      ,	pad_token=__lowerCamelCase      ,	add_prefix_space=__lowerCamelCase      ,	clean_up_tokenization_spaces=__lowerCamelCase      ,	**__lowerCamelCase      ,	)
									_SCREAMING_SNAKE_CASE	      =  json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()     )
									if pre_tok_state.get("""add_prefix_space"""      ,	__lowerCamelCase     ) != add_prefix_space:
															_SCREAMING_SNAKE_CASE	      =  getattr(__lowerCamelCase      ,	pre_tok_state.pop("""type"""     )     )
															_SCREAMING_SNAKE_CASE	      =  add_prefix_space
															_SCREAMING_SNAKE_CASE	      =  pre_tok_class(**__lowerCamelCase     )

									_SCREAMING_SNAKE_CASE	      =  add_prefix_space







			def 							UpperCamelCase      (	self:  Dict      ,	*UpperCAmelCase_:  Any      ,	**UpperCAmelCase_:  Any     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  kwargs.get("""is_split_into_words"""      ,	__lowerCamelCase     )
									if not (self.add_prefix_space or not is_split_into_words):
															raise Exception(
															    F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with'
															    """ pretokenized inputs."""     )

									return super()._batch_encode_plus(*__lowerCamelCase      ,	**__lowerCamelCase     )







			def 							UpperCamelCase      (	self:  Optional[int]      ,	*UpperCAmelCase_:  Optional[Any]      ,	**UpperCAmelCase_:  List[Any]     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  kwargs.get("""is_split_into_words"""      ,	__lowerCamelCase     )

									if not (self.add_prefix_space or not is_split_into_words):
															raise Exception(
															    F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with'
															    """ pretokenized inputs."""     )

									return super()._encode_plus(*__lowerCamelCase      ,	**__lowerCamelCase     )







			def 							UpperCamelCase      (	self:  Tuple      ,	UpperCAmelCase_:  str      ,	UpperCAmelCase_:  Optional[str] = None     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  self._tokenizer.model.save(__lowerCamelCase      ,	name=__lowerCamelCase     )
									return tuple(__lowerCamelCase     )







			def 							UpperCamelCase      (	self:  Dict      ,	UpperCAmelCase_:  "Conversation"     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE	      =  []
									for is_user, text in conversation.iter_texts():
															input_ids.extend(self.encode(__lowerCamelCase      ,	add_special_tokens=__lowerCamelCase     ) + [self.eos_token_id]     )

									if len(__lowerCamelCase     ) > self.model_max_length:
															_SCREAMING_SNAKE_CASE	      =  input_ids[-self.model_max_length :]
									return input_ids





import datasets

from .evaluate import evaluate


A      :    Dict		=					"\\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"

A      :    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"

A      :    str		=					"\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 			_lowercase (							datasets.Metric):


       """simple docstring"""




       def 						lowerCAmelCase     (   self							:			Optional[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 						lowerCAmelCase     (   self							:			Union[str, Any]					,      __lowerCamelCase							:			List[str]					,      __lowerCamelCase							:			Dict       ):


             '''simple docstring'''



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


