




'''simple docstring'''






import datasets

from .evaluate import (
    apply_no_ans_threshold,
    find_all_best_thresh,
    get_raw_scores,
    make_eval_dict,
    make_qid_to_has_ans,
    merge_eval,
)


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

lowercase	:      Union[str, Any]				=       '''
This metric wrap the official scoring script for version 2 of the Stanford Question
Answering Dataset (SQuAD).

Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by
crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,
from the corresponding reading passage, or the question might be unanswerable.

SQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions
written adversarially by crowdworkers to look similar to answerable ones.
To do well on SQuAD2.0, systems must not only answer questions when possible, but also
determine when no answer is supported by the paragraph and abstain from answering.
'''

lowercase	:      int				=       '''
Computes SQuAD v2 scores (F1 and EM).
Args:
    predictions: List of triple for question-answers to score with the following elements:
        - the question-answer \'id\' field as given in the references (see below)
        - the text of the answer
        - the probability that the question has no answer
    references: List of question-answers dictionaries with the following key-values:
            - \'id\': id of the question-answer pair (see above),
            - \'answers\': a list of Dict {\'text\': text of the answer as a string}
    no_answer_threshold: float
        Probability threshold to decide that a question has no answer.
Returns:
    \'exact\': Exact match (the normalized answer exactly match the gold answer)
    \'f1\': The F-score of predicted tokens versus the gold answer
    \'total\': Number of score considered
    \'HasAns_exact\': Exact match (the normalized answer exactly match the gold answer)
    \'HasAns_f1\': The F-score of predicted tokens versus the gold answer
    \'HasAns_total\': Number of score considered
    \'NoAns_exact\': Exact match (the normalized answer exactly match the gold answer)
    \'NoAns_f1\': The F-score of predicted tokens versus the gold answer
    \'NoAns_total\': Number of score considered
    \'best_exact\': Best exact match (with varying threshold)
    \'best_exact_thresh\': No-answer probability threshold associated to the best exact match
    \'best_f1\': Best F1 (with varying threshold)
    \'best_f1_thresh\': No-answer probability threshold associated to the best F1
Examples:

    >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\', \'no_answer_probability\': 0.}]
    >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}]
    >>> squad_v2_metric = datasets.load_metric("squad_v2")
    >>> results = squad_v2_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'exact\': 100.0, \'f1\': 100.0, \'total\': 1, \'HasAns_exact\': 100.0, \'HasAns_f1\': 100.0, \'HasAns_total\': 1, \'best_exact\': 100.0, \'best_exact_thresh\': 0.0, \'best_f1\': 100.0, \'best_f1_thresh\': 0.0}
'''

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



 def    SCREAMING_SNAKE_CASE(  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.Value('''string''' ),
                        '''no_answer_probability''': datasets.Value('''float32''' ),
                    },
                    '''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    SCREAMING_SNAKE_CASE(  self   ,		A   ,		A   ,		A=1.0 ):






        '''simple docstring'''




        lowercase  :		int						=      {p['''id''']: p['''no_answer_probability'''] for p in predictions}
        lowercase  :		List[Any]						=      [{'''paragraphs''': [{'''qas''': references}]}]
        lowercase  :		Dict						=      {p['''id''']: p['''prediction_text'''] for p in predictions}

        lowercase  :		int						=      make_qid_to_has_ans(A )  # maps qid to True/False
        lowercase  :		Optional[Any]						=      [k for k, v in qid_to_has_ans.items() if v]
        lowercase  :		Dict						=      [k for k, v in qid_to_has_ans.items() if not v]

        lowercase  :		Dict						=      get_raw_scores(A   ,		A )
        lowercase  :		int						=      apply_no_ans_threshold(A   ,		A   ,		A   ,		A )
        lowercase  :		Union[str, Any]						=      apply_no_ans_threshold(A   ,		A   ,		A   ,		A )
        lowercase  :		Tuple						=      make_eval_dict(A   ,		A )

        if has_ans_qids:
               lowercase  :		Any						=      make_eval_dict(A   ,		A   ,		qid_list=A )
               merge_eval(A   ,		A   ,		'''HasAns''' )
        if no_ans_qids:
               lowercase  :		int						=      make_eval_dict(A   ,		A   ,		qid_list=A )
               merge_eval(A   ,		A   ,		'''NoAns''' )
        find_all_best_thresh(A   ,		A   ,		A   ,		A   ,		A   ,		A )
        return dict(A )










'''simple docstring'''






import os
import tempfile
from pathlib import Path
from unittest import TestCase

import pyarrow as pa
import pytest

from datasets.arrow_dataset import Dataset
from datasets.arrow_reader import ArrowReader, BaseReader, FileInstructions, ReadInstruction, make_file_instructions
from datasets.info import DatasetInfo
from datasets.splits import NamedSplit, Split, SplitDict, SplitInfo

from .utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases

class   SCREAMING_SNAKE_CASE_		(       lowerCamelCase_				):



 def    SCREAMING_SNAKE_CASE(  self   ,		A   ,		A=False ):






        '''simple docstring'''




        lowercase,     lowercase,     lowercase  :		Union[str, Any]						=      (
            filename_skip_take['''filename'''],
            filename_skip_take['''skip'''] if '''skip''' in filename_skip_take else None,
            filename_skip_take['''take'''] if '''take''' in filename_skip_take else None,
        )
        open(os.path.join(A )   ,		'''wb''' ).close()
        lowercase  :		List[Any]						=      pa.Table.from_pydict({'''filename''': [Path(A ).name] * 100} )
        if take == -1:
               lowercase  :		int						=      len(A ) - skip
        if skip is not None and take is not None:
               lowercase  :		Optional[Any]						=      pa_table.slice(A   ,		A )
        return pa_table






class   SCREAMING_SNAKE_CASE_		(       lowerCamelCase_				):



 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        lowercase  :		Optional[Any]						=      '''my_name'''
        lowercase  :		Tuple						=      SplitInfo(name='''train'''   ,		num_examples=100 )
        lowercase  :		Union[str, Any]						=      SplitInfo(name='''test'''   ,		num_examples=100 )
        lowercase  :		Any						=      [train_info, test_info]
        lowercase  :		Union[str, Any]						=      SplitDict()
        split_dict.add(A )
        split_dict.add(A )
        lowercase  :		List[str]						=      DatasetInfo(splits=A )

        with tempfile.TemporaryDirectory() as tmp_dir:
               lowercase  :		Union[str, Any]						=      ReaderTest(A   ,		A )

               lowercase  :		str						=      '''test[:33%]'''
               lowercase  :		List[Any]						=      Dataset(**reader.read(A   ,		A   ,		A ) )
               self.assertEqual(dset['''filename'''][0]   ,		f"""{name}-test""" )
               self.assertEqual(dset.num_rows   ,		33 )
               self.assertEqual(dset.num_columns   ,		1 )

               lowercase  :		Dict						=      ['''train''', '''test[:33%]''']
               lowercase  :		List[Any]						=      [Split.TRAIN, ReadInstruction.from_spec('''test[:33%]''' )]
               for instructions in [instructionsa, instructionsa]:
                      lowercase  :		Union[str, Any]						=      [reader.read(A   ,		A   ,		A ) for instr in instructions]
                      lowercase,     lowercase  :		Tuple						=      (Dataset(**A ) for dataset_kwargs in datasets_kwargs)
                      self.assertEqual(train_dset['''filename'''][0]   ,		f"""{name}-train""" )
                      self.assertEqual(train_dset.num_rows   ,		100 )
                      self.assertEqual(train_dset.num_columns   ,		1 )
                      self.assertIsInstance(train_dset.split   ,		A )
                      self.assertEqual(str(train_dset.split )   ,		'''train''' )
                      self.assertEqual(test_dset['''filename'''][0]   ,		f"""{name}-test""" )
                      self.assertEqual(test_dset.num_rows   ,		33 )
                      self.assertEqual(test_dset.num_columns   ,		1 )
                      self.assertIsInstance(test_dset.split   ,		A )
                      self.assertEqual(str(test_dset.split )   ,		'''test[:33%]''' )
                      del train_dset, test_dset



 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        lowercase  :		str						=      '''my_name'''
        lowercase  :		Dict						=      SplitInfo(name='''train'''   ,		num_examples=1000   ,		shard_lengths=[100] * 10 )
        lowercase  :		Tuple						=      [train_info]
        lowercase  :		str						=      SplitDict()
        split_dict.add(A )
        lowercase  :		str						=      DatasetInfo(splits=A )

        with tempfile.TemporaryDirectory() as tmp_dir:
               lowercase  :		int						=      ReaderTest(A   ,		A )

               lowercase  :		Dict						=      '''train[:33%]'''
               lowercase  :		Tuple						=      Dataset(**reader.read(A   ,		A   ,		A ) )
               self.assertEqual(dset['''filename'''][0]   ,		f"""{name}-train-00000-of-00010""" )
               self.assertEqual(dset['''filename'''][-1]   ,		f"""{name}-train-00003-of-00010""" )
               self.assertEqual(dset.num_rows   ,		330 )
               self.assertEqual(dset.num_columns   ,		1 )





 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        lowercase  :		Union[str, Any]						=      SplitInfo(name='''train'''   ,		num_examples=100 )
        lowercase  :		Dict						=      SplitInfo(name='''test'''   ,		num_examples=100 )
        lowercase  :		List[str]						=      SplitDict()
        split_dict.add(A )
        split_dict.add(A )
        lowercase  :		List[Any]						=      DatasetInfo(splits=A )

        with tempfile.TemporaryDirectory() as tmp_dir:
               lowercase  :		Optional[int]						=      ReaderTest(A   ,		A )

               lowercase  :		Optional[int]						=      [
                   {'''filename''': os.path.join(A   ,		'''train''' )},
                   {'''filename''': os.path.join(A   ,		'''test''' ), '''skip''': 10, '''take''': 10},
               ]
               lowercase  :		int						=      Dataset(**reader.read_files(A   ,		original_instructions='''train+test[10:20]''' ) )
               self.assertEqual(dset.num_rows   ,		110 )
               self.assertEqual(dset.num_columns   ,		1 )
               del dset






@pytest.mark.parametrize('''in_memory'''   ,				[False, True]      )
def 		a_( lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase      )				->Union[str, Any]:






       '''simple docstring'''




       lowercase  :		Any						=      arrow_file
       with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase():
              lowercase  :		str						=      ArrowReader.read_table(lowerCamelCase   ,				in_memory=lowerCamelCase      )
       assert table.shape == dataset.data.shape
       assert set(table.column_names      ) == set(dataset.data.column_names      )
       assert dict(table.to_pydict()      ) == dict(dataset.data.to_pydict()      )  # to_pydict returns OrderedDict




@pytest.mark.parametrize('''in_memory'''   ,				[False, True]      )
def 		a_( lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase      )				->Dict:






       '''simple docstring'''




       lowercase  :		Optional[Any]						=      arrow_file
       lowercase  :		Union[str, Any]						=      ArrowReader(''''''   ,				lowerCamelCase      )
       with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase():
              lowercase  :		List[str]						=      reader.read_files([{'''filename''': filename}]   ,				in_memory=lowerCamelCase      )
       assert dataset_kwargs.keys() == {"arrow_table", "info", "split"}
       lowercase  :		Optional[int]						=      dataset_kwargs['''arrow_table''']
       assert table.shape == dataset.data.shape
       assert set(table.column_names      ) == set(dataset.data.column_names      )
       assert dict(table.to_pydict()      ) == dict(dataset.data.to_pydict()      )  # to_pydict returns OrderedDict




def 		a_( )				->Any:






       '''simple docstring'''




       assert ReadInstruction('''train'''   ,				to=10   ,				unit='''abs'''      ).to_spec() == "train[:10]"
       assert ReadInstruction('''train'''   ,				from_=-80   ,				to=10   ,				unit='''%'''      ).to_spec() == "train[-80%:10%]"

       lowercase  :		Union[str, Any]						=      '''train+test'''
       assert ReadInstruction.from_spec(lowerCamelCase      ).to_spec() == spec_train_test

       lowercase  :		Any						=      '''train[2:10]'''
       assert ReadInstruction.from_spec(lowerCamelCase      ).to_spec() == spec_train_abs

       lowercase  :		List[str]						=      '''train[15%:-20%]'''
       assert ReadInstruction.from_spec(lowerCamelCase      ).to_spec() == spec_train_pct

       lowercase  :		Tuple						=      '''train[:10%](closest)'''
       assert ReadInstruction.from_spec(lowerCamelCase      ).to_spec() == "train[:10%]"

       lowercase  :		Any						=      '''train[:10%](pct1_dropremainder)'''
       assert ReadInstruction.from_spec(lowerCamelCase      ).to_spec() == spec_train_pct_rounding

       lowercase  :		int						=      '''train[:10%](pct1_dropremainder)+test[-10%:](pct1_dropremainder)'''
       assert ReadInstruction.from_spec(lowerCamelCase      ).to_spec() == spec_train_test_pct_rounding




def 		a_( )				->str:






       '''simple docstring'''




       lowercase  :		int						=      '''dummy'''
       lowercase  :		int						=      [SplitInfo(name='''train'''   ,				num_examples=100      )]
       lowercase  :		Union[str, Any]						=      '''train[:33%]'''
       lowercase  :		str						=      '''arrow'''
       lowercase  :		int						=      '''prefix'''

       lowercase  :		Optional[Any]						=      make_file_instructions(lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase      )
       assert isinstance(lowerCamelCase   ,				lowerCamelCase      )
       assert file_instructions.num_examples == 33
       assert file_instructions.file_instructions == [
           {"filename": os.path.join(lowerCamelCase   ,				f"""{name}-train.arrow"""      ), "skip": 0, "take": 33}
       ]

       lowercase  :		List[str]						=      [SplitInfo(name='''train'''   ,				num_examples=100   ,				shard_lengths=[10] * 10      )]
       lowercase  :		Any						=      make_file_instructions(lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase      )
       assert isinstance(lowerCamelCase   ,				lowerCamelCase      )
       assert file_instructions.num_examples == 33
       assert file_instructions.file_instructions == [
           {"filename": os.path.join(lowerCamelCase   ,				f"""{name}-train-00000-of-00010.arrow"""      ), "skip": 0, "take": -1},
           {"filename": os.path.join(lowerCamelCase   ,				f"""{name}-train-00001-of-00010.arrow"""      ), "skip": 0, "take": -1},
           {"filename": os.path.join(lowerCamelCase   ,				f"""{name}-train-00002-of-00010.arrow"""      ), "skip": 0, "take": -1},
           {"filename": os.path.join(lowerCamelCase   ,				f"""{name}-train-00003-of-00010.arrow"""      ), "skip": 0, "take": 3},
       ]





@pytest.mark.parametrize('''name, expected_exception'''   ,				[(None, TypeError), ('''''', ValueError)]      )
def 		a_( lowerCamelCase   ,				lowerCamelCase      )				->int:






       '''simple docstring'''




       lowercase  :		List[str]						=      [SplitInfo(name='''train'''   ,				num_examples=100      )]
       lowercase  :		List[Any]						=      '''train'''
       lowercase  :		Any						=      '''arrow'''
       lowercase  :		Union[str, Any]						=      '''prefix_path'''
       with pytest.raises(lowerCamelCase      ):
              lowercase  :		List[Any]						=      make_file_instructions(lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase   ,				lowerCamelCase      )




