






import datasets

from .evaluate import evaluate


snake_case__   :						int													=   """\
@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}
}
"""

snake_case__   :						Union[str, Any]													=   """
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.
"""

snake_case__   :						Any													=   """
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     _a							(	datasets.Metric     ):






  """simple docstring"""





  def  _UpperCAmelCase  (  self			)      ->			Optional[int]:
     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  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Dict:
     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=_UpperCAmelCase		,		predictions=_UpperCAmelCase			)
     return score













'''simple docstring'''







import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import MgpstrTokenizer
from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available


if is_torch_available():
		import torch


if is_vision_available():
		from PIL import Image

		from transformers import MgpstrProcessor, ViTImageProcessor





@require_torch
@require_vision
class 						SCREAMING_SNAKE_CASE       (       unittest.TestCase							):
			snake_case__	=					ViTImageProcessor if is_vision_available() else None






			@property
			def       SCREAMING_SNAKE_CASE   (			self   :      List[str]       )      ->      List[str]:
							return self.image_processor_tester.prepare_image_processor_dict()






			def       SCREAMING_SNAKE_CASE   (			self   :      Tuple       )      ->      Optional[int]:
							a_		:	Optional[Any]									=   (3, 32, 128)
							a_		:	Optional[Any]									=   tempfile.mkdtemp()

							# fmt: off
							a_		:	Union[str, Any]									=   ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z''']
							# fmt: on
							a_		:	List[Any]									=   dict(zip(__SCREAMING_SNAKE_CASE	,    range(len(__SCREAMING_SNAKE_CASE       )       )       )       )

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

							a_		:	Union[str, Any]									=   {
							    '''do_normalize''': False,
							    '''do_resize''': True,
							    '''image_processor_type''': '''ViTImageProcessor''',
							    '''resample''': 3,
							    '''size''': {'''height''': 32, '''width''': 128},
							}
							a_		:	Any									=   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       SCREAMING_SNAKE_CASE   (			self   :      List[Any]	,    **__SCREAMING_SNAKE_CASE   :      Union[str, Any]       )      ->      Dict:
							return MgpstrTokenizer.from_pretrained(self.tmpdirname	,    **__SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      List[str]	,    **__SCREAMING_SNAKE_CASE   :      Union[str, Any]       )      ->      List[Any]:
							return ViTImageProcessor.from_pretrained(self.tmpdirname	,    **__SCREAMING_SNAKE_CASE       )






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






			def       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      str:
							a_		:	Optional[Any]									=   np.random.randint(255	,    size=(3, 30, 400)	,    dtype=np.uinta       )

							a_		:	Optional[int]									=   Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE	,    0	,    -1       )       )

							return image_input






			def       SCREAMING_SNAKE_CASE   (			self   :      int       )      ->      int:
							a_		:	str									=   self.get_tokenizer()
							a_		:	List[Any]									=   self.get_image_processor()

							a_		:	Union[str, Any]									=   MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE	,    image_processor=__SCREAMING_SNAKE_CASE       )
							processor.save_pretrained(self.tmpdirname       )
							a_		:	Tuple									=   MgpstrProcessor.from_pretrained(self.tmpdirname	,    use_fast=__SCREAMING_SNAKE_CASE       )

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

							self.assertEqual(processor.image_processor.to_json_string()	,    image_processor.to_json_string()       )
							self.assertIsInstance(processor.image_processor	,    __SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Optional[int]       )      ->      int:
							a_		:	Any									=   self.get_tokenizer()
							a_		:	Dict									=   self.get_image_processor()

							a_		:	Optional[Any]									=   MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE	,    image_processor=__SCREAMING_SNAKE_CASE       )
							processor.save_pretrained(self.tmpdirname       )

							a_		:	str									=   self.get_tokenizer(bos_token='''(BOS)'''	,    eos_token='''(EOS)'''       )
							a_		:	str									=   self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE	,    padding_value=1.0       )

							a_		:	Optional[int]									=   MgpstrProcessor.from_pretrained(
							    self.tmpdirname	,    bos_token='''(BOS)'''	,    eos_token='''(EOS)'''	,    do_normalize=__SCREAMING_SNAKE_CASE	,    padding_value=1.0       )

							self.assertEqual(processor.char_tokenizer.get_vocab()	,    tokenizer_add_kwargs.get_vocab()       )
							self.assertIsInstance(processor.char_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       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      Optional[Any]:
							a_		:	Dict									=   self.get_image_processor()
							a_		:	Tuple									=   self.get_tokenizer()

							a_		:	Any									=   MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE	,    image_processor=__SCREAMING_SNAKE_CASE       )

							a_		:	Optional[Any]									=   self.prepare_image_inputs()

							a_		:	List[Any]									=   image_processor(__SCREAMING_SNAKE_CASE	,    return_tensors='''np'''       )
							a_		:	int									=   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       SCREAMING_SNAKE_CASE   (			self   :      str       )      ->      Optional[Any]:
							a_		:	Dict									=   self.get_image_processor()
							a_		:	List[Any]									=   self.get_tokenizer()

							a_		:	int									=   MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE	,    image_processor=__SCREAMING_SNAKE_CASE       )

							a_		:	Tuple									=   '''test'''

							a_		:	Any									=   processor(text=__SCREAMING_SNAKE_CASE       )

							a_		:	Optional[int]									=   tokenizer(__SCREAMING_SNAKE_CASE       )
							for key in encoded_tok.keys():
											self.assertListEqual(encoded_tok[key]	,    encoded_processor[key]       )






			def       SCREAMING_SNAKE_CASE   (			self   :      int       )      ->      int:
							a_		:	Union[str, Any]									=   self.get_image_processor()
							a_		:	Tuple									=   self.get_tokenizer()

							a_		:	Optional[Any]									=   MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE	,    image_processor=__SCREAMING_SNAKE_CASE       )

							a_		:	Union[str, Any]									=   '''test'''
							a_		:	str									=   self.prepare_image_inputs()

							a_		:	Tuple									=   processor(text=__SCREAMING_SNAKE_CASE	,    images=__SCREAMING_SNAKE_CASE       )

							self.assertListEqual(list(inputs.keys()       )	,    ['''pixel_values''', '''labels''']       )

							# test if it raises when no input is passed
							with pytest.raises(__SCREAMING_SNAKE_CASE       ):
											processor()






			def       SCREAMING_SNAKE_CASE   (			self   :      List[str]       )      ->      int:
							a_		:	int									=   self.get_image_processor()
							a_		:	List[Any]									=   self.get_tokenizer()

							a_		:	Dict									=   MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE	,    image_processor=__SCREAMING_SNAKE_CASE       )

							a_		:	Tuple									=   [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]]

							a_		:	List[Any]									=   processor.char_decode(__SCREAMING_SNAKE_CASE       )
							a_		:	Optional[int]									=   tokenizer.batch_decode(__SCREAMING_SNAKE_CASE       )
							a_		:	Union[str, Any]									=   [seq.replace(''' '''	,    ''''''       ) for seq in decoded_tok]

							self.assertListEqual(__SCREAMING_SNAKE_CASE	,    __SCREAMING_SNAKE_CASE       )






			def       SCREAMING_SNAKE_CASE   (			self   :      Any       )      ->      List[Any]:
							a_		:	int									=   self.get_image_processor()
							a_		:	Tuple									=   self.get_tokenizer()

							a_		:	Any									=   MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE	,    image_processor=__SCREAMING_SNAKE_CASE       )

							a_		:	Dict									=   None
							a_		:	Tuple									=   self.prepare_image_inputs()

							a_		:	Optional[int]									=   processor(text=__SCREAMING_SNAKE_CASE	,    images=__SCREAMING_SNAKE_CASE       )

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







			def       SCREAMING_SNAKE_CASE   (			self   :      Tuple       )      ->      Union[str, Any]:
							a_		:	List[str]									=   self.get_image_processor()
							a_		:	str									=   self.get_tokenizer()

							a_		:	Any									=   MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE	,    image_processor=__SCREAMING_SNAKE_CASE       )

							a_		:	str									=   torch.randn(1	,    27	,    38       )
							a_		:	int									=   torch.randn(1	,    27	,    5_0257       )
							a_		:	Union[str, Any]									=   torch.randn(1	,    27	,    3_0522       )

							a_		:	Tuple									=   processor.batch_decode([char_input, bpe_input, wp_input]       )

							self.assertListEqual(list(results.keys()       )	,    ['''generated_text''', '''scores''', '''char_preds''', '''bpe_preds''', '''wp_preds''']       )




