






import datasets

from .evaluate import evaluate


UpperCAmelCase__				   =		"\\n@inproceedings{Rajpurkar2016SQuAD10,\n  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n  booktitle={EMNLP},\n  year={2016}\n}\n"

UpperCAmelCase__				   =		"\nThis metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).\n\nStanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by\ncrowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,\nfrom the corresponding reading passage, or the question might be unanswerable.\n"

UpperCAmelCase__				   =		"\nComputes SQuAD scores (F1 and EM).\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': the text of the answer\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 SQuAD 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\nExamples:\n\n    >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22'}]\n    >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]\n    >>> squad_metric = datasets.load_metric(\"squad\")\n    >>> results = squad_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'exact_match': 100.0, 'f1': 100.0}\n"






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,  _KWARGS_DESCRIPTION   )
class 		lowercase_					(	datasets.Metric   ):






      '''simple docstring'''




      def       __lowerCAmelCase					(      self      :						List[Any]  )    ->List[str]:




       """simple docstring"""


       return datasets.MetricInfo(
           description=_DESCRIPTION ,					citation=_CITATION ,					inputs_description=_KWARGS_DESCRIPTION ,					features=datasets.Features(
               {
                   '''predictions''': {'''id''': datasets.Value('''string'''  ), '''prediction_text''': datasets.Value('''string'''  )},
                   '''references''': {
                       '''id''': datasets.Value('''string'''  ),
                       '''answers''': datasets.features.Sequence(
                           {
                               '''text''': datasets.Value('''string'''  ),
                               '''answer_start''': datasets.Value('''int32'''  ),
                           }  ),
                   },
               }  ) ,					codebase_urls=['''https://rajpurkar.github.io/SQuAD-explorer/'''] ,					reference_urls=['''https://rajpurkar.github.io/SQuAD-explorer/'''] ,					)







      def       __lowerCAmelCase					(      self      :						str ,					__UpperCAmelCase      :						int ,					__UpperCAmelCase      :						List[Any]  )    ->Optional[int]:




       """simple docstring"""


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










import os
import unittest

from transformers import BatchEncoding
from transformers.models.bert.tokenization_bert import (
    BasicTokenizer,
    WordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer
from transformers.testing_utils import require_torch, slow

from ...test_tokenization_common import TokenizerTesterMixin






class 		lowercase_					(	lowercase ,  unittest.TestCase   ):






      '''simple docstring'''




      __snake_case       =  ProphetNetTokenizer
      __snake_case       =  False







      def       __lowerCAmelCase					(      self      :						Optional[int]  )    ->Optional[Any]:




       """simple docstring"""


       super().setUp()

       a		  =      [
           '''[UNK]''',
           '''[CLS]''',
           '''[SEP]''',
           '''[PAD]''',
           '''[MASK]''',
           '''want''',
           '''##want''',
           '''##ed''',
           '''wa''',
           '''un''',
           '''runn''',
           '''##ing''',
           ''',''',
           '''low''',
           '''lowest''',
       ]
       a		  =      os.path.join(self.tmpdirname ,					VOCAB_FILES_NAMES['''vocab_file''']  )
       with open(self.vocab_file ,					'''w''' ,					encoding='''utf-8'''  ) as vocab_writer:
        vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]  )  )







      def       __lowerCAmelCase					(      self      :						List[str] ,					__UpperCAmelCase      :						str  )    ->Dict:




       """simple docstring"""


       a		  =      '''UNwant\u00E9d,running'''
       a		  =      '''unwanted, running'''
       return input_text, output_text







      def       __lowerCAmelCase					(      self      :						Optional[int]  )    ->Optional[Any]:




       """simple docstring"""


       a		  =      self.tokenizer_class(self.vocab_file  )

       a		  =      tokenizer.tokenize('''UNwant\u00E9d,running'''  )
       self.assertListEqual(__UpperCAmelCase ,					['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing''']  )
       self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase  ) ,					[9, 6, 7, 12, 10, 11]  )







      def       __lowerCAmelCase					(      self      :						int  )    ->Any:




       """simple docstring"""


       a		  =      BasicTokenizer()

       self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz'''  ) ,					['''ah''', '''\u535A''', '''\u63A8''', '''zz''']  )







      def       __lowerCAmelCase					(      self      :						Any  )    ->int:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU?  '''  ) ,					['''hello''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
       self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  ) ,					['''hello''']  )







      def       __lowerCAmelCase					(      self      :						Union[str, Any]  )    ->Optional[int]:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase ,					strip_accents=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ) ,					['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
       self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  ) ,					['''h\u00E9llo''']  )







      def       __lowerCAmelCase					(      self      :						Dict  )    ->str:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase ,					strip_accents=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ) ,					['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
       self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  ) ,					['''hello''']  )







      def       __lowerCAmelCase					(      self      :						Any  )    ->Dict:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ) ,					['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
       self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  ) ,					['''hello''']  )







      def       __lowerCAmelCase					(      self      :						Tuple  )    ->Optional[Any]:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU?  '''  ) ,					['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']  )







      def       __lowerCAmelCase					(      self      :						Tuple  )    ->Tuple:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase ,					strip_accents=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ) ,					['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']  )







      def       __lowerCAmelCase					(      self      :						int  )    ->Optional[int]:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase ,					strip_accents=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ) ,					['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']  )







      def       __lowerCAmelCase					(      self      :						Any  )    ->int:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase ,					never_split=['''[UNK]''']  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU? [UNK]'''  ) ,					['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]''']  )







      def       __lowerCAmelCase					(      self      :						Union[str, Any]  )    ->int:




       """simple docstring"""


       a		  =      ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''']

       a		  =      {}
       for i, token in enumerate(__UpperCAmelCase  ):
        a		  =      i
       a		  =      WordpieceTokenizer(vocab=__UpperCAmelCase ,					unk_token='''[UNK]'''  )

       self.assertListEqual(tokenizer.tokenize(''''''  ) ,					[]  )

       self.assertListEqual(tokenizer.tokenize('''unwanted running'''  ) ,					['''un''', '''##want''', '''##ed''', '''runn''', '''##ing''']  )

       self.assertListEqual(tokenizer.tokenize('''unwantedX running'''  ) ,					['''[UNK]''', '''runn''', '''##ing''']  )







      @require_torch
      def       __lowerCAmelCase					(      self      :						int  )    ->int:




       """simple docstring"""


       a		  =      self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased'''  )

       a		  =      ['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
       a		  =      [1_037, 2_146, 20_423, 2_005, 7_680, 7_849, 3_989, 1_012, 102]
       a		  =      tokenizer(__UpperCAmelCase ,					padding=__UpperCAmelCase ,					return_tensors='''pt'''  )
       self.assertIsInstance(__UpperCAmelCase ,					__UpperCAmelCase  )
       a		  =      list(batch.input_ids.numpy()[0]  )
       self.assertListEqual(__UpperCAmelCase ,					__UpperCAmelCase  )

       self.assertEqual((2, 9) ,					batch.input_ids.shape  )
       self.assertEqual((2, 9) ,					batch.attention_mask.shape  )







      def       __lowerCAmelCase					(      self      :						Optional[Any]  )    ->List[str]:




       """simple docstring"""


       self.assertTrue(_is_whitespace(''' '''  )  )
       self.assertTrue(_is_whitespace('''\t'''  )  )
       self.assertTrue(_is_whitespace('''\r'''  )  )
       self.assertTrue(_is_whitespace('''\n'''  )  )
       self.assertTrue(_is_whitespace('''\u00A0'''  )  )

       self.assertFalse(_is_whitespace('''A'''  )  )
       self.assertFalse(_is_whitespace('''-'''  )  )







      def       __lowerCAmelCase					(      self      :						Any  )    ->List[str]:




       """simple docstring"""


       self.assertTrue(_is_control('''\u0005'''  )  )

       self.assertFalse(_is_control('''A'''  )  )
       self.assertFalse(_is_control(''' '''  )  )
       self.assertFalse(_is_control('''\t'''  )  )
       self.assertFalse(_is_control('''\r'''  )  )







      def       __lowerCAmelCase					(      self      :						List[Any]  )    ->List[str]:




       """simple docstring"""


       self.assertTrue(_is_punctuation('''-'''  )  )
       self.assertTrue(_is_punctuation('''$'''  )  )
       self.assertTrue(_is_punctuation('''`'''  )  )
       self.assertTrue(_is_punctuation('''.'''  )  )

       self.assertFalse(_is_punctuation('''A'''  )  )
       self.assertFalse(_is_punctuation(''' '''  )  )







      @slow
      def       __lowerCAmelCase					(      self      :						List[str]  )    ->List[str]:




       """simple docstring"""


       a		  =      self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased'''  )

       a		  =      tokenizer.encode('''sequence builders''' ,					add_special_tokens=__UpperCAmelCase  )
       a		  =      tokenizer.encode('''multi-sequence build''' ,					add_special_tokens=__UpperCAmelCase  )

       a		  =      tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase  )
       a		  =      tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase ,					__UpperCAmelCase  )

       assert encoded_sentence == text + [102]
       assert encoded_pair == text + [102] + text_a + [102]


