



"""simple docstring"""
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging


if TYPE_CHECKING:
      from ...processing_utils import ProcessorMixin
      from ...utils import TensorType


A:   Optional[int]								=		logging.get_logger(__name__)

A:   Optional[int]								=		{
    "microsoft/layoutlmv3-base": "https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json",
}



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):
   __lowerCAmelCase  :   Optional[Any]						=						'layoutlmv3'

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE=50265      ,     _SCREAMING_SNAKE_CASE=768      ,     _SCREAMING_SNAKE_CASE=12      ,     _SCREAMING_SNAKE_CASE=12      ,     _SCREAMING_SNAKE_CASE=3072      ,     _SCREAMING_SNAKE_CASE="gelu"      ,     _SCREAMING_SNAKE_CASE=0.1      ,     _SCREAMING_SNAKE_CASE=0.1      ,     _SCREAMING_SNAKE_CASE=512      ,     _SCREAMING_SNAKE_CASE=2      ,     _SCREAMING_SNAKE_CASE=0.02      ,     _SCREAMING_SNAKE_CASE=1E-5      ,     _SCREAMING_SNAKE_CASE=1      ,     _SCREAMING_SNAKE_CASE=0      ,     _SCREAMING_SNAKE_CASE=2      ,     _SCREAMING_SNAKE_CASE=1024      ,     _SCREAMING_SNAKE_CASE=128      ,     _SCREAMING_SNAKE_CASE=128      ,     _SCREAMING_SNAKE_CASE=True      ,     _SCREAMING_SNAKE_CASE=32      ,     _SCREAMING_SNAKE_CASE=128      ,     _SCREAMING_SNAKE_CASE=64      ,     _SCREAMING_SNAKE_CASE=256      ,     _SCREAMING_SNAKE_CASE=True      ,     _SCREAMING_SNAKE_CASE=True      ,     _SCREAMING_SNAKE_CASE=True      ,     _SCREAMING_SNAKE_CASE=224      ,     _SCREAMING_SNAKE_CASE=3      ,     _SCREAMING_SNAKE_CASE=16      ,     _SCREAMING_SNAKE_CASE=None      ,     **_SCREAMING_SNAKE_CASE      ,     )  ->      List[str]:





    '''simple docstring'''




    super().__init__(
        vocab_size=_SCREAMING_SNAKE_CASE      ,     hidden_size=_SCREAMING_SNAKE_CASE      ,     num_hidden_layers=_SCREAMING_SNAKE_CASE      ,     num_attention_heads=_SCREAMING_SNAKE_CASE      ,     intermediate_size=_SCREAMING_SNAKE_CASE      ,     hidden_act=_SCREAMING_SNAKE_CASE      ,     hidden_dropout_prob=_SCREAMING_SNAKE_CASE      ,     attention_probs_dropout_prob=_SCREAMING_SNAKE_CASE      ,     max_position_embeddings=_SCREAMING_SNAKE_CASE      ,     type_vocab_size=_SCREAMING_SNAKE_CASE      ,     initializer_range=_SCREAMING_SNAKE_CASE      ,     layer_norm_eps=_SCREAMING_SNAKE_CASE      ,     pad_token_id=_SCREAMING_SNAKE_CASE      ,     bos_token_id=_SCREAMING_SNAKE_CASE      ,     eos_token_id=_SCREAMING_SNAKE_CASE      ,     **_SCREAMING_SNAKE_CASE      ,     )
    UpperCAmelCase	:					Dict	=	max_ad_position_embeddings
    UpperCAmelCase	:					Union[str, Any]	=	coordinate_size
    UpperCAmelCase	:					str	=	shape_size
    UpperCAmelCase	:					Dict	=	has_relative_attention_bias
    UpperCAmelCase	:					List[Any]	=	rel_pos_bins
    UpperCAmelCase	:					List[Any]	=	max_rel_pos
    UpperCAmelCase	:					Any	=	has_spatial_attention_bias
    UpperCAmelCase	:					Union[str, Any]	=	rel_ad_pos_bins
    UpperCAmelCase	:					Optional[int]	=	max_rel_ad_pos
    UpperCAmelCase	:					List[Any]	=	text_embed
    UpperCAmelCase	:					List[Any]	=	visual_embed
    UpperCAmelCase	:					Union[str, Any]	=	input_size
    UpperCAmelCase	:					Dict	=	num_channels
    UpperCAmelCase	:					Dict	=	patch_size
    UpperCAmelCase	:					str	=	classifier_dropout



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):
   __lowerCAmelCase  :   int						=						version.parse('1.12' )

   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      Mapping[str, Mapping[int, str]]:





    '''simple docstring'''




    if self.task in ["question-answering", "sequence-classification"]:
     return OrderedDict(
         [
             ("""input_ids""", {0: """batch""", 1: """sequence"""}),
             ("""attention_mask""", {0: """batch""", 1: """sequence"""}),
             ("""bbox""", {0: """batch""", 1: """sequence"""}),
             ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
         ]						)
    else:
     return OrderedDict(
         [
             ("""input_ids""", {0: """batch""", 1: """sequence"""}),
             ("""bbox""", {0: """batch""", 1: """sequence"""}),
             ("""attention_mask""", {0: """batch""", 1: """sequence"""}),
             ("""pixel_values""", {0: """batch""", 1: """num_channels"""}),
         ]						)

   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      float:





    '''simple docstring'''




    return 1E-5

   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      int:





    '''simple docstring'''




    return 12




   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE = -1      ,     _SCREAMING_SNAKE_CASE = -1      ,     _SCREAMING_SNAKE_CASE = False      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = 3      ,     _SCREAMING_SNAKE_CASE = 40      ,     _SCREAMING_SNAKE_CASE = 40      ,     )  ->      Mapping[str, Any]:





    '''simple docstring'''




    setattr(processor.image_processor      ,     """apply_ocr"""      ,     _SCREAMING_SNAKE_CASE						)

    # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
    UpperCAmelCase	:					Tuple	=	compute_effective_axis_dimension(
        _SCREAMING_SNAKE_CASE      ,     fixed_dimension=OnnxConfig.default_fixed_batch      ,     num_token_to_add=0						)
    # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
    UpperCAmelCase	:					List[str]	=	processor.tokenizer.num_special_tokens_to_add(_SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					Union[str, Any]	=	compute_effective_axis_dimension(
        _SCREAMING_SNAKE_CASE      ,     fixed_dimension=OnnxConfig.default_fixed_sequence      ,     num_token_to_add=_SCREAMING_SNAKE_CASE						)
    # Generate dummy inputs according to compute batch and sequence
    UpperCAmelCase	:					Tuple	=	[[""" """.join([processor.tokenizer.unk_token]						) * seq_length]] * batch_size

    # Generate dummy bounding boxes
    UpperCAmelCase	:					Union[str, Any]	=	[[[48, 84, 73, 128]]] * batch_size

    # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
    # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
    UpperCAmelCase	:					Optional[Any]	=	self._generate_dummy_images(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					Optional[Any]	=	dict(
        processor(
            _SCREAMING_SNAKE_CASE      ,     text=_SCREAMING_SNAKE_CASE      ,     boxes=_SCREAMING_SNAKE_CASE      ,     return_tensors=_SCREAMING_SNAKE_CASE      ,     )						)

    return inputs





"""simple docstring"""
import datasets

from .evaluate import evaluate


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

A:   Optional[int]								=		"\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:   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       SCREAMING_SNAKE_CASE__  (					datasets.Metric ):

   def 	SCREAMING_SNAKE_CASE     (   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 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      Dict:





    '''simple docstring'''




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