




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


SCREAMING_SNAKE_CASE_						:					Dict			   =       datasets.utils.logging.get_logger(__name__)







@dataclass
class 		__UpperCAmelCase(		datasets.BuilderConfig ):





     """simple docstring"""



     __UpperCAmelCase	: Union[str, "sqlalchemy.sql.Selectable"]						=    None
     __UpperCAmelCase	: Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]						=    None
     __UpperCAmelCase	: Optional[Union[str, List[str]]]						=    None
     __UpperCAmelCase	: bool						=    True
     __UpperCAmelCase	: Optional[Union[List, Tuple, Dict]]						=    None
     __UpperCAmelCase	: Optional[Union[List, Dict]]						=    None
     __UpperCAmelCase	: Optional[List[str]]						=    None
     __UpperCAmelCase	: Optional[int]						=    10000
     __UpperCAmelCase	: Optional[datasets.Features]						=    None

     def 				__SCREAMING_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 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]						,				A :       dict						,				A :       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(A						,				A    ):
             if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
                 import sqlalchemy

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

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






     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]    )			->			str:






         """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 		__UpperCAmelCase(		datasets.ArrowBasedBuilder ):





     """simple docstring"""



     __UpperCAmelCase	: Union[str, Any]						=    SqlConfig

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






         """simple docstring"""
         return datasets.DatasetInfo(features=self.config.features    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict						,				A :       str    )			->			Optional[int]:






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

     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]						,				A :       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(A    ) for feature in self.config.features.values()    ):
                 # cheaper cast
                 a__      =       pa.Table.from_arrays([pa_table[field.name] for field in schema]						,				schema=A    )
             else:
                 # more expensive cast; allows str <-> int/float or str to Audio for example
                 a__      =       table_cast(A						,				A    )
         return pa_table






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






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












import warnings
from dataclasses import dataclass, field
from typing import Optional, Tuple

from .training_args import TrainingArguments
from .utils import cached_property, is_tf_available, logging, requires_backends


SCREAMING_SNAKE_CASE_						:					Optional[Any]			   =       logging.get_logger(__name__)

if is_tf_available():
 import tensorflow as tf







@dataclass
class 		__UpperCAmelCase(		lowercase__ ):





     """simple docstring"""



     __UpperCAmelCase	: int						=    """tf"""
     __UpperCAmelCase	: Optional[str]						=    field(
         default=lowercase__       ,	metadata={"""help""": """Name of TPU"""}       ,	)

     __UpperCAmelCase	: Optional[str]						=    field(
         default=lowercase__       ,	metadata={"""help""": """Zone of TPU"""}       ,	)

     __UpperCAmelCase	: Optional[str]						=    field(
         default=lowercase__       ,	metadata={"""help""": """Name of Cloud TPU-enabled project"""}       ,	)

     __UpperCAmelCase	: float						=    field(
         default=1.0       ,	metadata={"""help""": """Power for the Polynomial decay LR scheduler."""}       ,	)

     __UpperCAmelCase	: bool						=    field(default=lowercase__       ,	metadata={"""help""": """Whether to activate the XLA compilation or not"""} )

     @cached_property
     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			Tuple["tf.distribute.Strategy", int]:






         """simple docstring"""
         requires_backends(self						,				["""tf"""]    )
         logger.info("""Tensorflow: setting up strategy"""    )

         a__      =       tf.config.list_physical_devices("""GPU"""    )

         # Set to float16 at first
         if self.fpaa:
             tf.keras.mixed_precision.set_global_policy("""mixed_float16"""    )

         if self.no_cuda:
             a__      =       tf.distribute.OneDeviceStrategy(device="""/cpu:0"""    )
         else:
             try:
                 if self.tpu_name:
                     a__      =       tf.distribute.cluster_resolver.TPUClusterResolver(
                         self.tpu_name						,				zone=self.tpu_zone						,				project=self.gcp_project    )
                 else:
                     a__      =       tf.distribute.cluster_resolver.TPUClusterResolver()
             except ValueError:
                 if self.tpu_name:
                     raise RuntimeError(f"""Couldn't connect to TPU {self.tpu_name}!"""    )
                 else:
                     a__      =       None

             if tpu:
                 # Set to bfloat16 in case of TPU
                 if self.fpaa:
                     tf.keras.mixed_precision.set_global_policy("""mixed_bfloat16"""    )

                 tf.config.experimental_connect_to_cluster(A    )
                 tf.tpu.experimental.initialize_tpu_system(A    )

                 a__      =       tf.distribute.TPUStrategy(A    )

             elif len(A    ) == 0:
                 a__      =       tf.distribute.OneDeviceStrategy(device="""/cpu:0"""    )
             elif len(A    ) == 1:
                 a__      =       tf.distribute.OneDeviceStrategy(device="""/gpu:0"""    )
             elif len(A    ) > 1:
                 # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
                 a__      =       tf.distribute.MirroredStrategy()
             else:
                 raise ValueError("""Cannot find the proper strategy, please check your environment properties."""    )

         return strategy

     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       Tuple    )			->			"tf.distribute.Strategy":






         """simple docstring"""
         requires_backends(self						,				["""tf"""]    )
         return self._setup_strategy

     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			int:






         """simple docstring"""
         requires_backends(self						,				["""tf"""]    )
         return self._setup_strategy.num_replicas_in_sync

     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			List[Any]:






         """simple docstring"""
         return False  # TF Logging is handled by Keras not the Trainer

     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]    )			->			int:






         """simple docstring"""
         if self.per_gpu_train_batch_size:
             logger.warning(
                 """Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future """
                 """version. Using `--per_device_train_batch_size` is preferred."""    )
         a__      =       self.per_gpu_train_batch_size or self.per_device_train_batch_size
         return per_device_batch_size * self.n_replicas

     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       List[str]    )			->			int:






         """simple docstring"""
         if self.per_gpu_eval_batch_size:
             logger.warning(
                 """Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future """
                 """version. Using `--per_device_eval_batch_size` is preferred."""    )
         a__      =       self.per_gpu_eval_batch_size or self.per_device_eval_batch_size
         return per_device_batch_size * self.n_replicas






     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       str    )			->			int:






         """simple docstring"""
         requires_backends(self						,				["""tf"""]    )
         warnings.warn(
             """The n_gpu argument is deprecated and will be removed in a future version, use n_replicas instead."""						,				A						,				)
         return self._setup_strategy.num_replicas_in_sync






