





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 			lowerCAmelCase_			(				UpperCamelCase_	)  ->		List[Any]:
       UpperCamelCase_ 							=	task_cls()
       UpperCamelCase_ 							=	asdict(_A	)
       UpperCamelCase_ 							=	task_template_from_dict(_A	)
       assert task == reloaded



class 				_UpperCamelCase       :

       def lowercase			(		self:			List[Any]		)							->			List[Any]:




              """simple docstring"""


              UpperCamelCase_ 							=	LanguageModeling(text_column="input_text"		)
              assert {"input_text": "text"} == task.column_mapping



       def lowercase			(		self:			Union[str, Any]		)							->			Tuple:




              """simple docstring"""


              UpperCamelCase_ 							=	Features({"text": Value("string"		)}		)
              UpperCamelCase_ 							=	{"""text_column""": """input_text"""}
              UpperCamelCase_ 							=	LanguageModeling.from_dict(UpperCAmelCase__		)
              assert "language-modeling" == task.task
              assert input_schema == task.input_schema



class 				_UpperCamelCase       (						lowerCAmelCase_  ):

       def lowercase			(		self:			Optional[Any]		)							->			Any:




              """simple docstring"""


              UpperCamelCase_ 							=	sorted(["pos", "neg"]		)

       def lowercase			(		self:			Any		)							->			List[Any]:




              """simple docstring"""


              UpperCamelCase_ 							=	TextClassification(text_column="input_text"       , label_column="input_label"		)
              self.assertDictEqual({"input_text": "text", "input_label": "labels"}       , task.column_mapping		)

       def lowercase			(		self:			List[Any]		)							->			Union[str, Any]:




              """simple docstring"""


              UpperCamelCase_ 							=	Features({"text": Value("string"		)}		)
              # Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
              UpperCamelCase_ 							=	Features({"labels": ClassLabel}		)
              UpperCamelCase_ 							=	{"""text_column""": """input_text""", """label_column""": """input_labels"""}
              UpperCamelCase_ 							=	TextClassification.from_dict(UpperCAmelCase__		)
              self.assertEqual("text-classification"       , task.task		)
              self.assertEqual(UpperCAmelCase__       , task.input_schema		)
              self.assertEqual(UpperCAmelCase__       , task.label_schema		)



       def lowercase			(		self:			str		)							->			str:




              """simple docstring"""


              UpperCamelCase_ 							=	TextClassification(text_column="input_text"       , label_column="input_label"		)
              self.assertEqual(task.label_schema["labels"]       , UpperCAmelCase__		)
              UpperCamelCase_ 							=	task.align_with_features(Features({"input_label": ClassLabel(names=self.labels		)}		)		)
              self.assertEqual(task.label_schema["labels"]       , ClassLabel(names=self.labels		)		)



class 				_UpperCamelCase       (						lowerCAmelCase_  ):

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




              """simple docstring"""


              UpperCamelCase_ 							=	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:			Optional[int]		)							->			Tuple:




              """simple docstring"""


              UpperCamelCase_ 							=	Features({"question": Value("string"		), "context": Value("string"		)}		)
              UpperCamelCase_ 							=	Features(
                  {
                      "answers": Sequence(
                          {
                              "text": Value("string"		),
                              "answer_start": Value("int32"		),
                          }		)
                  }		)
              UpperCamelCase_ 							=	{
                  """context_column""": """input_input_context""",
                  """question_column""": """input_question""",
                  """answers_column""": """input_answers""",
              }
              UpperCamelCase_ 							=	QuestionAnsweringExtractive.from_dict(UpperCAmelCase__		)
              self.assertEqual("question-answering-extractive"       , task.task		)
              self.assertEqual(UpperCAmelCase__       , task.input_schema		)
              self.assertEqual(UpperCAmelCase__       , task.label_schema		)



class 				_UpperCamelCase       (						lowerCAmelCase_  ):

       def lowercase			(		self:			Dict		)							->			List[str]:




              """simple docstring"""


              UpperCamelCase_ 							=	Summarization(text_column="input_text"       , summary_column="input_summary"		)
              self.assertDictEqual({"input_text": "text", "input_summary": "summary"}       , task.column_mapping		)



       def lowercase			(		self:			Union[str, Any]		)							->			Dict:




              """simple docstring"""


              UpperCamelCase_ 							=	Features({"text": Value("string"		)}		)
              UpperCamelCase_ 							=	Features({"summary": Value("string"		)}		)
              UpperCamelCase_ 							=	{"""text_column""": """input_text""", """summary_column""": """input_summary"""}
              UpperCamelCase_ 							=	Summarization.from_dict(UpperCAmelCase__		)
              self.assertEqual("summarization"       , task.task		)
              self.assertEqual(UpperCAmelCase__       , task.input_schema		)
              self.assertEqual(UpperCAmelCase__       , task.label_schema		)



class 				_UpperCamelCase       (						lowerCAmelCase_  ):

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




              """simple docstring"""


              UpperCamelCase_ 							=	AutomaticSpeechRecognition(audio_column="input_audio"       , transcription_column="input_transcription"		)
              self.assertDictEqual({"input_audio": "audio", "input_transcription": "transcription"}       , task.column_mapping		)



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




              """simple docstring"""


              UpperCamelCase_ 							=	Features({"audio": Audio()}		)
              UpperCamelCase_ 							=	Features({"transcription": Value("string"		)}		)
              UpperCamelCase_ 							=	{
                  """audio_column""": """input_audio""",
                  """transcription_column""": """input_transcription""",
              }
              UpperCamelCase_ 							=	AutomaticSpeechRecognition.from_dict(UpperCAmelCase__		)
              self.assertEqual("automatic-speech-recognition"       , task.task		)
              self.assertEqual(UpperCAmelCase__       , task.input_schema		)
              self.assertEqual(UpperCAmelCase__       , task.label_schema		)



class 				_UpperCamelCase       (						lowerCAmelCase_  ):

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




              """simple docstring"""


              UpperCamelCase_ 							=	sorted(["pos", "neg"]		)

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




              """simple docstring"""


              UpperCamelCase_ 							=	AudioClassification(audio_column="input_audio"       , label_column="input_label"		)
              self.assertDictEqual({"input_audio": "audio", "input_label": "labels"}       , task.column_mapping		)

       def lowercase			(		self:			Optional[Any]		)							->			Dict:




              """simple docstring"""


              UpperCamelCase_ 							=	Features({"audio": Audio()}		)
              UpperCamelCase_ 							=	Features({"labels": ClassLabel}		)
              UpperCamelCase_ 							=	{
                  """audio_column""": """input_image""",
                  """label_column""": """input_label""",
              }
              UpperCamelCase_ 							=	AudioClassification.from_dict(UpperCAmelCase__		)
              self.assertEqual("audio-classification"       , task.task		)
              self.assertEqual(UpperCAmelCase__       , task.input_schema		)
              self.assertEqual(UpperCAmelCase__       , task.label_schema		)



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




              """simple docstring"""


              UpperCamelCase_ 							=	AudioClassification(audio_column="input_audio"       , label_column="input_label"		)
              self.assertEqual(task.label_schema["labels"]       , UpperCAmelCase__		)
              UpperCamelCase_ 							=	task.align_with_features(Features({"input_label": ClassLabel(names=self.labels		)}		)		)
              self.assertEqual(task.label_schema["labels"]       , ClassLabel(names=self.labels		)		)



class 				_UpperCamelCase       (						lowerCAmelCase_  ):

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




              """simple docstring"""


              UpperCamelCase_ 							=	sorted(["pos", "neg"]		)

       def lowercase			(		self:			int		)							->			Tuple:




              """simple docstring"""


              UpperCamelCase_ 							=	ImageClassification(image_column="input_image"       , label_column="input_label"		)
              self.assertDictEqual({"input_image": "image", "input_label": "labels"}       , task.column_mapping		)

       def lowercase			(		self:			List[Any]		)							->			List[Any]:




              """simple docstring"""


              UpperCamelCase_ 							=	Features({"image": Image()}		)
              UpperCamelCase_ 							=	Features({"labels": ClassLabel}		)
              UpperCamelCase_ 							=	{
                  """image_column""": """input_image""",
                  """label_column""": """input_label""",
              }
              UpperCamelCase_ 							=	ImageClassification.from_dict(UpperCAmelCase__		)
              self.assertEqual("image-classification"       , task.task		)
              self.assertEqual(UpperCAmelCase__       , task.input_schema		)
              self.assertEqual(UpperCAmelCase__       , task.label_schema		)



       def lowercase			(		self:			int		)							->			List[Any]:




              """simple docstring"""


              UpperCamelCase_ 							=	ImageClassification(image_column="input_image"       , label_column="input_label"		)
              self.assertEqual(task.label_schema["labels"]       , UpperCAmelCase__		)
              UpperCamelCase_ 							=	task.align_with_features(Features({"input_label": ClassLabel(names=self.labels		)}		)		)
              self.assertEqual(task.label_schema["labels"]       , ClassLabel(names=self.labels		)		)



class 				_UpperCamelCase       (						lowerCAmelCase_  ):

       def lowercase			(		self:			str		)							->			List[str]:




              """simple docstring"""


              UpperCamelCase_ 							=	DatasetInfo(task_templates=QuestionAnsweringExtractive()		)
              UpperCamelCase_ 							=	Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}       , info=UpperCAmelCase__		)
              assert isinstance(dataset.info.task_templates       , UpperCAmelCase__		)
              assert len(dataset.info.task_templates		) == 1

              def keep_task(_SCREAMING_SNAKE_CASE:			Any		):
                     return x

              def dont_keep_task(_SCREAMING_SNAKE_CASE:			Union[str, Any]		):
                     UpperCamelCase_ 							=	deepcopy(UpperCAmelCase__		)
                     UpperCamelCase_ 							=	0
                     return out

              UpperCamelCase_ 							=	dataset.map(UpperCAmelCase__		)
              assert mapped_dataset.info.task_templates == dataset.info.task_templates
              # reload from cache
              UpperCamelCase_ 							=	dataset.map(UpperCAmelCase__		)
              assert mapped_dataset.info.task_templates == dataset.info.task_templates

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



       def lowercase			(		self:			str		)							->			Tuple:




              """simple docstring"""


              UpperCamelCase_ 							=	Features({"text": Value("string"		), "label": ClassLabel(names=("pos", "neg")		)}		)
              UpperCamelCase_ 							=	TextClassification(text_column="text"       , label_column="label"		)
              UpperCamelCase_ 							=	DatasetInfo(features=UpperCAmelCase__       , task_templates=UpperCAmelCase__		)
              UpperCamelCase_ 							=	Dataset.from_dict({"text": ["A sentence."], "label": ["pos"]}       , info=UpperCAmelCase__		)

              def process(_SCREAMING_SNAKE_CASE:			Tuple		):
                     return example

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




import logging
from pathlib import Path

import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only

from utils import save_json






def        __lowercase   (  _A      )  ->    Dict:
      SCREAMING_SNAKE_CASE			:   Dict	  = filter(lambda _A      : p.requires_grad    ,     model.parameters()      )
      SCREAMING_SNAKE_CASE			:   Optional[int]	  = sum([np.prod(p.size()      ) for p in model_parameters]      )
      return params


UpperCAmelCase__			:  List[Any]					     =     logging.getLogger(__name__)







class 							a__							( pl.Callback							):







  """simple docstring"""




  def 			_lowercase   (      self     :			List[Any]					,					UpperCAmelCase__     :			str					,					UpperCAmelCase__     :			Any		)       ->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   List[str]	  = {f"lr_group_{i}": param["""lr"""] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups		)}
        pl_module.logger.log_metrics(UpperCAmelCase__		)


  @rank_zero_only
  def 			_lowercase   (      self     :			List[Any]					,					UpperCAmelCase__     :			pl.Trainer					,					UpperCAmelCase__     :			pl.LightningModule					,					UpperCAmelCase__     :			str					,					UpperCAmelCase__     :			Tuple=True		)       ->None:
        """simple docstring"""







        logger.info(f"***** {type_path} results at step {trainer.global_step:05d} *****"		)
        SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = trainer.callback_metrics
        trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["""log""", """progress_bar""", """preds"""]}		)
        # Log results
        SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = Path(pl_module.hparams.output_dir		)
        if type_path == "test":
              SCREAMING_SNAKE_CASE			:   Optional[int]	  = od / """test_results.txt"""
              SCREAMING_SNAKE_CASE			:   int	  = od / """test_generations.txt"""
        else:
              # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json
              # If people want this it will be easy enough to add back.
              SCREAMING_SNAKE_CASE			:   Any	  = od / f"{type_path}_results/{trainer.global_step:05d}.txt"
              SCREAMING_SNAKE_CASE			:   int	  = od / f"{type_path}_generations/{trainer.global_step:05d}.txt"
              results_file.parent.mkdir(exist_ok=UpperCAmelCase__		)
              generations_file.parent.mkdir(exist_ok=UpperCAmelCase__		)
        with open(UpperCAmelCase__					,					"""a+"""		) as writer:
              for key in sorted(UpperCAmelCase__		):
                    if key in ["log", "progress_bar", "preds"]:
                          continue
                    SCREAMING_SNAKE_CASE			:   Optional[int]	  = metrics[key]
                    if isinstance(UpperCAmelCase__					,					torch.Tensor		):
                          SCREAMING_SNAKE_CASE			:   Optional[int]	  = val.item()
                    SCREAMING_SNAKE_CASE			:   List[str]	  = f"{key}: {val:.6f}\n"
                    writer.write(UpperCAmelCase__		)

        if not save_generations:
              return

        if "preds" in metrics:
              SCREAMING_SNAKE_CASE			:   Optional[int]	  = """\n""".join(metrics["""preds"""]		)
              generations_file.open("""w+"""		).write(UpperCAmelCase__		)


  @rank_zero_only
  def 			_lowercase   (      self     :			Optional[int]					,					UpperCAmelCase__     :			Optional[int]					,					UpperCAmelCase__     :			Union[str, Any]		)       ->int:
        """simple docstring"""







        try:
              SCREAMING_SNAKE_CASE			:   int	  = pl_module.model.model.num_parameters()
        except AttributeError:
              SCREAMING_SNAKE_CASE			:   Optional[Any]	  = pl_module.model.num_parameters()

        SCREAMING_SNAKE_CASE			:   Dict	  = count_trainable_parameters(UpperCAmelCase__		)
        # mp stands for million parameters
        trainer.logger.log_metrics({"""n_params""": npars, """mp""": npars / 1e6, """grad_mp""": n_trainable_pars / 1e6}		)


  @rank_zero_only
  def 			_lowercase   (      self     :			str					,					UpperCAmelCase__     :			pl.Trainer					,					UpperCAmelCase__     :			pl.LightningModule		)       ->Optional[int]:
        """simple docstring"""







        save_json(pl_module.metrics					,					pl_module.metrics_save_path		)
        return self._write_logs(UpperCAmelCase__					,					UpperCAmelCase__					,					"""test"""		)




  @rank_zero_only
  def 			_lowercase   (      self     :			List[Any]					,					UpperCAmelCase__     :			pl.Trainer					,					UpperCAmelCase__     :			List[Any]		)       ->Dict:
        """simple docstring"""







        save_json(pl_module.metrics					,					pl_module.metrics_save_path		)
        # Uncommenting this will save val generations
        # return self._write_logs(trainer, pl_module, "valid")






def        __lowercase   (  _A    ,     _A    ,     _A=1    ,     _A=False      )  ->    Tuple:
      if metric == "rouge2":
            SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = """{val_avg_rouge2:.4f}-{step_count}"""
      elif metric == "bleu":
            SCREAMING_SNAKE_CASE			:   Tuple	  = """{val_avg_bleu:.4f}-{step_count}"""
      elif metric == "loss":
            SCREAMING_SNAKE_CASE			:   Any	  = """{val_avg_loss:.4f}-{step_count}"""
      else:
            raise NotImplementedError(
                F"seq2seq callbacks only support rouge2, bleu and loss, got {metric}, You can make your own by adding to"
                """ this function."""      )

      SCREAMING_SNAKE_CASE			:   Tuple	  = ModelCheckpoint(
          dirpath=_A    ,     filename=_A    ,     monitor=F"val_{metric}"    ,     mode="""min""" if """loss""" in metric else """max"""    ,     save_top_k=_A    ,     )
      return checkpoint_callback







def        __lowercase   (  _A    ,     _A      )  ->    Optional[int]:
      return EarlyStopping(
          monitor=F"val_{metric}"    ,     mode="""min""" if """loss""" in metric else """max"""    ,     patience=_A    ,     verbose=_A    ,     )




