
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__     :    Optional[Any]      							=					datasets.utils.logging.get_logger(__name__)

@dataclass
class      lowerCAmelCase__  (			datasets.BuilderConfig    ):
  a__ :		Union[str, "sqlalchemy.sql.Selectable"]   						=	None
  a__ :		Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]   						=	None
  a__ :		Optional[Union[str, List[str]]]   						=	None
  a__ :		bool   						=	True
  a__ :		Optional[Union[List, Tuple, Dict]]   						=	None
  a__ :		Optional[Union[List, Dict]]   						=	None
  a__ :		Optional[List[str]]   						=	None
  a__ :		Optional[int]   						=	10_000
  a__ :		Optional[datasets.Features]   						=	None






  def 				__A (	self	:							Dict						)  ->							Tuple:



      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	:							Optional[Any]							,    SCREAMING_SNAKE_CASE__	:							str							,    SCREAMING_SNAKE_CASE__	:							List[str] = None							,    )  ->							str:
      __lowerCamelCase					      =			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
      __lowerCamelCase					      =			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						):
                  __lowerCamelCase					      =			sqlalchemy.create_engine(config_kwargs['''con'''].split('''://'''						)[0] + '''://'''						)
                  __lowerCamelCase					      =			str(sql.compile(dialect=engine.dialect						)						)
                  __lowerCamelCase					      =			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}'''						)
      __lowerCamelCase					      =			config_kwargs['''con''']
      if not isinstance(lowerCamelCase__							,    lowerCamelCase__						):
          __lowerCamelCase					      =			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 				__A (	self	:							Optional[int]						)  ->							Union[str, Any]:
      __lowerCamelCase					      =			{
          '''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      lowerCAmelCase__  (			datasets.ArrowBasedBuilder    ):
  a__ :		Optional[Any]   						=	SqlConfig






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






  def 				__A (	self	:							Dict							,    SCREAMING_SNAKE_CASE__	:							List[Any]						)  ->							List[Any]:
      return [datasets.SplitGenerator(name=datasets.Split.TRAIN							,    gen_kwargs={}						)]






  def 				__A (	self	:							str							,    SCREAMING_SNAKE_CASE__	:							Optional[int]						)  ->							pa.Table:



      if self.config.features is not None:
          __lowerCamelCase					      =			self.config.features.arrow_schema
          if all(not require_storage_cast(lowerCamelCase__						) for feature in self.config.features.values()						):
              # cheaper cast
              __lowerCamelCase					      =			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
              __lowerCamelCase					      =			table_cast(lowerCamelCase__							,    lowerCamelCase__						)
      return pa_table







  def 				__A (	self	:							Any						)  ->							List[Any]:
      __lowerCamelCase					      =			self.config.chunksize
      __lowerCamelCase					      =			pd.read_sql(
          self.config.sql							,    self.config.con							,    chunksize=lowerCamelCase__							,    **self.config.pd_read_sql_kwargs						)
      __lowerCamelCase					      =			[sql_reader] if chunksize is None else sql_reader
      for chunk_idx, df in enumerate(lowerCamelCase__						):
          __lowerCamelCase					      =			pa.Table.from_pandas(lowerCamelCase__						)
          yield chunk_idx, self._cast_table(lowerCamelCase__						)





from ..utils import deprecate
from .attention_processor import (  # noqa: F401
    Attention,
    AttentionProcessor,
    AttnAddedKVProcessor,
    AttnProcessor2_0,
    LoRAAttnProcessor,
    LoRALinearLayer,
    LoRAXFormersAttnProcessor,
    SlicedAttnAddedKVProcessor,
    SlicedAttnProcessor,
    XFormersAttnProcessor,
)
from .attention_processor import AttnProcessor as AttnProcessorRename  # noqa: F401


deprecate(
    "cross_attention",
    "0.20.0",
    "Importing from cross_attention is deprecated. Please import from diffusers.models.attention_processor instead.",
    standard_warn=False,
)


SCREAMING_SNAKE_CASE__     :    Optional[int]      							=					AttentionProcessor

class      lowerCAmelCase__  (			__lowercase    ):






		def __init__(	self	:							Tuple							,    *SCREAMING_SNAKE_CASE__	:							Dict							,    **SCREAMING_SNAKE_CASE__	:							int						)  ->							List[Any]:
						__lowerCamelCase					      =			f'''{self.__class__.__name__} is deprecated and will be removed in `0.20.0`. Please use `from diffusers.models.attention_processor import {''.join(self.__class__.__name__.split('Cross'						)						)} instead.'''
						deprecate('''cross_attention'''							,    '''0.20.0'''							,    SCREAMING_SNAKE_CASE__							,    standard_warn=SCREAMING_SNAKE_CASE__						)
						super().__init__(*SCREAMING_SNAKE_CASE__							,    **SCREAMING_SNAKE_CASE__						)





class      lowerCAmelCase__  (			__lowercase    ):






		def __init__(	self	:							str							,    *SCREAMING_SNAKE_CASE__	:							Optional[Any]							,    **SCREAMING_SNAKE_CASE__	:							Optional[int]						)  ->							Optional[Any]:
						__lowerCamelCase					      =			f'''{self.__class__.__name__} is deprecated and will be removed in `0.20.0`. Please use `from diffusers.models.attention_processor import {''.join(self.__class__.__name__.split('Cross'						)						)} instead.'''
						deprecate('''cross_attention'''							,    '''0.20.0'''							,    SCREAMING_SNAKE_CASE__							,    standard_warn=SCREAMING_SNAKE_CASE__						)
						super().__init__(*SCREAMING_SNAKE_CASE__							,    **SCREAMING_SNAKE_CASE__						)





class      lowerCAmelCase__  (			__lowercase    ):






		def __init__(	self	:							str							,    *SCREAMING_SNAKE_CASE__	:							List[Any]							,    **SCREAMING_SNAKE_CASE__	:							List[str]						)  ->							List[Any]:
						__lowerCamelCase					      =			f'''{self.__class__.__name__} is deprecated and will be removed in `0.20.0`. Please use `from diffusers.models.attention_processor import {''.join(self.__class__.__name__.split('Cross'						)						)} instead.'''
						deprecate('''cross_attention'''							,    '''0.20.0'''							,    SCREAMING_SNAKE_CASE__							,    standard_warn=SCREAMING_SNAKE_CASE__						)
						super().__init__(*SCREAMING_SNAKE_CASE__							,    **SCREAMING_SNAKE_CASE__						)





class      lowerCAmelCase__  (			__lowercase    ):






		def __init__(	self	:							Optional[int]							,    *SCREAMING_SNAKE_CASE__	:							Optional[int]							,    **SCREAMING_SNAKE_CASE__	:							Tuple						)  ->							Optional[Any]:
						__lowerCamelCase					      =			f'''{self.__class__.__name__} is deprecated and will be removed in `0.20.0`. Please use `from diffusers.models.attention_processor import {''.join(self.__class__.__name__.split('Cross'						)						)} instead.'''
						deprecate('''cross_attention'''							,    '''0.20.0'''							,    SCREAMING_SNAKE_CASE__							,    standard_warn=SCREAMING_SNAKE_CASE__						)
						super().__init__(*SCREAMING_SNAKE_CASE__							,    **SCREAMING_SNAKE_CASE__						)





class      lowerCAmelCase__  (			__lowercase    ):






		def __init__(	self	:							Optional[Any]							,    *SCREAMING_SNAKE_CASE__	:							int							,    **SCREAMING_SNAKE_CASE__	:							Optional[Any]						)  ->							List[str]:
						__lowerCamelCase					      =			f'''{self.__class__.__name__} is deprecated and will be removed in `0.20.0`. Please use `from diffusers.models.attention_processor import {''.join(self.__class__.__name__.split('Cross'						)						)} instead.'''
						deprecate('''cross_attention'''							,    '''0.20.0'''							,    SCREAMING_SNAKE_CASE__							,    standard_warn=SCREAMING_SNAKE_CASE__						)
						super().__init__(*SCREAMING_SNAKE_CASE__							,    **SCREAMING_SNAKE_CASE__						)





class      lowerCAmelCase__  (			__lowercase    ):






		def __init__(	self	:							Tuple							,    *SCREAMING_SNAKE_CASE__	:							Tuple							,    **SCREAMING_SNAKE_CASE__	:							Any						)  ->							Union[str, Any]:
						__lowerCamelCase					      =			f'''{self.__class__.__name__} is deprecated and will be removed in `0.20.0`. Please use `from diffusers.models.attention_processor import {''.join(self.__class__.__name__.split('Cross'						)						)} instead.'''
						deprecate('''cross_attention'''							,    '''0.20.0'''							,    SCREAMING_SNAKE_CASE__							,    standard_warn=SCREAMING_SNAKE_CASE__						)
						super().__init__(*SCREAMING_SNAKE_CASE__							,    **SCREAMING_SNAKE_CASE__						)





class      lowerCAmelCase__  (			__lowercase    ):






		def __init__(	self	:							str							,    *SCREAMING_SNAKE_CASE__	:							Union[str, Any]							,    **SCREAMING_SNAKE_CASE__	:							Tuple						)  ->							int:
						__lowerCamelCase					      =			f'''{self.__class__.__name__} is deprecated and will be removed in `0.20.0`. Please use `from diffusers.models.attention_processor import {''.join(self.__class__.__name__.split('Cross'						)						)} instead.'''
						deprecate('''cross_attention'''							,    '''0.20.0'''							,    SCREAMING_SNAKE_CASE__							,    standard_warn=SCREAMING_SNAKE_CASE__						)
						super().__init__(*SCREAMING_SNAKE_CASE__							,    **SCREAMING_SNAKE_CASE__						)





class      lowerCAmelCase__  (			__lowercase    ):






		def __init__(	self	:							Optional[Any]							,    *SCREAMING_SNAKE_CASE__	:							Any							,    **SCREAMING_SNAKE_CASE__	:							str						)  ->							Dict:
						__lowerCamelCase					      =			f'''{self.__class__.__name__} is deprecated and will be removed in `0.20.0`. Please use `from diffusers.models.attention_processor import {''.join(self.__class__.__name__.split('Cross'						)						)} instead.'''
						deprecate('''cross_attention'''							,    '''0.20.0'''							,    SCREAMING_SNAKE_CASE__							,    standard_warn=SCREAMING_SNAKE_CASE__						)
						super().__init__(*SCREAMING_SNAKE_CASE__							,    **SCREAMING_SNAKE_CASE__						)



