

'''simple docstring'''





import datasets

from .evaluate import evaluate


__UpperCAmelCase    				=     '\\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'

__UpperCAmelCase    				=     '\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'

__UpperCAmelCase    				=     '\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 ):



 """simple docstring"""







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






      '''simple docstring'''




      _lowerCAmelCase   :					Union[str, Any]        =    {prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions}
      _lowerCAmelCase   :					Tuple        =    [
          {
              """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=A_     ,						predictions=A_       )
      return score









import argparse
import os

import torch

from transformers import FlavaConfig, FlavaForPreTraining
from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint







def 	_snake_case		(    SCREAMING_SNAKE_CASE				)       ->      Optional[int]:

     """simple docstring"""







     return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items()				)







def 	_snake_case		(    SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE				)       ->      Tuple:

     """simple docstring"""







     _lowerCAmelCase   :					str        =    {}

     for key, value in state_dict.items():
          if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key:
               continue

          _lowerCAmelCase   :					Union[str, Any]        =    key.replace("heads.cmd.mim_head.cls.predictions"		,							"mmm_image_head"				)
          _lowerCAmelCase   :					int        =    key.replace("heads.cmd.mlm_head.cls.predictions"		,							"mmm_text_head"				)
          _lowerCAmelCase   :					Any        =    key.replace("heads.cmd.itm_head.cls"		,							"itm_head"				)
          _lowerCAmelCase   :					Optional[Any]        =    key.replace("heads.cmd.itm_head.pooler"		,							"itm_head.pooler"				)
          _lowerCAmelCase   :					Any        =    key.replace("heads.cmd.clip_head.logit_scale"		,							"flava.logit_scale"				)
          _lowerCAmelCase   :					List[Any]        =    key.replace("heads.fairseq_mlm.cls.predictions"		,							"mlm_head"				)
          _lowerCAmelCase   :					Union[str, Any]        =    key.replace("heads.imagenet.mim_head.cls.predictions"		,							"mim_head"				)
          _lowerCAmelCase   :					Optional[int]        =    key.replace("mm_text_projection"		,							"flava.text_to_mm_projection"				)
          _lowerCAmelCase   :					int        =    key.replace("mm_image_projection"		,							"flava.image_to_mm_projection"				)
          _lowerCAmelCase   :					List[str]        =    key.replace("image_encoder.module"		,							"flava.image_model"				)
          _lowerCAmelCase   :					Optional[int]        =    key.replace("text_encoder.module"		,							"flava.text_model"				)
          _lowerCAmelCase   :					List[str]        =    key.replace("mm_encoder.module.encoder.cls_token"		,							"flava.multimodal_model.cls_token"				)
          _lowerCAmelCase   :					Dict        =    key.replace("mm_encoder.module"		,							"flava.multimodal_model"				)
          _lowerCAmelCase   :					Dict        =    key.replace("text_projection"		,							"flava.text_projection"				)
          _lowerCAmelCase   :					Optional[Any]        =    key.replace("image_projection"		,							"flava.image_projection"				)

          _lowerCAmelCase   :					List[Any]        =    value.float()

     for key, value in codebook_state_dict.items():
          _lowerCAmelCase   :					int        =    value

     return upgrade







@torch.no_grad()
def 	_snake_case		(    SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE=None				)       ->      Tuple:

     """simple docstring"""







     if config_path is not None:
          _lowerCAmelCase   :					Dict        =    FlavaConfig.from_pretrained(SCREAMING_SNAKE_CASE				)
     else:
          _lowerCAmelCase   :					Dict        =    FlavaConfig()

     _lowerCAmelCase   :					List[Any]        =    FlavaForPreTraining(SCREAMING_SNAKE_CASE				).eval()

     _lowerCAmelCase   :					Optional[int]        =    convert_dalle_checkpoint(SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE		,							save_checkpoint=SCREAMING_SNAKE_CASE				)

     if os.path.exists(SCREAMING_SNAKE_CASE				):
          _lowerCAmelCase   :					Dict        =    torch.load(SCREAMING_SNAKE_CASE		,							map_location="cpu"				)
     else:
          _lowerCAmelCase   :					Tuple        =    torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE		,							map_location="cpu"				)

     _lowerCAmelCase   :					Optional[int]        =    upgrade_state_dict(SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE				)
     hf_model.load_state_dict(SCREAMING_SNAKE_CASE				)
     _lowerCAmelCase   :					Optional[Any]        =    hf_model.state_dict()
     _lowerCAmelCase   :					Optional[Any]        =    count_parameters(SCREAMING_SNAKE_CASE				)
     _lowerCAmelCase   :					Optional[Any]        =    count_parameters(SCREAMING_SNAKE_CASE				) + count_parameters(SCREAMING_SNAKE_CASE				)

     assert torch.allclose(SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE		,							atol=1e-3				)

     hf_model.save_pretrained(SCREAMING_SNAKE_CASE				)


if __name__ == "__main__":
  __UpperCAmelCase    				=     argparse.ArgumentParser()
  parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
  parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint')
  parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint')
  parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
  __UpperCAmelCase    				=     parser.parse_args()

  convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)






