





'''simple docstring'''

import datasets

from .evaluate import evaluate


lowercase__		:     int			=							'\\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'

lowercase__		:     List[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'

lowercase__		:     int			=							'\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 							__lowerCAmelCase	(       datasets.Metric					):






       """simple docstring"""





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

            '''simple docstring'''




            _UpperCamelCase							       =			{prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions}
            _UpperCamelCase							       =			[
                {
                    '''paragraphs''': [
                        {
                            '''qas''': [
                                {
                                    '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']],
                                    '''id''': ref['''id'''],
                                }
                                for ref in references
                            ]
                        }
                    ]
                }
            ]
            _UpperCamelCase							       =			evaluate(dataset=lowerCAmelCase__			,					predictions=lowerCAmelCase__	)
            return score










'''simple docstring'''

from typing import List, Optional, Union

from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class 							__lowerCAmelCase	(       __magic_name__					):






       """simple docstring"""
       _snake_case      :	Dict									=       ['image_processor', 'tokenizer']
       _snake_case      :	int									=       'BlipImageProcessor'
       _snake_case      :	Tuple									=       ('BertTokenizer', 'BertTokenizerFast')





       def __init__(				self  :						Union[str, Any]			,					lowerCAmelCase__  :						List[Any]			,					lowerCAmelCase__  :						List[str]	)       ->	int:

            '''simple docstring'''




            _UpperCamelCase							       =			False
            super().__init__(lowerCAmelCase__			,					lowerCAmelCase__	)
            _UpperCamelCase							       =			self.image_processor





       def __call__(				self  :						int			,					lowerCAmelCase__  :						ImageInput = None			,					lowerCAmelCase__  :						Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None			,					lowerCAmelCase__  :						bool = True			,					lowerCAmelCase__  :						Union[bool, str, PaddingStrategy] = False			,					lowerCAmelCase__  :						Union[bool, str, TruncationStrategy] = None			,					lowerCAmelCase__  :						Optional[int] = None			,					lowerCAmelCase__  :						int = 0			,					lowerCAmelCase__  :						Optional[int] = None			,					lowerCAmelCase__  :						Optional[bool] = None			,					lowerCAmelCase__  :						bool = False			,					lowerCAmelCase__  :						bool = False			,					lowerCAmelCase__  :						bool = False			,					lowerCAmelCase__  :						bool = False			,					lowerCAmelCase__  :						bool = False			,					lowerCAmelCase__  :						bool = True			,					lowerCAmelCase__  :						Optional[Union[str, TensorType]] = None			,					**lowerCAmelCase__  :						Optional[Any]			,					)       ->	BatchEncoding:

            '''simple docstring'''




            if images is None and text is None:
                 raise ValueError('''You have to specify either images or text.'''	)

            # Get only text
            if images is None:
                 _UpperCamelCase							       =			self.tokenizer
                 _UpperCamelCase							       =			self.tokenizer(
                     text=lowerCAmelCase__			,					add_special_tokens=lowerCAmelCase__			,					padding=lowerCAmelCase__			,					truncation=lowerCAmelCase__			,					max_length=lowerCAmelCase__			,					stride=lowerCAmelCase__			,					pad_to_multiple_of=lowerCAmelCase__			,					return_attention_mask=lowerCAmelCase__			,					return_overflowing_tokens=lowerCAmelCase__			,					return_special_tokens_mask=lowerCAmelCase__			,					return_offsets_mapping=lowerCAmelCase__			,					return_token_type_ids=lowerCAmelCase__			,					return_length=lowerCAmelCase__			,					verbose=lowerCAmelCase__			,					return_tensors=lowerCAmelCase__			,					**lowerCAmelCase__			,					)
                 return text_encoding

            # add pixel_values
            _UpperCamelCase							       =			self.image_processor(lowerCAmelCase__			,					return_tensors=lowerCAmelCase__	)

            if text is not None:
                 _UpperCamelCase							       =			self.tokenizer(
                     text=lowerCAmelCase__			,					add_special_tokens=lowerCAmelCase__			,					padding=lowerCAmelCase__			,					truncation=lowerCAmelCase__			,					max_length=lowerCAmelCase__			,					stride=lowerCAmelCase__			,					pad_to_multiple_of=lowerCAmelCase__			,					return_attention_mask=lowerCAmelCase__			,					return_overflowing_tokens=lowerCAmelCase__			,					return_special_tokens_mask=lowerCAmelCase__			,					return_offsets_mapping=lowerCAmelCase__			,					return_token_type_ids=lowerCAmelCase__			,					return_length=lowerCAmelCase__			,					verbose=lowerCAmelCase__			,					return_tensors=lowerCAmelCase__			,					**lowerCAmelCase__			,					)
            else:
                 _UpperCamelCase							       =			None

            if text_encoding is not None:
                 encoding_image_processor.update(lowerCAmelCase__	)

            return encoding_image_processor





       def snake_case__		(				self  :						Any			,					*lowerCAmelCase__  :						Union[str, Any]			,					**lowerCAmelCase__  :						Dict	)       ->	List[str]:

            '''simple docstring'''




            return self.tokenizer.batch_decode(*lowerCAmelCase__			,					**lowerCAmelCase__	)





       def snake_case__		(				self  :						Tuple			,					*lowerCAmelCase__  :						int			,					**lowerCAmelCase__  :						Optional[int]	)       ->	Optional[int]:

            '''simple docstring'''




            return self.tokenizer.decode(*lowerCAmelCase__			,					**lowerCAmelCase__	)







       @property
       def snake_case__		(				self  :						Any	)       ->	str:

            '''simple docstring'''




            _UpperCamelCase							       =			self.tokenizer.model_input_names
            _UpperCamelCase							       =			self.image_processor.model_input_names
            return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names	)	)



