
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


SCREAMING_SNAKE_CASE__				=							{
    """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 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: List[str]     )	->		List[Any]:
				__lowercase								=   task_cls()
				__lowercase								=   asdict(SCREAMING_SNAKE_CASE     )
				__lowercase								=   task_template_from_dict(SCREAMING_SNAKE_CASE     )
				assert task == reloaded
class       A__  :





							def      a__					(					self    :  Tuple							)		->						Tuple:



											"""simple docstring"""


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





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



											"""simple docstring"""


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






class       A__  (		lowerCAmelCase__							):





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



											"""simple docstring"""


											__lowercase								=   sorted(['pos', 'neg']							)





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



											"""simple docstring"""


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





							def      a__					(					self    :  str							)		->						Any:



											"""simple docstring"""


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





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



											"""simple docstring"""


											__lowercase								=   TextClassification(text_column='input_text'	,					label_column='input_label'							)
											self.assertEqual(task.label_schema['labels']	,					_UpperCAmelCase							)
											__lowercase								=   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      a__					(					self    :  Optional[int]							)		->						Union[str, Any]:



											"""simple docstring"""


											__lowercase								=   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    :  Dict							)		->						List[str]:



											"""simple docstring"""


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






class       A__  (		lowerCAmelCase__							):





							def      a__					(					self    :  Tuple							)		->						List[Any]:



											"""simple docstring"""


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





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



											"""simple docstring"""


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






class       A__  (		lowerCAmelCase__							):





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



											"""simple docstring"""


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





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



											"""simple docstring"""


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






class       A__  (		lowerCAmelCase__							):





							def      a__					(					self    :  str							)		->						Any:



											"""simple docstring"""


											__lowercase								=   sorted(['pos', 'neg']							)





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



											"""simple docstring"""


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





							def      a__					(					self    :  Tuple							)		->						str:



											"""simple docstring"""


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





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



											"""simple docstring"""


											__lowercase								=   AudioClassification(audio_column='input_audio'	,					label_column='input_label'							)
											self.assertEqual(task.label_schema['labels']	,					_UpperCAmelCase							)
											__lowercase								=   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      a__					(					self    :  str							)		->						Tuple:



											"""simple docstring"""


											__lowercase								=   sorted(['pos', 'neg']							)





							def      a__					(					self    :  str							)		->						Tuple:



											"""simple docstring"""


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





							def      a__					(					self    :  str							)		->						Dict:



											"""simple docstring"""


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





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



											"""simple docstring"""


											__lowercase								=   ImageClassification(image_column='input_image'	,					label_column='input_label'							)
											self.assertEqual(task.label_schema['labels']	,					_UpperCAmelCase							)
											__lowercase								=   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      a__					(					self    :  Optional[Any]							)		->						List[Any]:



											"""simple docstring"""


											__lowercase								=   DatasetInfo(task_templates=QuestionAnsweringExtractive()							)
											__lowercase								=   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(_UpperCAmelCase    :  List[str]							):
															return x

											def dont_keep_task(_UpperCAmelCase    :  Tuple							):
															__lowercase								=   deepcopy(_UpperCAmelCase							)
															__lowercase								=   0
															return out

											__lowercase								=   dataset.map(_UpperCAmelCase							)
											assert mapped_dataset.info.task_templates == dataset.info.task_templates
											# reload from cache
											__lowercase								=   dataset.map(_UpperCAmelCase							)
											assert mapped_dataset.info.task_templates == dataset.info.task_templates

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





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



											"""simple docstring"""


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

											def process(_UpperCAmelCase    :  Union[str, Any]							):
															return example

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







import itertools
from dataclasses import dataclass
from io import StringIO
from typing import Optional

import pyarrow as pa

import datasets
from datasets.features.features import require_storage_cast
from datasets.table import table_cast


SCREAMING_SNAKE_CASE__				=							datasets.utils.logging.get_logger(__name__)
@dataclass
class       A__  (		datasets.BuilderConfig							):
							lowerCAmelCase__						:		Optional[datasets.Features]            =				None
							lowerCAmelCase__						:		str            =				"utf-8"
							lowerCAmelCase__						:		Optional[str]            =				None
							lowerCAmelCase__						:		int            =				10 << 20  # 10MB
							lowerCAmelCase__						:		bool            =				False
							lowerCAmelCase__						:		str            =				"line"






class       A__  (		datasets.ArrowBasedBuilder							):
							lowerCAmelCase__						:		Optional[int]            =				TextConfig





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



											"""simple docstring"""


											return datasets.DatasetInfo(features=self.config.features							)





							def      a__					(					self    :  Tuple	,					_UpperCAmelCase    :  str							)		->						List[str]:



											"""simple docstring"""


											if not self.config.data_files:
															raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}"""							)
											__lowercase								=   dl_manager.download_and_extract(self.config.data_files							)
											if isinstance(_UpperCAmelCase	,					(str, list, tuple)							):
															__lowercase								=   data_files
															if isinstance(_UpperCAmelCase	,					_UpperCAmelCase							):
																			__lowercase								=   [files]
															__lowercase								=   [dl_manager.iter_files(_UpperCAmelCase							) for file in files]
															return [datasets.SplitGenerator(name=datasets.Split.TRAIN	,					gen_kwargs={'files': files}							)]
											__lowercase								=   []
											for split_name, files in data_files.items():
															if isinstance(_UpperCAmelCase	,					_UpperCAmelCase							):
																			__lowercase								=   [files]
															__lowercase								=   [dl_manager.iter_files(_UpperCAmelCase							) for file in files]
															splits.append(datasets.SplitGenerator(name=_UpperCAmelCase	,					gen_kwargs={'files': files}							)							)
											return splits





							def      a__					(					self    :  int	,					_UpperCAmelCase    :  pa.Table							)		->						pa.Table:



											"""simple docstring"""


											if self.config.features is not None:
															__lowercase								=   self.config.features.arrow_schema
															if all(not require_storage_cast(_UpperCAmelCase							) for feature in self.config.features.values()							):
																			# cheaper cast
																			__lowercase								=   pa_table.cast(_UpperCAmelCase							)
															else:
																			# more expensive cast; allows str <-> int/float or str to Audio for example
																			__lowercase								=   table_cast(_UpperCAmelCase	,					_UpperCAmelCase							)
															return pa_table
											else:
															return pa_table.cast(pa.schema({'text': pa.string()}							)							)





							def      a__					(					self    :  Union[str, Any]	,					_UpperCAmelCase    :  Optional[Any]							)		->						List[Any]:



											"""simple docstring"""


											__lowercase								=   list(self.config.features							) if self.config.features is not None else ['text']
											for file_idx, file in enumerate(itertools.chain.from_iterable(_UpperCAmelCase							)							):
															# open in text mode, by default translates universal newlines ("\n", "\r\n" and "\r") into "\n"
															with open(_UpperCAmelCase	,					encoding=self.config.encoding	,					errors=self.config.errors							) as f:
																			if self.config.sample_by == "line":
																							__lowercase								=   0
																							while True:
																											__lowercase								=   f.read(self.config.chunksize							)
																											if not batch:
																															break
																											batch += f.readline()  # finish current line
																											# StringIO.readlines, by default splits only on "\n" (and keeps line breaks)
																											__lowercase								=   StringIO(_UpperCAmelCase							).readlines()
																											if not self.config.keep_linebreaks:
																															__lowercase								=   [line.rstrip('\n'							) for line in batch]
																											__lowercase								=   pa.Table.from_arrays([pa.array(_UpperCAmelCase							)]	,					names=_UpperCAmelCase							)
																											# Uncomment for debugging (will print the Arrow table size and elements)
																											# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
																											# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																											yield (file_idx, batch_idx), self._cast_table(_UpperCAmelCase							)
																											batch_idx += 1
																			elif self.config.sample_by == "paragraph":
																							__lowercase								=   0
																							__lowercase								=   ''
																							while True:
																											__lowercase								=   f.read(self.config.chunksize							)
																											if not new_batch:
																															break
																											batch += new_batch
																											batch += f.readline()  # finish current line
																											__lowercase								=   batch.split('\n\n'							)
																											__lowercase								=   pa.Table.from_arrays(
																											    [pa.array([example for example in batch[:-1] if example]							)]	,					names=_UpperCAmelCase							)
																											# Uncomment for debugging (will print the Arrow table size and elements)
																											# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
																											# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																											yield (file_idx, batch_idx), self._cast_table(_UpperCAmelCase							)
																											batch_idx += 1
																											__lowercase								=   batch[-1]
																							if batch:
																											__lowercase								=   pa.Table.from_arrays([pa.array([batch]							)]	,					names=_UpperCAmelCase							)
																											yield (file_idx, batch_idx), self._cast_table(_UpperCAmelCase							)
																			elif self.config.sample_by == "document":
																							__lowercase								=   f.read()
																							__lowercase								=   pa.Table.from_arrays([pa.array([text]							)]	,					names=_UpperCAmelCase							)
																							yield file_idx, self._cast_table(_UpperCAmelCase							)





