"""simple docstring"""


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


__A       			=      {
    """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_15]},
}

@pytest.mark.parametrize(
    """task_cls"""				, [
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]				, )
def 						UpperCamelCase				(	_lowerCAmelCase   :							List[str]						):
    __a			      =						task_cls()
    __a			      =						asdict(_lowerCAmelCase						)
    __a			      =						task_template_from_dict(_lowerCAmelCase						)
    assert task == reloaded






class 					a					:



  def        lowerCAmelCase_				(		self   :    Tuple     )      -> List[Any]:
      __a			      =						LanguageModeling(text_column="""input_text"""     )
      assert {"input_text": "text"} == task.column_mapping



  def        lowerCAmelCase_				(		self   :    str     )      -> Optional[Any]:
      __a			      =						Features({"""text""": Value("""string"""     )}     )
      __a			      =						{"""text_column""": """input_text"""}
      __a			      =						LanguageModeling.from_dict(_snake_case     )
      assert "language-modeling" == task.task
      assert input_schema == task.input_schema






class 					a					(				lowerCamelCase__							):



  def        lowerCAmelCase_				(		self   :    Union[str, Any]     )      -> Optional[int]:
      __a			      =						sorted(["""pos""", """neg"""]     )



  def        lowerCAmelCase_				(		self   :    Any     )      -> Optional[int]:
      __a			      =						TextClassification(text_column="""input_text"""						,  label_column="""input_label"""     )
      self.assertDictEqual({"""input_text""": """text""", """input_label""": """labels"""}						,  task.column_mapping     )



  def        lowerCAmelCase_				(		self   :    Optional[Any]     )      -> List[str]:
      __a			      =						Features({"""text""": Value("""string"""     )}     )
      # Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
      __a			      =						Features({"""labels""": ClassLabel}     )
      __a			      =						{"""text_column""": """input_text""", """label_column""": """input_labels"""}
      __a			      =						TextClassification.from_dict(_snake_case     )
      self.assertEqual("""text-classification"""						,  task.task     )
      self.assertEqual(_snake_case						,  task.input_schema     )
      self.assertEqual(_snake_case						,  task.label_schema     )



  def        lowerCAmelCase_				(		self   :    int     )      -> Any:
      __a			      =						TextClassification(text_column="""input_text"""						,  label_column="""input_label"""     )
      self.assertEqual(task.label_schema["""labels"""]						,  _snake_case     )
      __a			      =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels     )}     )     )
      self.assertEqual(task.label_schema["""labels"""]						,  ClassLabel(names=self.labels     )     )






class 					a					(				lowerCamelCase__							):



  def        lowerCAmelCase_				(		self   :    List[Any]     )      -> Union[str, Any]:
      __a			      =						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        lowerCAmelCase_				(		self   :    Tuple     )      -> str:
      __a			      =						Features({"""question""": Value("""string"""     ), """context""": Value("""string"""     )}     )
      __a			      =						Features(
          {
              """answers""": Sequence(
                  {
                      """text""": Value("""string"""     ),
                      """answer_start""": Value("""int32"""     ),
                  }     )
          }     )
      __a			      =						{
          """context_column""": """input_input_context""",
          """question_column""": """input_question""",
          """answers_column""": """input_answers""",
      }
      __a			      =						QuestionAnsweringExtractive.from_dict(_snake_case     )
      self.assertEqual("""question-answering-extractive"""						,  task.task     )
      self.assertEqual(_snake_case						,  task.input_schema     )
      self.assertEqual(_snake_case						,  task.label_schema     )






class 					a					(				lowerCamelCase__							):



  def        lowerCAmelCase_				(		self   :    Any     )      -> str:
      __a			      =						Summarization(text_column="""input_text"""						,  summary_column="""input_summary"""     )
      self.assertDictEqual({"""input_text""": """text""", """input_summary""": """summary"""}						,  task.column_mapping     )



  def        lowerCAmelCase_				(		self   :    List[Any]     )      -> Optional[Any]:
      __a			      =						Features({"""text""": Value("""string"""     )}     )
      __a			      =						Features({"""summary""": Value("""string"""     )}     )
      __a			      =						{"""text_column""": """input_text""", """summary_column""": """input_summary"""}
      __a			      =						Summarization.from_dict(_snake_case     )
      self.assertEqual("""summarization"""						,  task.task     )
      self.assertEqual(_snake_case						,  task.input_schema     )
      self.assertEqual(_snake_case						,  task.label_schema     )






class 					a					(				lowerCamelCase__							):



  def        lowerCAmelCase_				(		self   :    Any     )      -> str:
      __a			      =						AutomaticSpeechRecognition(audio_column="""input_audio"""						,  transcription_column="""input_transcription"""     )
      self.assertDictEqual({"""input_audio""": """audio""", """input_transcription""": """transcription"""}						,  task.column_mapping     )



  def        lowerCAmelCase_				(		self   :    Tuple     )      -> Dict:
      __a			      =						Features({"""audio""": Audio()}     )
      __a			      =						Features({"""transcription""": Value("""string"""     )}     )
      __a			      =						{
          """audio_column""": """input_audio""",
          """transcription_column""": """input_transcription""",
      }
      __a			      =						AutomaticSpeechRecognition.from_dict(_snake_case     )
      self.assertEqual("""automatic-speech-recognition"""						,  task.task     )
      self.assertEqual(_snake_case						,  task.input_schema     )
      self.assertEqual(_snake_case						,  task.label_schema     )






class 					a					(				lowerCamelCase__							):



  def        lowerCAmelCase_				(		self   :    Optional[Any]     )      -> List[str]:
      __a			      =						sorted(["""pos""", """neg"""]     )



  def        lowerCAmelCase_				(		self   :    Dict     )      -> Any:
      __a			      =						AudioClassification(audio_column="""input_audio"""						,  label_column="""input_label"""     )
      self.assertDictEqual({"""input_audio""": """audio""", """input_label""": """labels"""}						,  task.column_mapping     )



  def        lowerCAmelCase_				(		self   :    Any     )      -> Any:
      __a			      =						Features({"""audio""": Audio()}     )
      __a			      =						Features({"""labels""": ClassLabel}     )
      __a			      =						{
          """audio_column""": """input_image""",
          """label_column""": """input_label""",
      }
      __a			      =						AudioClassification.from_dict(_snake_case     )
      self.assertEqual("""audio-classification"""						,  task.task     )
      self.assertEqual(_snake_case						,  task.input_schema     )
      self.assertEqual(_snake_case						,  task.label_schema     )



  def        lowerCAmelCase_				(		self   :    int     )      -> Optional[Any]:
      __a			      =						AudioClassification(audio_column="""input_audio"""						,  label_column="""input_label"""     )
      self.assertEqual(task.label_schema["""labels"""]						,  _snake_case     )
      __a			      =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels     )}     )     )
      self.assertEqual(task.label_schema["""labels"""]						,  ClassLabel(names=self.labels     )     )






class 					a					(				lowerCamelCase__							):



  def        lowerCAmelCase_				(		self   :    Optional[int]     )      -> Optional[Any]:
      __a			      =						sorted(["""pos""", """neg"""]     )



  def        lowerCAmelCase_				(		self   :    Optional[Any]     )      -> Tuple:
      __a			      =						ImageClassification(image_column="""input_image"""						,  label_column="""input_label"""     )
      self.assertDictEqual({"""input_image""": """image""", """input_label""": """labels"""}						,  task.column_mapping     )



  def        lowerCAmelCase_				(		self   :    Tuple     )      -> Any:
      __a			      =						Features({"""image""": Image()}     )
      __a			      =						Features({"""labels""": ClassLabel}     )
      __a			      =						{
          """image_column""": """input_image""",
          """label_column""": """input_label""",
      }
      __a			      =						ImageClassification.from_dict(_snake_case     )
      self.assertEqual("""image-classification"""						,  task.task     )
      self.assertEqual(_snake_case						,  task.input_schema     )
      self.assertEqual(_snake_case						,  task.label_schema     )



  def        lowerCAmelCase_				(		self   :    Any     )      -> Dict:
      __a			      =						ImageClassification(image_column="""input_image"""						,  label_column="""input_label"""     )
      self.assertEqual(task.label_schema["""labels"""]						,  _snake_case     )
      __a			      =						task.align_with_features(Features({"""input_label""": ClassLabel(names=self.labels     )}     )     )
      self.assertEqual(task.label_schema["""labels"""]						,  ClassLabel(names=self.labels     )     )






class 					a					(				lowerCamelCase__							):



  def        lowerCAmelCase_				(		self   :    Optional[int]     )      -> int:
      __a			      =						DatasetInfo(task_templates=QuestionAnsweringExtractive()     )
      __a			      =						Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}						,  info=_snake_case     )
      assert isinstance(dataset.info.task_templates						,  _snake_case     )
      assert len(dataset.info.task_templates     ) == 1

      def keep_task(lowerCamelCase_   :    str     ):
          return x

      def dont_keep_task(lowerCamelCase_   :    int     ):
          __a			      =						deepcopy(_snake_case     )
          __a			      =						0
          return out

      __a			      =						dataset.map(_snake_case     )
      assert mapped_dataset.info.task_templates == dataset.info.task_templates
      # reload from cache
      __a			      =						dataset.map(_snake_case     )
      assert mapped_dataset.info.task_templates == dataset.info.task_templates

      __a			      =						dataset.map(_snake_case     )
      assert mapped_dataset.info.task_templates == []
      # reload from cache
      __a			      =						dataset.map(_snake_case     )
      assert mapped_dataset.info.task_templates == []



  def        lowerCAmelCase_				(		self   :    int     )      -> List[str]:
      __a			      =						Features({"""text""": Value("""string"""     ), """label""": ClassLabel(names=("""pos""", """neg""")     )}     )
      __a			      =						TextClassification(text_column="""text"""						,  label_column="""label"""     )
      __a			      =						DatasetInfo(features=_snake_case						,  task_templates=_snake_case     )
      __a			      =						Dataset.from_dict({"""text""": ["""A sentence."""], """label""": ["""pos"""]}						,  info=_snake_case     )

      def process(lowerCamelCase_   :    List[Any]     ):
          return example

      __a			      =						dataset.remove_columns("""label"""     )
      __a			      =						modified_dataset.map(_snake_case     )
      assert mapped_dataset.info.task_templates == []





import argparse
import json
import re
import string
import sys
from collections import Counter


def 						_UpperCAmelCase							( snake_case     ):





					"""simple docstring"""

					def remove_articles(snake_case     ):
										return re.sub(R"""\b(a|an|the)\b"""      ,		""" """      ,		snake_case     )

					def white_space_fix(snake_case     ):
										return " ".join(text.split()     )

					def remove_punc(snake_case     ):
										_lowerCAmelCase         =       set(string.punctuation     )
										return "".join(ch for ch in text if ch not in exclude     )

					def lower(snake_case     ):
										return text.lower()

					return white_space_fix(remove_articles(remove_punc(lower(snake_case     )     )     )     )


def 						_UpperCAmelCase							( snake_case      ,		snake_case     ):





					"""simple docstring"""

					_lowerCAmelCase         =       normalize_answer(snake_case     ).split()
					_lowerCAmelCase         =       normalize_answer(snake_case     ).split()
					_lowerCAmelCase         =       Counter(snake_case     ) & Counter(snake_case     )
					_lowerCAmelCase         =       sum(common.values()     )
					if num_same == 0:
										return 0
					_lowerCAmelCase         =       1.0 * num_same / len(snake_case     )
					_lowerCAmelCase         =       1.0 * num_same / len(snake_case     )
					_lowerCAmelCase         =       (2 * precision * recall) / (precision + recall)
					return fa


def 						_UpperCAmelCase							( snake_case      ,		snake_case     ):





					"""simple docstring"""

					return normalize_answer(snake_case     ) == normalize_answer(snake_case     )


def 						_UpperCAmelCase							( snake_case      ,		snake_case      ,		snake_case     ):





					"""simple docstring"""

					_lowerCAmelCase         =       []
					for ground_truth in ground_truths:
										_lowerCAmelCase         =       metric_fn(snake_case      ,		snake_case     )
										scores_for_ground_truths.append(snake_case     )
					return max(snake_case     )


def 						_UpperCAmelCase							( snake_case      ,		snake_case     ):





					"""simple docstring"""

					_lowerCAmelCase         =       _lowerCAmelCase         =       _lowerCAmelCase         =       0
					for article in dataset:
										for paragraph in article["paragraphs"]:
															for qa in paragraph["qas"]:
																				total += 1
																				if qa["id"] not in predictions:
																									_lowerCAmelCase         =       """Unanswered question """ + qa["""id"""] + """ will receive score 0."""
																									print(snake_case      ,		file=sys.stderr     )
																									continue
																				_lowerCAmelCase         =       [x["""text"""] for x in qa["""answers"""]]
																				_lowerCAmelCase         =       predictions[qa["""id"""]]
																				exact_match += metric_max_over_ground_truths(snake_case      ,		snake_case      ,		snake_case     )
																				fa += metric_max_over_ground_truths(snake_case      ,		snake_case      ,		snake_case     )

					_lowerCAmelCase         =       100.0 * exact_match / total
					_lowerCAmelCase         =       100.0 * fa / total

					return {"exact_match": exact_match, "f1": fa}


if __name__ == "__main__":
	A__       =			"""1.1"""
	A__       =			argparse.ArgumentParser(description="""Evaluation for SQuAD """ + expected_version)
	parser.add_argument("""dataset_file""", help="""Dataset file""")
	parser.add_argument("""prediction_file""", help="""Prediction File""")
	A__       =			parser.parse_args()
	with open(args.dataset_file) as dataset_file:
		A__       =			json.load(dataset_file)
		if dataset_json["version"] != expected_version:
			print(
			    """Evaluation expects v-""" + expected_version + """, but got dataset with v-""" + dataset_json["""version"""],
			    file=sys.stderr,
			)
		A__       =			dataset_json["""data"""]
	with open(args.prediction_file) as prediction_file:
		A__       =			json.load(prediction_file)
	print(json.dumps(evaluate(dataset, predictions)))



