




from copy import deepcopy
from unittest.case import TestCase

import pytest

from datasets.arrow_dataset import Dataset
from datasets.features import Audio, ClassLabel, Features, Image, Sequence, Value
from datasets.info import DatasetInfo
from datasets.tasks import (
    AudioClassification,
    AutomaticSpeechRecognition,
    ImageClassification,
    LanguageModeling,
    QuestionAnsweringExtractive,
    Summarization,
    TextClassification,
    task_template_from_dict,
)
from datasets.utils.py_utils import asdict


UpperCamelCase__						=		{
    'id': '5733be284776f41900661182',
    'title': 'University_of_Notre_Dame',
    'context': 'Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.',
    'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?',
    'answers': {'text': ['Saint Bernadette Soubirous'], 'answer_start': [5_1_5]},
}






@pytest.mark.parametrize(
    'task_cls'		,  [
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]		,  )
def    snake_case   (				A     )				->				int:




	'''simple docstring'''


	lowerCamelCase_				:						Any				  =				task_cls()
	lowerCamelCase_				:						int				  =				asdict(A     )
	lowerCamelCase_				:						List[str]				  =				task_template_from_dict(A     )
	assert task == reloaded


class 							__SCREAMING_SNAKE_CASE				:

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						List[str]				  =				LanguageModeling(text_column='input_text'   )
						assert {"input_text": "text"} == task.column_mapping





					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Tuple				  =				Features({'text': Value('string'   )}   )
						lowerCamelCase_				:						List[str]				  =				{'text_column': 'input_text'}
						lowerCamelCase_				:						Dict				  =				LanguageModeling.from_dict(__lowercase   )
						assert "language-modeling" == task.task
						assert input_schema == task.input_schema


class 							__SCREAMING_SNAKE_CASE				(						lowerCamelCase    ):

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Optional[Any]				  =				sorted(['pos', 'neg']   )

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						List[str]				  =				TextClassification(text_column='input_text'					,			label_column='input_label'   )
						self.assertDictEqual({'input_text': 'text', 'input_label': 'labels'}					,			task.column_mapping   )

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						List[Any]				  =				Features({'text': Value('string'   )}   )
						# Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
						lowerCamelCase_				:						int				  =				Features({'labels': ClassLabel}   )
						lowerCamelCase_				:						Optional[int]				  =				{'text_column': 'input_text', 'label_column': 'input_labels'}
						lowerCamelCase_				:						Dict				  =				TextClassification.from_dict(__lowercase   )
						self.assertEqual('text-classification'					,			task.task   )
						self.assertEqual(__lowercase					,			task.input_schema   )
						self.assertEqual(__lowercase					,			task.label_schema   )





					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						List[Any]				  =				TextClassification(text_column='input_text'					,			label_column='input_label'   )
						self.assertEqual(task.label_schema['labels']					,			__lowercase   )
						lowerCamelCase_				:						Any				  =				task.align_with_features(Features({'input_label': ClassLabel(names=self.labels   )}   )   )
						self.assertEqual(task.label_schema['labels']					,			ClassLabel(names=self.labels   )   )


class 							__SCREAMING_SNAKE_CASE				(						lowerCamelCase    ):

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Any				  =				QuestionAnsweringExtractive(
						    context_column='input_context'					,			question_column='input_question'					,			answers_column='input_answers'   )
						self.assertDictEqual(
						    {'input_context': 'context', 'input_question': 'question', 'input_answers': 'answers'}					,			task.column_mapping   )





					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						List[str]				  =				Features({'question': Value('string'   ), 'context': Value('string'   )}   )
						lowerCamelCase_				:						List[Any]				  =				Features(
						    {
						        'answers': Sequence(
						            {
						                'text': Value('string'   ),
						                'answer_start': Value('int32'   ),
						            }   )
						    }   )
						lowerCamelCase_				:						Optional[Any]				  =				{
						    'context_column': 'input_input_context',
						    'question_column': 'input_question',
						    'answers_column': 'input_answers',
						}
						lowerCamelCase_				:						Dict				  =				QuestionAnsweringExtractive.from_dict(__lowercase   )
						self.assertEqual('question-answering-extractive'					,			task.task   )
						self.assertEqual(__lowercase					,			task.input_schema   )
						self.assertEqual(__lowercase					,			task.label_schema   )


class 							__SCREAMING_SNAKE_CASE				(						lowerCamelCase    ):

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Dict				  =				Summarization(text_column='input_text'					,			summary_column='input_summary'   )
						self.assertDictEqual({'input_text': 'text', 'input_summary': 'summary'}					,			task.column_mapping   )





					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Optional[int]				  =				Features({'text': Value('string'   )}   )
						lowerCamelCase_				:						List[Any]				  =				Features({'summary': Value('string'   )}   )
						lowerCamelCase_				:						Optional[Any]				  =				{'text_column': 'input_text', 'summary_column': 'input_summary'}
						lowerCamelCase_				:						List[Any]				  =				Summarization.from_dict(__lowercase   )
						self.assertEqual('summarization'					,			task.task   )
						self.assertEqual(__lowercase					,			task.input_schema   )
						self.assertEqual(__lowercase					,			task.label_schema   )


class 							__SCREAMING_SNAKE_CASE				(						lowerCamelCase    ):

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Any				  =				AutomaticSpeechRecognition(audio_column='input_audio'					,			transcription_column='input_transcription'   )
						self.assertDictEqual({'input_audio': 'audio', 'input_transcription': 'transcription'}					,			task.column_mapping   )





					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						List[Any]				  =				Features({'audio': Audio()}   )
						lowerCamelCase_				:						Any				  =				Features({'transcription': Value('string'   )}   )
						lowerCamelCase_				:						int				  =				{
						    'audio_column': 'input_audio',
						    'transcription_column': 'input_transcription',
						}
						lowerCamelCase_				:						Optional[int]				  =				AutomaticSpeechRecognition.from_dict(__lowercase   )
						self.assertEqual('automatic-speech-recognition'					,			task.task   )
						self.assertEqual(__lowercase					,			task.input_schema   )
						self.assertEqual(__lowercase					,			task.label_schema   )


class 							__SCREAMING_SNAKE_CASE				(						lowerCamelCase    ):

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						List[Any]				  =				sorted(['pos', 'neg']   )

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Optional[Any]				  =				AudioClassification(audio_column='input_audio'					,			label_column='input_label'   )
						self.assertDictEqual({'input_audio': 'audio', 'input_label': 'labels'}					,			task.column_mapping   )

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						List[str]				  =				Features({'audio': Audio()}   )
						lowerCamelCase_				:						Tuple				  =				Features({'labels': ClassLabel}   )
						lowerCamelCase_				:						List[Any]				  =				{
						    'audio_column': 'input_image',
						    'label_column': 'input_label',
						}
						lowerCamelCase_				:						List[str]				  =				AudioClassification.from_dict(__lowercase   )
						self.assertEqual('audio-classification'					,			task.task   )
						self.assertEqual(__lowercase					,			task.input_schema   )
						self.assertEqual(__lowercase					,			task.label_schema   )





					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						List[Any]				  =				AudioClassification(audio_column='input_audio'					,			label_column='input_label'   )
						self.assertEqual(task.label_schema['labels']					,			__lowercase   )
						lowerCamelCase_				:						List[str]				  =				task.align_with_features(Features({'input_label': ClassLabel(names=self.labels   )}   )   )
						self.assertEqual(task.label_schema['labels']					,			ClassLabel(names=self.labels   )   )


class 							__SCREAMING_SNAKE_CASE				(						lowerCamelCase    ):

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Any				  =				sorted(['pos', 'neg']   )

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Dict				  =				ImageClassification(image_column='input_image'					,			label_column='input_label'   )
						self.assertDictEqual({'input_image': 'image', 'input_label': 'labels'}					,			task.column_mapping   )

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						List[str]				  =				Features({'image': Image()}   )
						lowerCamelCase_				:						Tuple				  =				Features({'labels': ClassLabel}   )
						lowerCamelCase_				:						str				  =				{
						    'image_column': 'input_image',
						    'label_column': 'input_label',
						}
						lowerCamelCase_				:						Tuple				  =				ImageClassification.from_dict(__lowercase   )
						self.assertEqual('image-classification'					,			task.task   )
						self.assertEqual(__lowercase					,			task.input_schema   )
						self.assertEqual(__lowercase					,			task.label_schema   )





					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Union[str, Any]				  =				ImageClassification(image_column='input_image'					,			label_column='input_label'   )
						self.assertEqual(task.label_schema['labels']					,			__lowercase   )
						lowerCamelCase_				:						str				  =				task.align_with_features(Features({'input_label': ClassLabel(names=self.labels   )}   )   )
						self.assertEqual(task.label_schema['labels']					,			ClassLabel(names=self.labels   )   )


class 							__SCREAMING_SNAKE_CASE				(						lowerCamelCase    ):

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						List[str]				  =				DatasetInfo(task_templates=QuestionAnsweringExtractive()   )
						lowerCamelCase_				:						Tuple				  =				Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}					,			info=__lowercase   )
						assert isinstance(dataset.info.task_templates					,			__lowercase   )
						assert len(dataset.info.task_templates   ) == 1

						def keep_task(__lowercase   ):
							return x

						def dont_keep_task(__lowercase   ):
							lowerCamelCase_				:						Union[str, Any]				  =				deepcopy(__lowercase   )
							lowerCamelCase_				:						List[Any]				  =				0
							return out

						lowerCamelCase_				:						List[Any]				  =				dataset.map(__lowercase   )
						assert mapped_dataset.info.task_templates == dataset.info.task_templates
						# reload from cache
						lowerCamelCase_				:						Union[str, Any]				  =				dataset.map(__lowercase   )
						assert mapped_dataset.info.task_templates == dataset.info.task_templates

						lowerCamelCase_				:						Tuple				  =				dataset.map(__lowercase   )
						assert mapped_dataset.info.task_templates == []
						# reload from cache
						lowerCamelCase_				:						str				  =				dataset.map(__lowercase   )
						assert mapped_dataset.info.task_templates == []





					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Optional[int]				  =				Features({'text': Value('string'   ), 'label': ClassLabel(names=('pos', 'neg')   )}   )
						lowerCamelCase_				:						int				  =				TextClassification(text_column='text'					,			label_column='label'   )
						lowerCamelCase_				:						Optional[Any]				  =				DatasetInfo(features=__lowercase					,			task_templates=__lowercase   )
						lowerCamelCase_				:						Optional[int]				  =				Dataset.from_dict({'text': ['A sentence.'], 'label': ['pos']}					,			info=__lowercase   )

						def process(__lowercase   ):
							return example

						lowerCamelCase_				:						List[str]				  =				dataset.remove_columns('label'   )
						lowerCamelCase_				:						Optional[int]				  =				modified_dataset.map(__lowercase   )
						assert mapped_dataset.info.task_templates == []




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     __a     (       datasets.Metric ):
 def 						SCREAMING_SNAKE_CASE__  (  self					)   ->							Dict:




        '''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							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__=1.0					)   ->							str:




        '''simple docstring'''
        lowercase__:  int         =  {p['id']: p['no_answer_probability'] for p in predictions}
        lowercase__:  int         =  [{'paragraphs': [{'qas': references}]}]
        lowercase__:  Optional[int]         =  {p['id']: p['prediction_text'] for p in predictions}

        lowercase__:  Any         =  make_qid_to_has_ans(lowerCAmelCase__					)  # 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__     ,		lowercase__:  Dict         =  get_raw_scores(lowerCAmelCase__							,					lowerCAmelCase__					)
        lowercase__:  Optional[int]         =  apply_no_ans_threshold(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__					)
        lowercase__:  List[Any]         =  apply_no_ans_threshold(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__					)
        lowercase__:  Dict         =  make_eval_dict(lowerCAmelCase__							,					lowerCAmelCase__					)

        if has_ans_qids:
               lowercase__:  List[Any]         =  make_eval_dict(lowerCAmelCase__							,					lowerCAmelCase__							,					qid_list=lowerCAmelCase__					)
               merge_eval(lowerCAmelCase__							,					lowerCAmelCase__							,					'HasAns'					)
        if no_ans_qids:
               lowercase__:  int         =  make_eval_dict(lowerCAmelCase__							,					lowerCAmelCase__							,					qid_list=lowerCAmelCase__					)
               merge_eval(lowerCAmelCase__							,					lowerCAmelCase__							,					'NoAns'					)
        find_all_best_thresh(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__					)
        return dict(lowerCAmelCase__					)


