



"""simple docstring"""






import re
import tempfile
import unittest
from pathlib import Path

from datasets.utils.metadata import DatasetMetadata


def 							A__ (     UpperCamelCase__    ):


  '''simple docstring'''


  _SCREAMING_SNAKE_CASE        =			min(re.search('''^ +'''       ,							SCREAMING_SNAKE_CASE__    ).end() if t.startswith(''' '''    ) else 0 for t in string.splitlines()    )
  return "\n".join([line[indent_level:] for line in string.splitlines() if indent_level < len(SCREAMING_SNAKE_CASE__    )]    )


lowerCamelCase				:     Dict								=  """\\n---\nlanguage:\n- zh\n- en\ntask_ids:\n- sentiment-classification\n---\n# Begin of markdown\n\nSome cool dataset card\n"""

lowerCamelCase				:     Tuple								=  """\\n---\n---\n# Begin of markdown\n\nSome cool dataset card\n"""


lowerCamelCase				:     Optional[Any]								=  """\\n# Begin of markdown\n\nSome cool dataset card\n"""







class    __snake_case(					unittest.TestCase       ):




    def   A   (   self			):





      '''simple docstring'''



      with tempfile.TemporaryDirectory() as tmp_dir:
        _SCREAMING_SNAKE_CASE        =			Path(lowercase_			) / '''README.md'''
        with open(lowercase_    ,							'''w+'''			) as readme_file:
          readme_file.write(lowercase_			)
        _SCREAMING_SNAKE_CASE        =			DatasetMetadata.from_readme(lowercase_			)
        self.assertDictEqual(lowercase_    ,							{'''language''': ['''zh''', '''en'''], '''task_ids''': ['''sentiment-classification''']}			)

        with open(lowercase_    ,							'''w+'''			) as readme_file:
          readme_file.write(lowercase_			)
        _SCREAMING_SNAKE_CASE        =			DatasetMetadata.from_readme(lowercase_			)
        self.assertDictEqual(lowercase_    ,							{}			)

        with open(lowercase_    ,							'''w+'''			) as readme_file:
          readme_file.write(lowercase_			)
        _SCREAMING_SNAKE_CASE        =			DatasetMetadata.from_readme(lowercase_			)
        self.assertEqual(lowercase_    ,							{}			)




    def   A   (   self			):





      '''simple docstring'''



      _SCREAMING_SNAKE_CASE        =			_dedent(
          '''\\n            annotations_creators:\n            - found\n            language_creators:\n            - found\n            language:\n            - en\n            license:\n            - unknown\n            multilinguality:\n            - monolingual\n            pretty_name: Test Dataset\n            size_categories:\n            - 10K<n<100K\n            source_datasets:\n            - extended|other-yahoo-webscope-l6\n            task_categories:\n            - question-answering\n            task_ids:\n            - open-domain-qa\n            '''			)
      assert DatasetMetadata.from_yaml_string(lowercase_			)

      _SCREAMING_SNAKE_CASE        =			_dedent(
          '''\\n            annotations_creators:\n            - found\n            language:\n            - en\n            license:\n            - unknown\n            multilinguality:\n            - monolingual\n            pretty_name: Test Dataset\n            size_categories:\n            - 10K<n<100K\n            source_datasets:\n            - extended|other-yahoo-webscope-l6\n            task_categories:\n            - question-answering\n            task_ids:\n            - open-domain-qa\n            task_ids:\n            - open-domain-qa\n            '''			)
      with self.assertRaises(lowercase_			):
        DatasetMetadata.from_yaml_string(lowercase_			)

      _SCREAMING_SNAKE_CASE        =			_dedent(
          '''\\n            annotations_creators:\n            - found\n            language_creators:\n            - found\n            language:\n            - en\n            license:\n            - unknown\n            multilinguality:\n            - monolingual\n            pretty_name: Test Dataset\n            size_categories:\n            - 10K<n<100K\n            source_datasets:\n            - extended|other-yahoo-webscope-l6\n            task_categories:\n            - text-classification\n            task_ids:\n            - multi-class-classification\n            paperswithcode_id:\n            - squad\n            configs:\n            - en\n            train-eval-index:\n            - config: en\n              task: text-classification\n              task_id: multi_class_classification\n              splits:\n                train_split: train\n                eval_split: test\n              col_mapping:\n                text: text\n                label: target\n              metrics:\n                - type: accuracy\n                  name: Accuracy\n            extra_gated_prompt: |\n              By clicking on “Access repository” below, you also agree to ImageNet Terms of Access:\n              [RESEARCHER_FULLNAME] (the "Researcher") has requested permission to use the ImageNet database (the "Database") at Princeton University and Stanford University. In exchange for such permission, Researcher hereby agrees to the following terms and conditions:\n              1. Researcher shall use the Database only for non-commercial research and educational purposes.\n            extra_gated_fields:\n              Company: text\n              Country: text\n              I agree to use this model for non-commerical use ONLY: checkbox\n            '''			)
      assert DatasetMetadata.from_yaml_string(lowercase_			)



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_									=    datasets.utils.logging.get_logger(__name__)


@dataclass
class 					A		(				datasets.BuilderConfig					):







    """simple docstring"""





    lowerCamelCase						      =				None
    lowerCamelCase						      =				None
    lowerCamelCase						      =				None
    lowerCamelCase						      =				True
    lowerCamelCase						      =				None
    lowerCamelCase						      =				None
    lowerCamelCase						      =				None
    lowerCamelCase						      =				1_00_00
    lowerCamelCase						      =				None


    def 		snake_case__	( self					:			Tuple						)->       Optional[int]:





        '''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 		snake_case__	( self					:			Dict,lowercase_					:			dict,lowercase_					:			Optional[datasets.Features] = None,)->       str:





        '''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(lowercase_,lowercase_						):
            if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
                import sqlalchemy

                if isinstance(lowercase_,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(lowercase_						)}: {sql}'						)
            else:
                raise TypeError(
                    F'Supported types for \'sql\' are string and sqlalchemy.sql.Selectable but got {type(lowercase_						)}: {sql}'						)
        A__        =  config_kwargs['con']
        if not isinstance(lowercase_,lowercase_						):
            A__        =  id(lowercase_						)
            logger.info(
                F'SQL connection \'con\' of type {type(lowercase_						)} couldn\'t be hashed properly. To enable hashing, specify \'con\' as URI string instead.'						)

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


    @property
    def 		snake_case__	( self					:			Union[str, Any]						)->       Any:





        '''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 					A		(				datasets.ArrowBasedBuilder					):







    """simple docstring"""





    lowerCamelCase						      =				SqlConfig


    def 		snake_case__	( self					:			Any						)->       Any:





        '''simple docstring'''







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


    def 		snake_case__	( self					:			Tuple,lowercase_					:			List[Any]						)->       Union[str, Any]:





        '''simple docstring'''







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


    def 		snake_case__	( self					:			Any,lowercase_					:			pa.Table						)->       pa.Table:





        '''simple docstring'''







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


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





        '''simple docstring'''







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

