



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


_lowercase:					str      =						{
    "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        a( A			:       Union[str, Any]			)						->			Dict:
					"""simple docstring"""





					a   	=  task_cls()
					a   	=  asdict(A			)
					a   	=  task_template_from_dict(A			)
					assert task == reloaded



class       _lowercase				:





	"""simple docstring"""




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




class       _lowercase				(  lowerCAmelCase      ):





	"""simple docstring"""




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




class       _lowercase				(  lowerCAmelCase      ):





	"""simple docstring"""




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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

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




class       _lowercase				(  lowerCAmelCase      ):





	"""simple docstring"""




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




class       _lowercase				(  lowerCAmelCase      ):





	"""simple docstring"""




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




class       _lowercase				(  lowerCAmelCase      ):





	"""simple docstring"""




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




class       _lowercase				(  lowerCAmelCase      ):





	"""simple docstring"""




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




class       _lowercase				(  lowerCAmelCase      ):





	"""simple docstring"""




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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

						def keep_task(lowerCamelCase_						):
											return x

						def dont_keep_task(lowerCamelCase_						):
											a   	=  deepcopy(lowerCamelCase_						)
											a   	=  0
											return out

						a   	=  dataset.map(lowerCamelCase_						)
						assert mapped_dataset.info.task_templates == dataset.info.task_templates
						# reload from cache
						a   	=  dataset.map(lowerCamelCase_						)
						assert mapped_dataset.info.task_templates == dataset.info.task_templates

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




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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

						def process(lowerCamelCase_						):
											return example

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





import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union

import pandas as pd
import pyarrow as pa

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


if TYPE_CHECKING:
				import sqlitea

				import sqlalchemy


_lowercase:					Optional[Any]      =						datasets.utils.logging.get_logger(__name__)



@dataclass
class       _lowercase				(  datasets.BuilderConfig      ):





	"""simple docstring"""
	__A		      =				None
	__A		      =				None
	__A		      =				None
	__A		      =				True
	__A		      =				None
	__A		      =				None
	__A		      =				None
	__A		      =				10000
	__A		      =				None




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

						if self.sql is None:
											raise ValueError("sql must be specified"						)
						if self.con is None:
											raise ValueError("con must be specified"						)




	def 	UpperCamelCase_			(self						,			lowerCamelCase_						,			lowerCamelCase_ = None						,			):
						"""simple docstring"""

						a   	=  config_kwargs.copy()
						# We need to stringify the Selectable object to make its hash deterministic

						# The process of stringifying is explained here: http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
						a   	=  config_kwargs["sql"]
						if not isinstance(lowerCamelCase_						,			lowerCamelCase_						):
											if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
																import sqlalchemy

																if isinstance(lowerCamelCase_						,			sqlalchemy.sql.Selectable						):
																					a   	=  sqlalchemy.create_engine(config_kwargs["con"].split("://"						)[0] + "://"						)
																					a   	=  str(sql.compile(dialect=engine.dialect						)						)
																					a   	=  sql_str
																else:
																					raise TypeError(
																					    F'''Supported types for \'sql\' are string and sqlalchemy.sql.Selectable but got {type(lowerCamelCase_						)}: {sql}'''						)
											else:
																raise TypeError(
																    F'''Supported types for \'sql\' are string and sqlalchemy.sql.Selectable but got {type(lowerCamelCase_						)}: {sql}'''						)
						a   	=  config_kwargs["con"]
						if not isinstance(lowerCamelCase_						,			lowerCamelCase_						):
											a   	=  id(lowerCamelCase_						)
											logger.info(
											    F'''SQL connection \'con\' of type {type(lowerCamelCase_						)} couldn\'t be hashed properly. To enable hashing, specify \'con\' as URI string instead.'''						)

						return super().create_config_id(lowerCamelCase_						,			custom_features=lowerCamelCase_						)




	@property
	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

						a   	=  {
						    "index_col": self.index_col,
						    "columns": self.columns,
						    "params": self.params,
						    "coerce_float": self.coerce_float,
						    "parse_dates": self.parse_dates,
						}
						return pd_read_sql_kwargs




class       _lowercase				(  datasets.ArrowBasedBuilder      ):





	"""simple docstring"""
	__A		      =				SqlConfig




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						,			lowerCamelCase_						):
						"""simple docstring"""

						return [datasets.SplitGenerator(name=datasets.Split.TRAIN						,			gen_kwargs={}						)]




	def 	UpperCamelCase_			(self						,			lowerCamelCase_						):
						"""simple docstring"""

						if self.config.features is not None:
											a   	=  self.config.features.arrow_schema
											if all(not require_storage_cast(lowerCamelCase_						) for feature in self.config.features.values()						):
																# cheaper cast
																a   	=  pa.Table.from_arrays([pa_table[field.name] for field in schema]						,			schema=lowerCamelCase_						)
											else:
																# more expensive cast; allows str <-> int/float or str to Audio for example
																a   	=  table_cast(lowerCamelCase_						,			lowerCamelCase_						)
						return pa_table




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

						a   	=  self.config.chunksize
						a   	=  pd.read_sql(
						    self.config.sql						,			self.config.con						,			chunksize=lowerCamelCase_						,			**self.config.pd_read_sql_kwargs						)
						a   	=  [sql_reader] if chunksize is None else sql_reader
						for chunk_idx, df in enumerate(lowerCamelCase_						):
											a   	=  pa.Table.from_pandas(lowerCamelCase_						)
											yield chunk_idx, self._cast_table(lowerCamelCase_						)
