
"""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 		lowerCamelCase__					(					__magic_name__				):





			'''simple docstring'''



			def 					_lowerCAmelCase		(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase=False  ) ->     List[Any]:
				_lowerCAmelCase						,							_lowerCAmelCase						,							_lowerCAmelCase								=(
				    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(__UpperCAmelCase  )     ,     """wb"""  ).close()
				_lowerCAmelCase								=pa.Table.from_pydict({"""filename""": [Path(__UpperCAmelCase  ).name] * 1_00}  )
				if take == -1:
					_lowerCAmelCase								=len(__UpperCAmelCase  ) - skip
				if skip is not None and take is not None:
					_lowerCAmelCase								=pa_table.slice(__UpperCAmelCase     ,     __UpperCAmelCase  )
				return pa_table







class 		lowerCamelCase__					(					__magic_name__				):





			'''simple docstring'''



			def 					_lowerCAmelCase		(							self  ) ->     Any:
				_lowerCAmelCase								="""my_name"""
				_lowerCAmelCase								=SplitInfo(name="""train"""     ,     num_examples=1_00  )
				_lowerCAmelCase								=SplitInfo(name="""test"""     ,     num_examples=1_00  )
				_lowerCAmelCase								=[train_info, test_info]
				_lowerCAmelCase								=SplitDict()
				split_dict.add(__UpperCAmelCase  )
				split_dict.add(__UpperCAmelCase  )
				_lowerCAmelCase								=DatasetInfo(splits=__UpperCAmelCase  )

				with tempfile.TemporaryDirectory() as tmp_dir:
					_lowerCAmelCase								=ReaderTest(__UpperCAmelCase     ,     __UpperCAmelCase  )

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

					_lowerCAmelCase								=["""train""", """test[:33%]"""]
					_lowerCAmelCase								=[Split.TRAIN, ReadInstruction.from_spec("""test[:33%]"""  )]
					for instructions in [instructionsa, instructionsa]:
						_lowerCAmelCase								=[reader.read(__UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase  ) for instr in instructions]
						_lowerCAmelCase						,							_lowerCAmelCase								=(Dataset(**__UpperCAmelCase  ) for dataset_kwargs in datasets_kwargs)
						self.assertEqual(train_dset["""filename"""][0]     ,     f'''{name}-train'''  )
						self.assertEqual(train_dset.num_rows     ,     1_00  )
						self.assertEqual(train_dset.num_columns     ,     1  )
						self.assertIsInstance(train_dset.split     ,     __UpperCAmelCase  )
						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     ,     __UpperCAmelCase  )
						self.assertEqual(str(test_dset.split  )     ,     """test[:33%]"""  )
						del train_dset, test_dset



			def 					_lowerCAmelCase		(							self  ) ->     Tuple:
				_lowerCAmelCase								="""my_name"""
				_lowerCAmelCase								=SplitInfo(name="""train"""     ,     num_examples=10_00     ,     shard_lengths=[1_00] * 10  )
				_lowerCAmelCase								=[train_info]
				_lowerCAmelCase								=SplitDict()
				split_dict.add(__UpperCAmelCase  )
				_lowerCAmelCase								=DatasetInfo(splits=__UpperCAmelCase  )

				with tempfile.TemporaryDirectory() as tmp_dir:
					_lowerCAmelCase								=ReaderTest(__UpperCAmelCase     ,     __UpperCAmelCase  )

					_lowerCAmelCase								="""train[:33%]"""
					_lowerCAmelCase								=Dataset(**reader.read(__UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase  )  )
					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     ,     3_30  )
					self.assertEqual(dset.num_columns     ,     1  )



			def 					_lowerCAmelCase		(							self  ) ->     str:
				_lowerCAmelCase								=SplitInfo(name="""train"""     ,     num_examples=1_00  )
				_lowerCAmelCase								=SplitInfo(name="""test"""     ,     num_examples=1_00  )
				_lowerCAmelCase								=SplitDict()
				split_dict.add(__UpperCAmelCase  )
				split_dict.add(__UpperCAmelCase  )
				_lowerCAmelCase								=DatasetInfo(splits=__UpperCAmelCase  )

				with tempfile.TemporaryDirectory() as tmp_dir:
					_lowerCAmelCase								=ReaderTest(__UpperCAmelCase     ,     __UpperCAmelCase  )

					_lowerCAmelCase								=[
					    {"""filename""": os.path.join(__UpperCAmelCase     ,     """train"""  )},
					    {"""filename""": os.path.join(__UpperCAmelCase     ,     """test"""  ), """skip""": 10, """take""": 10},
					]
					_lowerCAmelCase								=Dataset(**reader.read_files(__UpperCAmelCase     ,     original_instructions="""train+test[10:20]"""  )  )
					self.assertEqual(dset.num_rows     ,     1_10  )
					self.assertEqual(dset.num_columns     ,     1  )
					del dset







@pytest.mark.parametrize("""in_memory"""    , [False, True]       )
def     _lowerCamelCase(__UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase       )				-> Optional[Any]:
	_lowerCAmelCase								=arrow_file
	with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase():
		_lowerCAmelCase								=ArrowReader.read_table(__UpperCamelCase    , in_memory=__UpperCamelCase       )
	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     _lowerCamelCase(__UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase       )				-> Optional[int]:
	_lowerCAmelCase								=arrow_file
	_lowerCAmelCase								=ArrowReader(""""""    , __UpperCamelCase       )
	with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase():
		_lowerCAmelCase								=reader.read_files([{"""filename""": filename}]    , in_memory=__UpperCamelCase       )
	assert dataset_kwargs.keys() == {"arrow_table", "info", "split"}
	_lowerCAmelCase								=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     _lowerCamelCase()				-> List[Any]:
	assert ReadInstruction("""train"""    , to=10    , unit="""abs"""       ).to_spec() == "train[:10]"
	assert ReadInstruction("""train"""    , from_=-80    , to=10    , unit="""%"""       ).to_spec() == "train[-80%:10%]"

	_lowerCAmelCase								="""train+test"""
	assert ReadInstruction.from_spec(__UpperCamelCase       ).to_spec() == spec_train_test

	_lowerCAmelCase								="""train[2:10]"""
	assert ReadInstruction.from_spec(__UpperCamelCase       ).to_spec() == spec_train_abs

	_lowerCAmelCase								="""train[15%:-20%]"""
	assert ReadInstruction.from_spec(__UpperCamelCase       ).to_spec() == spec_train_pct

	_lowerCAmelCase								="""train[:10%](closest)"""
	assert ReadInstruction.from_spec(__UpperCamelCase       ).to_spec() == "train[:10%]"

	_lowerCAmelCase								="""train[:10%](pct1_dropremainder)"""
	assert ReadInstruction.from_spec(__UpperCamelCase       ).to_spec() == spec_train_pct_rounding

	_lowerCAmelCase								="""train[:10%](pct1_dropremainder)+test[-10%:](pct1_dropremainder)"""
	assert ReadInstruction.from_spec(__UpperCamelCase       ).to_spec() == spec_train_test_pct_rounding



def     _lowerCamelCase()				-> Optional[int]:
	_lowerCAmelCase								="""dummy"""
	_lowerCAmelCase								=[SplitInfo(name="""train"""    , num_examples=100       )]
	_lowerCAmelCase								="""train[:33%]"""
	_lowerCAmelCase								="""arrow"""
	_lowerCAmelCase								="""prefix"""

	_lowerCAmelCase								=make_file_instructions(__UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase       )
	assert isinstance(__UpperCamelCase    , __UpperCamelCase       )
	assert file_instructions.num_examples == 33
	assert file_instructions.file_instructions == [
	    {"filename": os.path.join(__UpperCamelCase    , F'''{name}-train.arrow'''       ), "skip": 0, "take": 33}
	]

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



@pytest.mark.parametrize("""name, expected_exception"""    , [(None, TypeError), ("""""", ValueError)]       )
def     _lowerCamelCase(__UpperCamelCase    , __UpperCamelCase       )				-> Tuple:
	_lowerCAmelCase								=[SplitInfo(name="""train"""    , num_examples=100       )]
	_lowerCAmelCase								="""train"""
	_lowerCAmelCase								="""arrow"""
	_lowerCAmelCase								="""prefix_path"""
	with pytest.raises(__UpperCamelCase       ):
		_lowerCAmelCase								=make_file_instructions(__UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase    , __UpperCamelCase       )










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,
)


lowerCAmelCase_        =			"""\
@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}
}
"""

lowerCAmelCase_        =			"""
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.
"""

lowerCAmelCase_        =			"""
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 				_lowerCAmelCase			(	datasets.Metric							):


  '''simple docstring'''







  def UpperCamelCase_       (					self					:    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'							),
                    '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 UpperCamelCase_       (					self					:    Optional[Any]					, UpperCamelCase					:    List[str]					, UpperCamelCase					:    Optional[Any]					, UpperCamelCase					:    str=1.0							):


    '''simple docstring'''





    _snake_case      : Dict														=		{p['id']: p['no_answer_probability'] for p in predictions}
    _snake_case      : Dict														=		[{'paragraphs': [{'qas': references}]}]
    _snake_case      : Dict														=		{p['id']: p['prediction_text'] for p in predictions}

    _snake_case      : Optional[Any]														=		make_qid_to_has_ans(UpperCamelCase							)  # maps qid to True/False
    _snake_case      : str														=		[k for k, v in qid_to_has_ans.items() if v]
    _snake_case      : Optional[Any]														=		[k for k, v in qid_to_has_ans.items() if not v]

    _snake_case							,    _snake_case      : Union[str, Any]														=		get_raw_scores(UpperCamelCase					, UpperCamelCase							)
    _snake_case      : int														=		apply_no_ans_threshold(UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase							)
    _snake_case      : List[Any]														=		apply_no_ans_threshold(UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase							)
    _snake_case      : Optional[Any]														=		make_eval_dict(UpperCamelCase					, UpperCamelCase							)

    if has_ans_qids:
      _snake_case      : Optional[int]														=		make_eval_dict(UpperCamelCase					, UpperCamelCase					, qid_list=UpperCamelCase							)
      merge_eval(UpperCamelCase					, UpperCamelCase					, 'HasAns'							)
    if no_ans_qids:
      _snake_case      : List[str]														=		make_eval_dict(UpperCamelCase					, UpperCamelCase					, qid_list=UpperCamelCase							)
      merge_eval(UpperCamelCase					, UpperCamelCase					, 'NoAns'							)
    find_all_best_thresh(UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase							)
    return dict(UpperCamelCase							)




