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 					SCREAMING_SNAKE_CASE_			(		lowerCAmelCase_: Tuple     ):
      snake_case_     :			str       =       task_cls()
      snake_case_     :			List[str]       =       asdict(_UpperCAmelCase     )
      snake_case_     :			List[str]       =       task_template_from_dict(_UpperCAmelCase     )
      assert task == reloaded



class 					snake_case__       :



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




         '''simple docstring'''




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



   def 					UpperCAmelCase__       (				self   :   Dict   )							->     Optional[int]:




         '''simple docstring'''




         snake_case_     :			Any       =       Features({"text": Value("string"   )}   )
         snake_case_     :			Union[str, Any]       =       {"text_column": "input_text"}
         snake_case_     :			Any       =       LanguageModeling.from_dict(SCREAMING_SNAKE_CASE_   )
         assert "language-modeling" == task.task
         assert input_schema == task.input_schema



class 					snake_case__       (				lowerCamelCase__							):



   def 					UpperCAmelCase__       (				self   :   int   )							->     int:




         '''simple docstring'''




         snake_case_     :			List[str]       =       sorted(["pos", "neg"]   )



   def 					UpperCAmelCase__       (				self   :   Dict   )							->     Dict:




         '''simple docstring'''




         snake_case_     :			Optional[Any]       =       TextClassification(text_column="input_text"			,	label_column="input_label"   )
         self.assertDictEqual({"input_text": "text", "input_label": "labels"}			,	task.column_mapping   )



   def 					UpperCAmelCase__       (				self   :   str   )							->     List[Any]:




         '''simple docstring'''




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



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




         '''simple docstring'''




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



class 					snake_case__       (				lowerCamelCase__							):



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




         '''simple docstring'''




         snake_case_     :			Tuple       =       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 					UpperCAmelCase__       (				self   :   List[str]   )							->     Union[str, Any]:




         '''simple docstring'''




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



class 					snake_case__       (				lowerCamelCase__							):



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




         '''simple docstring'''




         snake_case_     :			List[Any]       =       Summarization(text_column="input_text"			,	summary_column="input_summary"   )
         self.assertDictEqual({"input_text": "text", "input_summary": "summary"}			,	task.column_mapping   )



   def 					UpperCAmelCase__       (				self   :   Dict   )							->     Tuple:




         '''simple docstring'''




         snake_case_     :			List[Any]       =       Features({"text": Value("string"   )}   )
         snake_case_     :			Union[str, Any]       =       Features({"summary": Value("string"   )}   )
         snake_case_     :			Tuple       =       {"text_column": "input_text", "summary_column": "input_summary"}
         snake_case_     :			List[Any]       =       Summarization.from_dict(SCREAMING_SNAKE_CASE_   )
         self.assertEqual("summarization"			,	task.task   )
         self.assertEqual(SCREAMING_SNAKE_CASE_			,	task.input_schema   )
         self.assertEqual(SCREAMING_SNAKE_CASE_			,	task.label_schema   )



class 					snake_case__       (				lowerCamelCase__							):



   def 					UpperCAmelCase__       (				self   :   Tuple   )							->     List[str]:




         '''simple docstring'''




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



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




         '''simple docstring'''




         snake_case_     :			Union[str, Any]       =       Features({"audio": Audio()}   )
         snake_case_     :			Optional[int]       =       Features({"transcription": Value("string"   )}   )
         snake_case_     :			Tuple       =       {
             "audio_column": "input_audio",
             "transcription_column": "input_transcription",
         }
         snake_case_     :			List[str]       =       AutomaticSpeechRecognition.from_dict(SCREAMING_SNAKE_CASE_   )
         self.assertEqual("automatic-speech-recognition"			,	task.task   )
         self.assertEqual(SCREAMING_SNAKE_CASE_			,	task.input_schema   )
         self.assertEqual(SCREAMING_SNAKE_CASE_			,	task.label_schema   )



class 					snake_case__       (				lowerCamelCase__							):



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




         '''simple docstring'''




         snake_case_     :			List[Any]       =       sorted(["pos", "neg"]   )



   def 					UpperCAmelCase__       (				self   :   Tuple   )							->     str:




         '''simple docstring'''




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



   def 					UpperCAmelCase__       (				self   :   List[str]   )							->     Tuple:




         '''simple docstring'''




         snake_case_     :			Optional[int]       =       Features({"audio": Audio()}   )
         snake_case_     :			Optional[int]       =       Features({"labels": ClassLabel}   )
         snake_case_     :			Optional[int]       =       {
             "audio_column": "input_image",
             "label_column": "input_label",
         }
         snake_case_     :			int       =       AudioClassification.from_dict(SCREAMING_SNAKE_CASE_   )
         self.assertEqual("audio-classification"			,	task.task   )
         self.assertEqual(SCREAMING_SNAKE_CASE_			,	task.input_schema   )
         self.assertEqual(SCREAMING_SNAKE_CASE_			,	task.label_schema   )



   def 					UpperCAmelCase__       (				self   :   str   )							->     int:




         '''simple docstring'''




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



class 					snake_case__       (				lowerCamelCase__							):



   def 					UpperCAmelCase__       (				self   :   Tuple   )							->     str:




         '''simple docstring'''




         snake_case_     :			List[str]       =       sorted(["pos", "neg"]   )



   def 					UpperCAmelCase__       (				self   :   List[Any]   )							->     Dict:




         '''simple docstring'''




         snake_case_     :			Optional[int]       =       ImageClassification(image_column="input_image"			,	label_column="input_label"   )
         self.assertDictEqual({"input_image": "image", "input_label": "labels"}			,	task.column_mapping   )



   def 					UpperCAmelCase__       (				self   :   List[str]   )							->     Any:




         '''simple docstring'''




         snake_case_     :			Union[str, Any]       =       Features({"image": Image()}   )
         snake_case_     :			Optional[Any]       =       Features({"labels": ClassLabel}   )
         snake_case_     :			int       =       {
             "image_column": "input_image",
             "label_column": "input_label",
         }
         snake_case_     :			str       =       ImageClassification.from_dict(SCREAMING_SNAKE_CASE_   )
         self.assertEqual("image-classification"			,	task.task   )
         self.assertEqual(SCREAMING_SNAKE_CASE_			,	task.input_schema   )
         self.assertEqual(SCREAMING_SNAKE_CASE_			,	task.label_schema   )



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




         '''simple docstring'''




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



class 					snake_case__       (				lowerCamelCase__							):



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




         '''simple docstring'''




         snake_case_     :			Optional[Any]       =       DatasetInfo(task_templates=QuestionAnsweringExtractive()   )
         snake_case_     :			Optional[int]       =       Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}			,	info=SCREAMING_SNAKE_CASE_   )
         assert isinstance(dataset.info.task_templates			,	SCREAMING_SNAKE_CASE_   )
         assert len(dataset.info.task_templates   ) == 1

         def keep_task(A__   :   Any   ):
               return x

         def dont_keep_task(A__   :   Any   ):
               snake_case_     :			Optional[Any]       =       deepcopy(SCREAMING_SNAKE_CASE_   )
               snake_case_     :			Tuple       =       0
               return out

         snake_case_     :			Optional[int]       =       dataset.map(SCREAMING_SNAKE_CASE_   )
         assert mapped_dataset.info.task_templates == dataset.info.task_templates
         # reload from cache
         snake_case_     :			str       =       dataset.map(SCREAMING_SNAKE_CASE_   )
         assert mapped_dataset.info.task_templates == dataset.info.task_templates

         snake_case_     :			Optional[Any]       =       dataset.map(SCREAMING_SNAKE_CASE_   )
         assert mapped_dataset.info.task_templates == []
         # reload from cache
         snake_case_     :			List[Any]       =       dataset.map(SCREAMING_SNAKE_CASE_   )
         assert mapped_dataset.info.task_templates == []



   def 					UpperCAmelCase__       (				self   :   str   )							->     Optional[Any]:




         '''simple docstring'''




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

         def process(A__   :   int   ):
               return example

         snake_case_     :			int       =       dataset.remove_columns("label"   )
         snake_case_     :			Union[str, Any]       =       modified_dataset.map(SCREAMING_SNAKE_CASE_   )
         assert mapped_dataset.info.task_templates == []
import random
from typing import List, Optional, Union

import numpy as np
import torch

from ..state import AcceleratorState
from .constants import CUDA_DISTRIBUTED_TYPES
from .dataclasses import DistributedType, RNGType
from .imports import is_npu_available, is_tpu_available, is_xpu_available


if is_tpu_available(check_device=False):
     import torch_xla.core.xla_model as xm






def 					SCREAMING_SNAKE_CASE_			(		lowerCAmelCase_: int ,	lowerCAmelCase_: bool = False     ):
      if device_specific:
            seed += AcceleratorState().process_index
      random.seed(lowerCAmelCase_     )
      np.random.seed(lowerCAmelCase_     )
      torch.manual_seed(lowerCAmelCase_     )
      if is_xpu_available():
            torch.xpu.manual_seed_all(lowerCAmelCase_     )
      elif is_npu_available():
            torch.npu.manual_seed_all(lowerCAmelCase_     )
      else:
            torch.cuda.manual_seed_all(lowerCAmelCase_     )
      # ^^ safe to call this function even if cuda is not available
      if is_tpu_available():
            xm.set_rng_state(lowerCAmelCase_     )






def 					SCREAMING_SNAKE_CASE_			(		lowerCAmelCase_: Optional[RNGType] = None ,	lowerCAmelCase_: Optional[torch.Generator] = None     ):
      # Get the proper rng state
      if rng_type == RNGType.TORCH:
            snake_case_     :			List[Any]       =       torch.get_rng_state()
      elif rng_type == RNGType.CUDA:
            snake_case_     :			Dict       =       torch.cuda.get_rng_state()
      elif rng_type == RNGType.XLA:
            assert is_tpu_available(), "Can't synchronize XLA seeds on an environment without TPUs."
            snake_case_     :			Tuple       =       torch.tensor(xm.get_rng_state()     )
      elif rng_type == RNGType.NPU:
            assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs."
            snake_case_     :			List[str]       =       torch.npu.get_rng_state()
      elif rng_type == RNGType.XPU:
            assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs."
            snake_case_     :			List[str]       =       torch.xpu.get_rng_state()
      elif rng_type == RNGType.GENERATOR:
            assert generator is not None, "Need a generator to synchronize its seed."
            snake_case_     :			Optional[Any]       =       generator.get_state()

      # Broadcast the rng state from device 0 to other devices
      snake_case_     :			List[Any]       =       AcceleratorState()
      if state.distributed_type == DistributedType.TPU:
            snake_case_     :			int       =       rng_state.to(xm.xla_device()     )
            xm.collective_broadcast([rng_state]     )
            xm.mark_step()
            snake_case_     :			List[str]       =       rng_state.cpu()
      elif (
          state.distributed_type in CUDA_DISTRIBUTED_TYPES
          or state.distributed_type == DistributedType.MULTI_NPU
          or state.distributed_type == DistributedType.MULTI_XPU
      ):
            snake_case_     :			Dict       =       rng_state.to(state.device     )
            torch.distributed.broadcast(lowerCAmelCase_ ,	0     )
            snake_case_     :			Dict       =       rng_state.cpu()
      elif state.distributed_type == DistributedType.MULTI_CPU:
            torch.distributed.broadcast(lowerCAmelCase_ ,	0     )

      # Set the broadcast rng state
      if rng_type == RNGType.TORCH:
            torch.set_rng_state(lowerCAmelCase_     )
      elif rng_type == RNGType.CUDA:
            torch.cuda.set_rng_state(lowerCAmelCase_     )
      elif rng_type == RNGType.NPU:
            torch.npu.set_rng_state(lowerCAmelCase_     )
      elif rng_type == RNGType.XPU:
            torch.xpu.set_rng_state(lowerCAmelCase_     )
      elif rng_type == RNGType.XLA:
            xm.set_rng_state(rng_state.item()     )
      elif rng_type == RNGType.GENERATOR:
            generator.set_state(lowerCAmelCase_     )






def 					SCREAMING_SNAKE_CASE_			(		lowerCAmelCase_: List[Union[str, RNGType]] ,	lowerCAmelCase_: Optional[torch.Generator] = None     ):
      for rng_type in rng_types:
            synchronize_rng_state(RNGType(lowerCAmelCase_     ) ,	generator=lowerCAmelCase_     )



