




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


__magic_name__     :     Optional[Any]  							=					{
    """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 		a_       (   __lowerCAmelCase							):
		lowerCAmelCase__								=			task_cls()
		lowerCAmelCase__								=			asdict(UpperCamelCase__							)
		lowerCAmelCase__								=			task_template_from_dict(UpperCamelCase__							)
		assert task == reloaded





class 						SCREAMING_SNAKE_CASE__		:
					def 					A__			(	self  :		Union[str, Any]	):



							"""simple docstring"""
							lowerCAmelCase__								=			LanguageModeling(text_column='''input_text'''	)
							assert {"input_text": "text"} == task.column_mapping



					def 					A__			(	self  :		Dict	):



							"""simple docstring"""
							lowerCAmelCase__								=			Features({'''text''': Value('''string'''	)}	)
							lowerCAmelCase__								=			{'''text_column''': '''input_text'''}
							lowerCAmelCase__								=			LanguageModeling.from_dict(a_	)
							assert "language-modeling" == task.task
							assert input_schema == task.input_schema





class 						SCREAMING_SNAKE_CASE__		(_a ):
					def 					A__			(	self  :		Dict	):



							"""simple docstring"""
							lowerCAmelCase__								=			sorted(['''pos''', '''neg''']	)
					def 					A__			(	self  :		List[Any]	):



							"""simple docstring"""
							lowerCAmelCase__								=			TextClassification(text_column='''input_text'''					,	label_column='''input_label'''	)
							self.assertDictEqual({'''input_text''': '''text''', '''input_label''': '''labels'''}					,	task.column_mapping	)
					def 					A__			(	self  :		Optional[int]	):



							"""simple docstring"""
							lowerCAmelCase__								=			Features({'''text''': Value('''string'''	)}	)
							# Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
							lowerCAmelCase__								=			Features({'''labels''': ClassLabel}	)
							lowerCAmelCase__								=			{'''text_column''': '''input_text''', '''label_column''': '''input_labels'''}
							lowerCAmelCase__								=			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  :		List[str]	):



							"""simple docstring"""
							lowerCAmelCase__								=			TextClassification(text_column='''input_text'''					,	label_column='''input_label'''	)
							self.assertEqual(task.label_schema['''labels''']					,	a_	)
							lowerCAmelCase__								=			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__		(_a ):
					def 					A__			(	self  :		Union[str, Any]	):



							"""simple docstring"""
							lowerCAmelCase__								=			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	):



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





class 						SCREAMING_SNAKE_CASE__		(_a ):
					def 					A__			(	self  :		Optional[int]	):



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



					def 					A__			(	self  :		Dict	):



							"""simple docstring"""
							lowerCAmelCase__								=			Features({'''text''': Value('''string'''	)}	)
							lowerCAmelCase__								=			Features({'''summary''': Value('''string'''	)}	)
							lowerCAmelCase__								=			{'''text_column''': '''input_text''', '''summary_column''': '''input_summary'''}
							lowerCAmelCase__								=			Summarization.from_dict(a_	)
							self.assertEqual('''summarization'''					,	task.task	)
							self.assertEqual(a_					,	task.input_schema	)
							self.assertEqual(a_					,	task.label_schema	)





class 						SCREAMING_SNAKE_CASE__		(_a ):
					def 					A__			(	self  :		Any	):



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



					def 					A__			(	self  :		Dict	):



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





class 						SCREAMING_SNAKE_CASE__		(_a ):
					def 					A__			(	self  :		Any	):



							"""simple docstring"""
							lowerCAmelCase__								=			sorted(['''pos''', '''neg''']	)
					def 					A__			(	self  :		List[Any]	):



							"""simple docstring"""
							lowerCAmelCase__								=			AudioClassification(audio_column='''input_audio'''					,	label_column='''input_label'''	)
							self.assertDictEqual({'''input_audio''': '''audio''', '''input_label''': '''labels'''}					,	task.column_mapping	)
					def 					A__			(	self  :		Optional[int]	):



							"""simple docstring"""
							lowerCAmelCase__								=			Features({'''audio''': Audio()}	)
							lowerCAmelCase__								=			Features({'''labels''': ClassLabel}	)
							lowerCAmelCase__								=			{
							    '''audio_column''': '''input_image''',
							    '''label_column''': '''input_label''',
							}
							lowerCAmelCase__								=			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  :		Tuple	):



							"""simple docstring"""
							lowerCAmelCase__								=			AudioClassification(audio_column='''input_audio'''					,	label_column='''input_label'''	)
							self.assertEqual(task.label_schema['''labels''']					,	a_	)
							lowerCAmelCase__								=			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__		(_a ):
					def 					A__			(	self  :		Dict	):



							"""simple docstring"""
							lowerCAmelCase__								=			sorted(['''pos''', '''neg''']	)
					def 					A__			(	self  :		Dict	):



							"""simple docstring"""
							lowerCAmelCase__								=			ImageClassification(image_column='''input_image'''					,	label_column='''input_label'''	)
							self.assertDictEqual({'''input_image''': '''image''', '''input_label''': '''labels'''}					,	task.column_mapping	)
					def 					A__			(	self  :		List[str]	):



							"""simple docstring"""
							lowerCAmelCase__								=			Features({'''image''': Image()}	)
							lowerCAmelCase__								=			Features({'''labels''': ClassLabel}	)
							lowerCAmelCase__								=			{
							    '''image_column''': '''input_image''',
							    '''label_column''': '''input_label''',
							}
							lowerCAmelCase__								=			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  :		Any	):



							"""simple docstring"""
							lowerCAmelCase__								=			ImageClassification(image_column='''input_image'''					,	label_column='''input_label'''	)
							self.assertEqual(task.label_schema['''labels''']					,	a_	)
							lowerCAmelCase__								=			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__		(_a ):
					def 					A__			(	self  :		int	):



							"""simple docstring"""
							lowerCAmelCase__								=			DatasetInfo(task_templates=QuestionAnsweringExtractive()	)
							lowerCAmelCase__								=			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(__lowerCamelCase  :		Union[str, Any]	):
									return x

							def dont_keep_task(__lowerCamelCase  :		str	):
									lowerCAmelCase__								=			deepcopy(a_	)
									lowerCAmelCase__								=			0
									return out

							lowerCAmelCase__								=			dataset.map(a_	)
							assert mapped_dataset.info.task_templates == dataset.info.task_templates
							# reload from cache
							lowerCAmelCase__								=			dataset.map(a_	)
							assert mapped_dataset.info.task_templates == dataset.info.task_templates

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



					def 					A__			(	self  :		str	):



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

							def process(__lowerCamelCase  :		Tuple	):
									return example

							lowerCAmelCase__								=			dataset.remove_columns('''label'''	)
							lowerCAmelCase__								=			modified_dataset.map(a_	)
							assert mapped_dataset.info.task_templates == []







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


__magic_name__     :     List[Any]  							=					get_logger(__name__)


if TYPE_CHECKING:
      from .builder import DatasetBuilder
def 		a_       (   __lowerCAmelCase      ,   __lowerCAmelCase = None							):
  lowerCAmelCase__								=			importlib.import_module(__lowerCAmelCase							)

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

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

    lowerCAmelCase__								=			'''wrap_auth'''
    return wrapper

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




def 		a_       (   __lowerCAmelCase							):
  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":
        lowerCAmelCase__								=			imports[1]
        lowerCAmelCase__								=			'''.'''.join(builder.__module__.split('''.'''							)[:-1] + [internal_import_name]							)
        extend_module_for_streaming(__lowerCAmelCase      ,   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

  lowerCAmelCase__								=			[
      cls.__module__
      for cls in type(__lowerCAmelCase							).__mro__[1:]  # make sure it's not the same module we've already patched
      if issubclass(cls      ,   __lowerCAmelCase							) 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(__lowerCAmelCase      ,   use_auth_token=builder.use_auth_token							)

