




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': [515]},
}







@pytest.mark.parametrize(
    '''task_cls''' ,						[
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ] ,						)
def lowerCamelCase__   (			_lowercase      ):

     '''simple docstring'''


     UpperCAmelCase_			:							Dict   =			task_cls()
     UpperCAmelCase_			:							List[Any]   =			asdict(__lowercase      )
     UpperCAmelCase_			:							int   =			task_template_from_dict(__lowercase      )
     assert task == reloaded

class   __a:






    """simple docstring"""





    def 							a__      (      self  ) ->		Union[str, Any]:
         UpperCAmelCase_			:							List[str]   =			LanguageModeling(text_column='''input_text'''  )
         assert {"input_text": "text"} == task.column_mapping





    def 							a__      (      self  ) ->		Tuple:
         UpperCAmelCase_			:							List[str]   =			Features({'''text''': Value('''string'''  )}  )
         UpperCAmelCase_			:							Union[str, Any]   =			{'''text_column''': '''input_text'''}
         UpperCAmelCase_			:							List[Any]   =			LanguageModeling.from_dict(a__  )
         assert "language-modeling" == task.task
         assert input_schema == task.input_schema


class   __a(     _UpperCamelCase   ):






    """simple docstring"""





    def 							a__      (      self  ) ->		str:
         UpperCAmelCase_			:							Union[str, Any]   =			sorted(['''pos''', '''neg''']  )





    def 							a__      (      self  ) ->		Dict:
         UpperCAmelCase_			:							List[Any]   =			TextClassification(text_column='''input_text'''   ,label_column='''input_label'''  )
         self.assertDictEqual({'''input_text''': '''text''', '''input_label''': '''labels'''}   ,task.column_mapping  )





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





    def 							a__      (      self  ) ->		Optional[Any]:
         UpperCAmelCase_			:							Tuple   =			TextClassification(text_column='''input_text'''   ,label_column='''input_label'''  )
         self.assertEqual(task.label_schema['''labels''']   ,a__  )
         UpperCAmelCase_			:							str   =			task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels  )}  )  )
         self.assertEqual(task.label_schema['''labels''']   ,ClassLabel(names=self.labels  )  )


class   __a(     _UpperCamelCase   ):






    """simple docstring"""





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


class   __a(     _UpperCamelCase   ):






    """simple docstring"""





    def 							a__      (      self  ) ->		Any:
         UpperCAmelCase_			:							Union[str, Any]   =			Summarization(text_column='''input_text'''   ,summary_column='''input_summary'''  )
         self.assertDictEqual({'''input_text''': '''text''', '''input_summary''': '''summary'''}   ,task.column_mapping  )





    def 							a__      (      self  ) ->		Optional[Any]:
         UpperCAmelCase_			:							Union[str, Any]   =			Features({'''text''': Value('''string'''  )}  )
         UpperCAmelCase_			:							List[Any]   =			Features({'''summary''': Value('''string'''  )}  )
         UpperCAmelCase_			:							str   =			{'''text_column''': '''input_text''', '''summary_column''': '''input_summary'''}
         UpperCAmelCase_			:							Optional[int]   =			Summarization.from_dict(a__  )
         self.assertEqual('''summarization'''   ,task.task  )
         self.assertEqual(a__   ,task.input_schema  )
         self.assertEqual(a__   ,task.label_schema  )


class   __a(     _UpperCamelCase   ):






    """simple docstring"""





    def 							a__      (      self  ) ->		Optional[int]:
         UpperCAmelCase_			:							Tuple   =			AutomaticSpeechRecognition(audio_column='''input_audio'''   ,transcription_column='''input_transcription'''  )
         self.assertDictEqual({'''input_audio''': '''audio''', '''input_transcription''': '''transcription'''}   ,task.column_mapping  )





    def 							a__      (      self  ) ->		Dict:
         UpperCAmelCase_			:							List[str]   =			Features({'''audio''': Audio()}  )
         UpperCAmelCase_			:							Tuple   =			Features({'''transcription''': Value('''string'''  )}  )
         UpperCAmelCase_			:							Optional[Any]   =			{
             '''audio_column''': '''input_audio''',
             '''transcription_column''': '''input_transcription''',
         }
         UpperCAmelCase_			:							Optional[Any]   =			AutomaticSpeechRecognition.from_dict(a__  )
         self.assertEqual('''automatic-speech-recognition'''   ,task.task  )
         self.assertEqual(a__   ,task.input_schema  )
         self.assertEqual(a__   ,task.label_schema  )


class   __a(     _UpperCamelCase   ):






    """simple docstring"""





    def 							a__      (      self  ) ->		Tuple:
         UpperCAmelCase_			:							Dict   =			sorted(['''pos''', '''neg''']  )





    def 							a__      (      self  ) ->		str:
         UpperCAmelCase_			:							Optional[Any]   =			AudioClassification(audio_column='''input_audio'''   ,label_column='''input_label'''  )
         self.assertDictEqual({'''input_audio''': '''audio''', '''input_label''': '''labels'''}   ,task.column_mapping  )





    def 							a__      (      self  ) ->		str:
         UpperCAmelCase_			:							Union[str, Any]   =			Features({'''audio''': Audio()}  )
         UpperCAmelCase_			:							Any   =			Features({'''labels''': ClassLabel}  )
         UpperCAmelCase_			:							List[str]   =			{
             '''audio_column''': '''input_image''',
             '''label_column''': '''input_label''',
         }
         UpperCAmelCase_			:							Dict   =			AudioClassification.from_dict(a__  )
         self.assertEqual('''audio-classification'''   ,task.task  )
         self.assertEqual(a__   ,task.input_schema  )
         self.assertEqual(a__   ,task.label_schema  )





    def 							a__      (      self  ) ->		str:
         UpperCAmelCase_			:							List[Any]   =			AudioClassification(audio_column='''input_audio'''   ,label_column='''input_label'''  )
         self.assertEqual(task.label_schema['''labels''']   ,a__  )
         UpperCAmelCase_			:							Optional[Any]   =			task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels  )}  )  )
         self.assertEqual(task.label_schema['''labels''']   ,ClassLabel(names=self.labels  )  )


class   __a(     _UpperCamelCase   ):






    """simple docstring"""





    def 							a__      (      self  ) ->		List[str]:
         UpperCAmelCase_			:							Dict   =			sorted(['''pos''', '''neg''']  )





    def 							a__      (      self  ) ->		Optional[int]:
         UpperCAmelCase_			:							Union[str, Any]   =			ImageClassification(image_column='''input_image'''   ,label_column='''input_label'''  )
         self.assertDictEqual({'''input_image''': '''image''', '''input_label''': '''labels'''}   ,task.column_mapping  )





    def 							a__      (      self  ) ->		Any:
         UpperCAmelCase_			:							Dict   =			Features({'''image''': Image()}  )
         UpperCAmelCase_			:							int   =			Features({'''labels''': ClassLabel}  )
         UpperCAmelCase_			:							Union[str, Any]   =			{
             '''image_column''': '''input_image''',
             '''label_column''': '''input_label''',
         }
         UpperCAmelCase_			:							Union[str, Any]   =			ImageClassification.from_dict(a__  )
         self.assertEqual('''image-classification'''   ,task.task  )
         self.assertEqual(a__   ,task.input_schema  )
         self.assertEqual(a__   ,task.label_schema  )





    def 							a__      (      self  ) ->		Tuple:
         UpperCAmelCase_			:							Optional[Any]   =			ImageClassification(image_column='''input_image'''   ,label_column='''input_label'''  )
         self.assertEqual(task.label_schema['''labels''']   ,a__  )
         UpperCAmelCase_			:							Dict   =			task.align_with_features(Features({'''input_label''': ClassLabel(names=self.labels  )}  )  )
         self.assertEqual(task.label_schema['''labels''']   ,ClassLabel(names=self.labels  )  )


class   __a(     _UpperCamelCase   ):






    """simple docstring"""





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

         def keep_task(_SCREAMING_SNAKE_CASE  ):
              return x

         def dont_keep_task(_SCREAMING_SNAKE_CASE  ):
              UpperCAmelCase_			:							Dict   =			deepcopy(a__  )
              UpperCAmelCase_			:							List[Any]   =			0
              return out

         UpperCAmelCase_			:							Dict   =			dataset.map(a__  )
         assert mapped_dataset.info.task_templates == dataset.info.task_templates
         # reload from cache
         UpperCAmelCase_			:							Tuple   =			dataset.map(a__  )
         assert mapped_dataset.info.task_templates == dataset.info.task_templates

         UpperCAmelCase_			:							List[Any]   =			dataset.map(a__  )
         assert mapped_dataset.info.task_templates == []
         # reload from cache
         UpperCAmelCase_			:							str   =			dataset.map(a__  )
         assert mapped_dataset.info.task_templates == []





    def 							a__      (      self  ) ->		Any:
         UpperCAmelCase_			:							Tuple   =			Features({'''text''': Value('''string'''  ), '''label''': ClassLabel(names=('''pos''', '''neg''')  )}  )
         UpperCAmelCase_			:							List[Any]   =			TextClassification(text_column='''text'''   ,label_column='''label'''  )
         UpperCAmelCase_			:							Dict   =			DatasetInfo(features=a__   ,task_templates=a__  )
         UpperCAmelCase_			:							Tuple   =			Dataset.from_dict({'''text''': ['''A sentence.'''], '''label''': ['''pos''']}   ,info=a__  )

         def process(_SCREAMING_SNAKE_CASE  ):
              return example

         UpperCAmelCase_			:							Tuple   =			dataset.remove_columns('''label'''  )
         UpperCAmelCase_			:							Optional[int]   =			modified_dataset.map(a__  )
         assert mapped_dataset.info.task_templates == []



"""simple docstring"""


import importlib
import inspect
from functools import wraps
from typing import TYPE_CHECKING, Optional, Union

from .download.streaming_download_manager import (
    xbasename,
    xdirname,
    xet_parse,
    xexists,
    xgetsize,
    xglob,
    xgzip_open,
    xisdir,
    xisfile,
    xjoin,
    xlistdir,
    xnumpy_load,
    xopen,
    xpandas_read_csv,
    xpandas_read_excel,
    xPath,
    xrelpath,
    xsio_loadmat,
    xsplit,
    xsplitext,
    xwalk,
    xxml_dom_minidom_parse,
)
from .utils.logging import get_logger
from .utils.patching import patch_submodule
from .utils.py_utils import get_imports


a_											=			get_logger(__name__)


if TYPE_CHECKING:
		from .builder import DatasetBuilder






def    a__       ( __lowercase   ,	__lowercase = None      )		->		Optional[Any]:
				_A         =	importlib.import_module(__lowercase      )

				# TODO(QL): always update the module to add subsequent new authentication
				if hasattr(__lowercase   ,	"_patched_for_streaming"      ) and module._patched_for_streaming:
								return

				def wrap_auth(__lowercase      ):
								@wraps(__lowercase      )
								def wrapper(*__lowercase   ,	**__lowercase      ):
												return function(*__lowercase   ,	use_auth_token=__lowercase   ,	**__lowercase      )

								_A         =	"wrap_auth"
								return wrapper

				# open files in a streaming fashion
				patch_submodule(__lowercase   ,	"open"   ,	wrap_auth(__lowercase      )      ).start()
				patch_submodule(__lowercase   ,	"os.listdir"   ,	wrap_auth(__lowercase      )      ).start()
				patch_submodule(__lowercase   ,	"os.walk"   ,	wrap_auth(__lowercase      )      ).start()
				patch_submodule(__lowercase   ,	"glob.glob"   ,	wrap_auth(__lowercase      )      ).start()
				# allow to navigate in remote zip files
				patch_submodule(__lowercase   ,	"os.path.join"   ,	__lowercase      ).start()
				patch_submodule(__lowercase   ,	"os.path.dirname"   ,	__lowercase      ).start()
				patch_submodule(__lowercase   ,	"os.path.basename"   ,	__lowercase      ).start()
				patch_submodule(__lowercase   ,	"os.path.relpath"   ,	__lowercase      ).start()
				patch_submodule(__lowercase   ,	"os.path.split"   ,	__lowercase      ).start()
				patch_submodule(__lowercase   ,	"os.path.splitext"   ,	__lowercase      ).start()
				# allow checks on paths
				patch_submodule(__lowercase   ,	"os.path.exists"   ,	wrap_auth(__lowercase      )      ).start()
				patch_submodule(__lowercase   ,	"os.path.isdir"   ,	wrap_auth(__lowercase      )      ).start()
				patch_submodule(__lowercase   ,	"os.path.isfile"   ,	wrap_auth(__lowercase      )      ).start()
				patch_submodule(__lowercase   ,	"os.path.getsize"   ,	wrap_auth(__lowercase      )      ).start()
				patch_submodule(__lowercase   ,	"pathlib.Path"   ,	__lowercase      ).start()
				# file readers
				patch_submodule(__lowercase   ,	"gzip.open"   ,	wrap_auth(__lowercase      )      ).start()
				patch_submodule(__lowercase   ,	"numpy.load"   ,	wrap_auth(__lowercase      )      ).start()
				patch_submodule(__lowercase   ,	"pandas.read_csv"   ,	wrap_auth(__lowercase      )   ,	attrs=["__version__"]      ).start()
				patch_submodule(__lowercase   ,	"pandas.read_excel"   ,	wrap_auth(__lowercase      )   ,	attrs=["__version__"]      ).start()
				patch_submodule(__lowercase   ,	"scipy.io.loadmat"   ,	wrap_auth(__lowercase      )   ,	attrs=["__version__"]      ).start()
				patch_submodule(__lowercase   ,	"xml.etree.ElementTree.parse"   ,	wrap_auth(__lowercase      )      ).start()
				patch_submodule(__lowercase   ,	"xml.dom.minidom.parse"   ,	wrap_auth(__lowercase      )      ).start()
				_A         =	True






def    a__       ( __lowercase      )		->		str:
				extend_module_for_streaming(builder.__module__   ,	use_auth_token=builder.use_auth_token      )
				# if needed, we also have to extend additional internal imports (like wmt14 -> wmt_utils)
				if not builder.__module__.startswith("datasets."      ):  # check that it's not a packaged builder like csv
								for imports in get_imports(inspect.getfile(builder.__class__      )      ):
												if imports[0] == "internal":
																_A         =	imports[1]
																_A         =	".".join(builder.__module__.split("."      )[:-1] + [internal_import_name]      )
																extend_module_for_streaming(__lowercase   ,	use_auth_token=builder.use_auth_token      )

    # builders can inherit from other builders that might use streaming functionality
    # (for example, ImageFolder and AudioFolder inherit from FolderBuilder which implements examples generation)
    # but these parents builders are not patched automatically as they are not instantiated, so we patch them here
				from .builder import DatasetBuilder

				_A         =	[
				    cls.__module__
				    for cls in type(__lowercase      ).__mro__[1:]  # make sure it's not the same module we've already patched
				    if issubclass(cls   ,	__lowercase      ) and cls.__module__ != DatasetBuilder.__module__
				]  # check it's not a standard builder from datasets.builder
				for module in parent_builder_modules:
								extend_module_for_streaming(__lowercase   ,	use_auth_token=builder.use_auth_token      )