




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     UpperCAmelCase_      ( self :     List[str]				)    ->						Tuple:
													"""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     UpperCAmelCase_      ( self :     Tuple				,							lowerCamelCase__ :     str				,							lowerCamelCase__ :     Any				)    ->						Dict:
													"""simple docstring"""


													__lowercase      =    {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions}
													__lowercase      =    [
													    {
													        '''paragraphs''': [
													            {
													                '''qas''': [
													                    {
													                        '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']],
													                        '''id''': ref['''id'''],
													                    }
													                    for ref in references
													                ]
													            }
													        ]
													    }
													]
													__lowercase      =    evaluate(dataset=UpperCAmelCase_				,							predictions=UpperCAmelCase_				)
													return score












import unittest

from transformers import GPTSwaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


UpperCAmelCase__				     = get_tests_dir("fixtures/test_sentencepiece_with_bytefallback.model")







@require_sentencepiece
@require_tokenizers
class a (     __SCREAMING_SNAKE_CASE       ,						unittest.TestCase  ):
						"""simple docstring"""

						UpperCamelCase_	:       List[str]       	=		GPTSwaTokenizer
						UpperCamelCase_	:       Union[str, Any]       	=		False
						UpperCamelCase_	:       Union[str, Any]       	=		True
						UpperCamelCase_	:       Optional[Any]       	=		False






						def     UpperCAmelCase_      ( self :     int				)    ->						Optional[int]:
													"""simple docstring"""


													super().setUp()

													# We have a SentencePiece fixture for testing
													__lowercase      =    GPTSwaTokenizer(lowerCamelCase__				,							eos_token='''<unk>'''				,							bos_token='''<unk>'''				,							pad_token='''<unk>'''				)

													tokenizer.save_pretrained(self.tmpdirname				)






						def     UpperCAmelCase_      ( self :     int				,							lowerCamelCase__ :     Dict				)    ->						Dict:
													"""simple docstring"""


													__lowercase      =    '''This is a test'''
													__lowercase      =    '''This is a test'''
													return input_text, output_text






						def     UpperCAmelCase_      ( self :     Optional[Any]				)    ->						Union[str, Any]:
													"""simple docstring"""


													__lowercase      =    '''<s>'''
													__lowercase      =    1

													self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase__				)				,							lowerCamelCase__				)
													self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase__				)				,							lowerCamelCase__				)






						def     UpperCAmelCase_      ( self :     Dict				)    ->						Optional[int]:
													"""simple docstring"""


													__lowercase      =    list(self.get_tokenizer().get_vocab().keys()				)

													self.assertEqual(vocab_keys[0]				,							'''<unk>'''				)
													self.assertEqual(vocab_keys[1]				,							'''<s>'''				)
													self.assertEqual(vocab_keys[-1]				,							'''j'''				)
													self.assertEqual(len(lowerCamelCase__				)				,							2_000				)






						def     UpperCAmelCase_      ( self :     Dict				)    ->						str:
													"""simple docstring"""


													self.assertEqual(self.get_tokenizer().vocab_size				,							2_000				)






						def     UpperCAmelCase_      ( self :     List[str]				)    ->						Dict:
													"""simple docstring"""


													__lowercase      =    GPTSwaTokenizer(lowerCamelCase__				)

													__lowercase      =    tokenizer.tokenize('''This is a test'''				)
													self.assertListEqual(lowerCamelCase__				,							['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']				)

													self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase__				)				,							[465, 287, 265, 631, 842]				)

													__lowercase      =    tokenizer.tokenize('''I was born in 92000, and this is falsé.'''				)
													# fmt: off
													self.assertListEqual(
													    lowerCamelCase__				,							['''▁I''', '''▁was''', '''▁bor''', '''n''', '''▁in''', '''▁''', '''<0x39>''', '''2''', '''0''', '''0''', '''0''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁f''', '''al''', '''s''', '''<0xC3>''', '''<0xA9>''', '''.''']				,							)
													# fmt: on

													__lowercase      =    tokenizer.convert_tokens_to_ids(lowerCamelCase__				)
													self.assertListEqual(
													    lowerCamelCase__				,							[262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260]				,							)

													__lowercase      =    tokenizer.convert_ids_to_tokens(lowerCamelCase__				)
													# fmt: off
													self.assertListEqual(
													    lowerCamelCase__				,							['''▁I''', '''▁was''', '''▁bor''', '''n''', '''▁in''', '''▁''', '''<0x39>''', '''2''', '''0''', '''0''', '''0''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁f''', '''al''', '''s''', '''<0xC3>''', '''<0xA9>''', '''.''']				)
													# fmt: on






						def     UpperCAmelCase_      ( self :     Tuple				)    ->						Tuple:
													"""simple docstring"""


													__lowercase      =    GPTSwaTokenizer(lowerCamelCase__				)
													__lowercase      =    ['''This is a test''', '''I was born in 92000, and this is falsé.''']
													__lowercase      =    [
													    [465, 287, 265, 631, 842],
													    [262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260],
													]

													# Test that encode_fast returns the same as tokenize + convert_tokens_to_ids
													for text, expected_ids in zip(lowerCamelCase__				,							lowerCamelCase__				):
																				self.assertListEqual(tokenizer.encode_fast(lowerCamelCase__				)				,							lowerCamelCase__				)

													# Test that decode_fast returns the input text
													for text, token_ids in zip(lowerCamelCase__				,							lowerCamelCase__				):
																				self.assertEqual(tokenizer.decode_fast(lowerCamelCase__				)				,							lowerCamelCase__				)






						@slow
						def     UpperCAmelCase_      ( self :     List[str]				)    ->						int:
													"""simple docstring"""


													__lowercase      =    [
													    '''<|python|>def fibonacci(n)\n    if n < 0:\n        print(\'Incorrect input\')''',
													    '''Hey there, how are you doing this fine day?''',
													    '''This is a text with a trailing spaces followed by a dot     .''',
													    '''Häj sväjs lillebrör! =)''',
													    '''Det är inget fel på Mr. Cool''',
													]

													# fmt: off
													__lowercase      =    {'''input_ids''': [[63_423, 5, 6_811, 14_954, 282, 816, 3_821, 63_466, 63_425, 63_462, 18, 63_978, 678, 301, 1_320, 63_423, 63_455, 63_458, 18, 63_982, 4_246, 3_940, 1_901, 47_789, 5_547, 18_994], [19_630, 1_100, 63_446, 1_342, 633, 544, 4_488, 593, 5_102, 2_416, 63_495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_652, 428, 268, 1_936, 515, 268, 58_593, 22_413, 9_106, 546, 268, 33_213, 63_979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55_130, 63_450, 924, 63_449, 2_249, 4_062, 1_558, 318, 63_504, 21_498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2_827, 2_559, 332, 6_575, 63_443, 26_801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}
													# fmt: on
													self.tokenizer_integration_test_util(
													    expected_encoding=lowerCamelCase__				,							model_name='''AI-Sweden/gpt-sw3-126m'''				,							sequences=lowerCamelCase__				,							)






