


"""simple docstring"""







import datasets

from .evaluate import evaluate


lowerCAmelCase__      				=   '''\
@article{hendrycks2021cuad,
      title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},
      author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},
      journal={arXiv preprint arXiv:2103.06268},
      year={2021}
}
'''

lowerCAmelCase__      				=   '''
This metric wrap the official scoring script for version 1 of the Contract
Understanding Atticus Dataset (CUAD).
Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510
commercial legal contracts that have been manually labeled to identify 41 categories of important
clauses that lawyers look for when reviewing contracts in connection with corporate transactions.
'''

lowerCAmelCase__      				=   '''
Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).
Args:
    predictions: List of question-answers dictionaries with the following key-values:
        - \'id\': id of the question-answer pair as given in the references (see below)
        - \'prediction_text\': list of possible texts for the answer, as a list of strings
        depending on a threshold on the confidence probability of each prediction.
    references: List of question-answers dictionaries with the following key-values:
        - \'id\': id of the question-answer pair (see above),
        - \'answers\': a Dict in the CUAD dataset format
            {
                \'text\': list of possible texts for the answer, as a list of strings
                \'answer_start\': list of start positions for the answer, as a list of ints
            }
            Note that answer_start values are not taken into account to compute the metric.
Returns:
    \'exact_match\': Exact match (the normalized answer exactly match the gold answer)
    \'f1\': The F-score of predicted tokens versus the gold answer
    \'aupr\': Area Under the Precision-Recall curve
    \'prec_at_80_recall\': Precision at 80% recall
    \'prec_at_90_recall\': Precision at 90% recall
Examples:
    >>> 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\'}]
    >>> 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\'}]
    >>> cuad_metric = datasets.load_metric("cuad")
    >>> results = cuad_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}
'''


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,    _KWARGS_DESCRIPTION				)
class       SCREAMING_SNAKE_CASE__				(		datasets.Metric				):
       """simple docstring"""


       def        lowercase__							(						self						):






         """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        lowercase__							(						self		,     snake_case__		,     snake_case__						):






         """simple docstring"""





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








'''simple docstring'''



import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
  from PIL import Image

  from transformers import CLIPImageProcessor, CLIPProcessor







@require_vision
class 						lowerCAmelCase__   (      unittest.TestCase					):



 """simple docstring"""



 def       UpperCAmelCase__		(		self					:       Union[str, Any]			)  -> List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      tempfile.mkdtemp()

      # fmt: off
      __SCREAMING_SNAKE_CASE     =      ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""]
      # fmt: on
      __SCREAMING_SNAKE_CASE     =      dict(zip(__SCREAMING_SNAKE_CASE					,							range(len(__SCREAMING_SNAKE_CASE			)			)			)			)
      __SCREAMING_SNAKE_CASE     =      ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""]
      __SCREAMING_SNAKE_CASE     =      {"""unk_token""": """<unk>"""}

      __SCREAMING_SNAKE_CASE     =      os.path.join(self.tmpdirname					,							VOCAB_FILES_NAMES["""vocab_file"""]			)
      __SCREAMING_SNAKE_CASE     =      os.path.join(self.tmpdirname					,							VOCAB_FILES_NAMES["""merges_file"""]			)
      with open(self.vocab_file					,							"""w"""					,							encoding="""utf-8"""			) as fp:
           fp.write(json.dumps(__SCREAMING_SNAKE_CASE			) + """\n"""			)
      with open(self.merges_file					,							"""w"""					,							encoding="""utf-8"""			) as fp:
           fp.write("""\n""".join(__SCREAMING_SNAKE_CASE			)			)

      __SCREAMING_SNAKE_CASE     =      {
          """do_resize""": True,
          """size""": 20,
          """do_center_crop""": True,
          """crop_size""": 18,
          """do_normalize""": True,
          """image_mean""": [0.48145466, 0.4578275, 0.40821073],
          """image_std""": [0.26862954, 0.26130258, 0.27577711],
      }
      __SCREAMING_SNAKE_CASE     =      os.path.join(self.tmpdirname					,							__SCREAMING_SNAKE_CASE			)
      with open(self.image_processor_file					,							"""w"""					,							encoding="""utf-8"""			) as fp:
           json.dump(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       Optional[int]					,							**__SCREAMING_SNAKE_CASE					:       Optional[int]			)  -> str:


      """simple docstring"""




      return CLIPTokenizer.from_pretrained(self.tmpdirname					,							**__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       Tuple					,							**__SCREAMING_SNAKE_CASE					:       Any			)  -> int:


      """simple docstring"""




      return CLIPTokenizerFast.from_pretrained(self.tmpdirname					,							**__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       Optional[Any]					,							**__SCREAMING_SNAKE_CASE					:       Optional[int]			)  -> List[str]:


      """simple docstring"""




      return CLIPImageProcessor.from_pretrained(self.tmpdirname					,							**__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       Tuple			)  -> str:


      """simple docstring"""




      shutil.rmtree(self.tmpdirname			)
 def       UpperCAmelCase__		(		self					:       Optional[Any]			)  -> str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      [np.random.randint(255					,							size=(3, 30, 400)					,							dtype=np.uinta			)]

      __SCREAMING_SNAKE_CASE     =      [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE					,							0					,							-1			)			) for x in image_inputs]

      return image_inputs
 def       UpperCAmelCase__		(		self					:       Optional[int]			)  -> Any:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self.get_tokenizer()
      __SCREAMING_SNAKE_CASE     =      self.get_rust_tokenizer()
      __SCREAMING_SNAKE_CASE     =      self.get_image_processor()

      __SCREAMING_SNAKE_CASE     =      CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE					,							image_processor=__SCREAMING_SNAKE_CASE			)
      processor_slow.save_pretrained(self.tmpdirname			)
      __SCREAMING_SNAKE_CASE     =      CLIPProcessor.from_pretrained(self.tmpdirname					,							use_fast=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE					,							image_processor=__SCREAMING_SNAKE_CASE			)
      processor_fast.save_pretrained(self.tmpdirname			)
      __SCREAMING_SNAKE_CASE     =      CLIPProcessor.from_pretrained(self.tmpdirname			)

      self.assertEqual(processor_slow.tokenizer.get_vocab()					,							tokenizer_slow.get_vocab()			)
      self.assertEqual(processor_fast.tokenizer.get_vocab()					,							tokenizer_fast.get_vocab()			)
      self.assertEqual(tokenizer_slow.get_vocab()					,							tokenizer_fast.get_vocab()			)
      self.assertIsInstance(processor_slow.tokenizer					,							__SCREAMING_SNAKE_CASE			)
      self.assertIsInstance(processor_fast.tokenizer					,							__SCREAMING_SNAKE_CASE			)

      self.assertEqual(processor_slow.image_processor.to_json_string()					,							image_processor.to_json_string()			)
      self.assertEqual(processor_fast.image_processor.to_json_string()					,							image_processor.to_json_string()			)
      self.assertIsInstance(processor_slow.image_processor					,							__SCREAMING_SNAKE_CASE			)
      self.assertIsInstance(processor_fast.image_processor					,							__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       Optional[int]			)  -> Dict:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      CLIPProcessor(tokenizer=self.get_tokenizer()					,							image_processor=self.get_image_processor()			)
      processor.save_pretrained(self.tmpdirname			)

      __SCREAMING_SNAKE_CASE     =      self.get_tokenizer(bos_token="""(BOS)"""					,							eos_token="""(EOS)"""			)
      __SCREAMING_SNAKE_CASE     =      self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE					,							padding_value=1.0			)

      __SCREAMING_SNAKE_CASE     =      CLIPProcessor.from_pretrained(
          self.tmpdirname					,							bos_token="""(BOS)"""					,							eos_token="""(EOS)"""					,							do_normalize=__SCREAMING_SNAKE_CASE					,							padding_value=1.0			)

      self.assertEqual(processor.tokenizer.get_vocab()					,							tokenizer_add_kwargs.get_vocab()			)
      self.assertIsInstance(processor.tokenizer					,							__SCREAMING_SNAKE_CASE			)

      self.assertEqual(processor.image_processor.to_json_string()					,							image_processor_add_kwargs.to_json_string()			)
      self.assertIsInstance(processor.image_processor					,							__SCREAMING_SNAKE_CASE			)
 def       UpperCAmelCase__		(		self					:       List[str]			)  -> Dict:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self.get_image_processor()
      __SCREAMING_SNAKE_CASE     =      self.get_tokenizer()

      __SCREAMING_SNAKE_CASE     =      CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE					,							image_processor=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      self.prepare_image_inputs()

      __SCREAMING_SNAKE_CASE     =      image_processor(__SCREAMING_SNAKE_CASE					,							return_tensors="""np"""			)
      __SCREAMING_SNAKE_CASE     =      processor(images=__SCREAMING_SNAKE_CASE					,							return_tensors="""np"""			)

      for key in input_image_proc.keys():
           self.assertAlmostEqual(input_image_proc[key].sum()					,							input_processor[key].sum()					,							delta=1E-2			)
 def       UpperCAmelCase__		(		self					:       List[Any]			)  -> int:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self.get_image_processor()
      __SCREAMING_SNAKE_CASE     =      self.get_tokenizer()

      __SCREAMING_SNAKE_CASE     =      CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE					,							image_processor=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      """lower newer"""

      __SCREAMING_SNAKE_CASE     =      processor(text=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      tokenizer(__SCREAMING_SNAKE_CASE			)

      for key in encoded_tok.keys():
           self.assertListEqual(encoded_tok[key]					,							encoded_processor[key]			)
 def       UpperCAmelCase__		(		self					:       Dict			)  -> Union[str, Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self.get_image_processor()
      __SCREAMING_SNAKE_CASE     =      self.get_tokenizer()

      __SCREAMING_SNAKE_CASE     =      CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE					,							image_processor=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      """lower newer"""
      __SCREAMING_SNAKE_CASE     =      self.prepare_image_inputs()

      __SCREAMING_SNAKE_CASE     =      processor(text=__SCREAMING_SNAKE_CASE					,							images=__SCREAMING_SNAKE_CASE			)

      self.assertListEqual(list(inputs.keys()			)					,							["""input_ids""", """attention_mask""", """pixel_values"""]			)

      # test if it raises when no input is passed
      with pytest.raises(__SCREAMING_SNAKE_CASE			):
           processor()
 def       UpperCAmelCase__		(		self					:       List[str]			)  -> Union[str, Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self.get_image_processor()
      __SCREAMING_SNAKE_CASE     =      self.get_tokenizer()

      __SCREAMING_SNAKE_CASE     =      CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE					,							image_processor=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

      __SCREAMING_SNAKE_CASE     =      processor.batch_decode(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      tokenizer.batch_decode(__SCREAMING_SNAKE_CASE			)

      self.assertListEqual(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE			)


 def       UpperCAmelCase__		(		self					:       int			)  -> str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      self.get_image_processor()
      __SCREAMING_SNAKE_CASE     =      self.get_tokenizer()

      __SCREAMING_SNAKE_CASE     =      CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE					,							image_processor=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      """lower newer"""
      __SCREAMING_SNAKE_CASE     =      self.prepare_image_inputs()

      __SCREAMING_SNAKE_CASE     =      processor(text=__SCREAMING_SNAKE_CASE					,							images=__SCREAMING_SNAKE_CASE			)

      self.assertListEqual(list(inputs.keys()			)					,							processor.model_input_names			)






