


import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


A      :    List[str]		=					logging.get_logger(__name__)

A      :    List[str]		=					{
    "microsoft/git-base": "https://huggingface.co/microsoft/git-base/resolve/main/config.json",
}







class 			_lowercase (							lowercase__):


       """simple docstring"""




       A__											=			"git_vision_model"





       def __init__(   self							:			Tuple					,      __lowerCamelCase							:			Tuple=768					,      __lowerCamelCase							:			Any=3072					,      __lowerCamelCase							:			Optional[Any]=12					,      __lowerCamelCase							:			int=12					,      __lowerCamelCase							:			Optional[Any]=3					,      __lowerCamelCase							:			Union[str, Any]=224					,      __lowerCamelCase							:			str=16					,      __lowerCamelCase							:			Union[str, Any]="quick_gelu"					,      __lowerCamelCase							:			List[Any]=1E-5					,      __lowerCamelCase							:			Optional[int]=0.0					,      __lowerCamelCase							:			Union[str, Any]=0.0_2					,      **__lowerCamelCase							:			List[str]					,      ):


             '''simple docstring'''



             super().__init__(**__lowerCamelCase       )

             lowerCamelCase__		:				List[Any]    =  hidden_size
             lowerCamelCase__		:				Any    =  intermediate_size
             lowerCamelCase__		:				Union[str, Any]    =  num_hidden_layers
             lowerCamelCase__		:				Optional[int]    =  num_attention_heads
             lowerCamelCase__		:				Dict    =  num_channels
             lowerCamelCase__		:				List[Any]    =  patch_size
             lowerCamelCase__		:				str    =  image_size
             lowerCamelCase__		:				Optional[int]    =  initializer_range
             lowerCamelCase__		:				str    =  attention_dropout
             lowerCamelCase__		:				List[Any]    =  layer_norm_eps
             lowerCamelCase__		:				Any    =  hidden_act





       @classmethod
       def 						lowerCAmelCase     (   cls							:			List[Any]					,      __lowerCamelCase							:			Union[str, os.PathLike]					,      **__lowerCamelCase							:			Optional[Any]       ):


             '''simple docstring'''



             cls._set_token_in_kwargs(__lowerCamelCase       )

             lowerCamelCase__    ,   lowerCamelCase__		:				Optional[int]    =  cls.get_config_dict(__lowerCamelCase					,      **__lowerCamelCase       )

             # get the vision config dict if we are loading from GITConfig
             if config_dict.get("model_type"       ) == "git":
                   lowerCamelCase__		:				str    =  config_dict["vision_config"]

             if "model_type" in config_dict and hasattr(cls					,      "model_type"       ) and config_dict["model_type"] != cls.model_type:
                   logger.warning(
                       f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
                       f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."       )

             return cls.from_dict(__lowerCamelCase					,      **__lowerCamelCase       )







class 			_lowercase (							lowercase__):


       """simple docstring"""




       A__											=			"git"





       def __init__(   self							:			int					,      __lowerCamelCase							:			List[str]=None					,      __lowerCamelCase							:			Dict=30522					,      __lowerCamelCase							:			List[str]=768					,      __lowerCamelCase							:			str=6					,      __lowerCamelCase							:			List[str]=12					,      __lowerCamelCase							:			int=3072					,      __lowerCamelCase							:			Dict="gelu"					,      __lowerCamelCase							:			Any=0.1					,      __lowerCamelCase							:			Tuple=0.1					,      __lowerCamelCase							:			Dict=1024					,      __lowerCamelCase							:			Optional[Any]=0.0_2					,      __lowerCamelCase							:			Dict=1E-1_2					,      __lowerCamelCase							:			Optional[int]=0					,      __lowerCamelCase							:			str="absolute"					,      __lowerCamelCase							:			Dict=True					,      __lowerCamelCase							:			Any=False					,      __lowerCamelCase							:			List[str]=101					,      __lowerCamelCase							:			int=102					,      __lowerCamelCase							:			Any=None					,      **__lowerCamelCase							:			Dict					,      ):


             '''simple docstring'''



             super().__init__(bos_token_id=__lowerCamelCase					,      eos_token_id=__lowerCamelCase					,      pad_token_id=__lowerCamelCase					,      **__lowerCamelCase       )

             if vision_config is None:
                   lowerCamelCase__		:				List[Any]    =  {}
                   logger.info("vision_config is None. initializing the GitVisionConfig with default values."       )

             lowerCamelCase__		:				Union[str, Any]    =  GitVisionConfig(**__lowerCamelCase       )
             lowerCamelCase__		:				List[Any]    =  vocab_size
             lowerCamelCase__		:				str    =  hidden_size
             lowerCamelCase__		:				int    =  num_hidden_layers
             lowerCamelCase__		:				Any    =  num_attention_heads
             lowerCamelCase__		:				List[Any]    =  hidden_act
             lowerCamelCase__		:				Optional[int]    =  intermediate_size
             lowerCamelCase__		:				Dict    =  hidden_dropout_prob
             lowerCamelCase__		:				Optional[int]    =  attention_probs_dropout_prob
             lowerCamelCase__		:				Union[str, Any]    =  max_position_embeddings
             lowerCamelCase__		:				int    =  initializer_range
             lowerCamelCase__		:				List[Any]    =  layer_norm_eps
             lowerCamelCase__		:				Optional[int]    =  position_embedding_type
             lowerCamelCase__		:				Optional[Any]    =  use_cache
             lowerCamelCase__		:				List[str]    =  tie_word_embeddings
             lowerCamelCase__		:				str    =  num_image_with_embedding

             lowerCamelCase__		:				str    =  bos_token_id
             lowerCamelCase__		:				Any    =  eos_token_id





       def 						lowerCAmelCase     (   self							:			int       ):


             '''simple docstring'''



             lowerCamelCase__		:				int    =  copy.deepcopy(self.__dict__       )
             lowerCamelCase__		:				Any    =  self.vision_config.to_dict()
             lowerCamelCase__		:				Any    =  self.__class__.model_type
             return output






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


