




'''simple docstring'''





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     lowercase  ( datasets.BuilderConfig):
      __lowercase					=	None
      __lowercase					=	None
      __lowercase					=	None
      __lowercase					=	True
      __lowercase					=	None
      __lowercase					=	None
      __lowercase					=	None
      __lowercase					=	1_00_00
      __lowercase					=	None






      def  A__(self       )							-> str:






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






      def  A__(self			,	a__			,	a__ = None			,	)							-> Dict:
         SCREAMING_SNAKE_CASE__      :					Optional[int]							    =			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
         SCREAMING_SNAKE_CASE__      :					Tuple							    =			config_kwargs['''sql''']
         if not isinstance(__UpperCamelCase			,	__UpperCamelCase       ):
            if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
               import sqlalchemy

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

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






      @property
      def  A__(self       )							-> Any:
         SCREAMING_SNAKE_CASE__      :					int							    =			{
             '''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):
      __lowercase					=	SqlConfig






      def  A__(self       )							-> Tuple:
         return datasets.DatasetInfo(features=self.config.features       )






      def  A__(self			,	a__       )							-> int:
         return [datasets.SplitGenerator(name=datasets.Split.TRAIN			,	gen_kwargs={}       )]






      def  A__(self			,	a__       )							-> Tuple:






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






      def  A__(self       )							-> Optional[Any]:
         SCREAMING_SNAKE_CASE__      :					str							    =			self.config.chunksize
         SCREAMING_SNAKE_CASE__      :					Union[str, Any]							    =			pd.read_sql(
             self.config.sql			,	self.config.con			,	chunksize=__UpperCamelCase			,	**self.config.pd_read_sql_kwargs       )
         SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			[sql_reader] if chunksize is None else sql_reader
         for chunk_idx, df in enumerate(__UpperCamelCase       ):
            SCREAMING_SNAKE_CASE__      :					str							    =			pa.Table.from_pandas(__UpperCamelCase       )
            yield chunk_idx, self._cast_table(__UpperCamelCase       )







'''simple docstring'''

from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available


a__         =     {'''configuration_cvt''': ['''CVT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CvtConfig''']}


try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		a__         =     [
		    '''CVT_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''CvtForImageClassification''',
		    '''CvtModel''',
		    '''CvtPreTrainedModel''',
		]

try:
		if not is_tf_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		a__         =     [
		    '''TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''TFCvtForImageClassification''',
		    '''TFCvtModel''',
		    '''TFCvtPreTrainedModel''',
		]

if TYPE_CHECKING:
		from .configuration_cvt import CVT_PRETRAINED_CONFIG_ARCHIVE_MAP, CvtConfig

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_cvt import (
				    CVT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    CvtForImageClassification,
				    CvtModel,
				    CvtPreTrainedModel,
				)

		try:
				if not is_tf_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_tf_cvt import (
				    TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TFCvtForImageClassification,
				    TFCvtModel,
				    TFCvtPreTrainedModel,
				)


else:
		import sys

		a__         =     _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)